Merge origin/master

This commit is contained in:
LevelX2 2017-02-06 21:21:16 +01:00
commit b8cc0120cb
737 changed files with 1701 additions and 1729 deletions

View file

@ -795,7 +795,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
try { try {
LOGGER.debug("connecting (auto): " + currentConnection.getProxyType().toString() LOGGER.debug("connecting (auto): " + currentConnection.getProxyType().toString()
+ " " + currentConnection.getProxyHost() + " " + currentConnection.getProxyPort() + " " + currentConnection.getProxyUsername()); + ' ' + currentConnection.getProxyHost() + ' ' + currentConnection.getProxyPort() + ' ' + currentConnection.getProxyUsername());
if (MageFrame.connect(currentConnection)) { if (MageFrame.connect(currentConnection)) {
showGames(false); showGames(false);
return true; return true;
@ -1334,7 +1334,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
hideTables(); hideTables();
SessionHandler.disconnect(false); SessionHandler.disconnect(false);
if (errorCall) { if (errorCall) {
UserRequestMessage message = new UserRequestMessage("Connection lost", "The connection to server was lost. Reconnect to " + currentConnection.getHost() + "?"); UserRequestMessage message = new UserRequestMessage("Connection lost", "The connection to server was lost. Reconnect to " + currentConnection.getHost() + '?');
message.setButton1("No", null); message.setButton1("No", null);
message.setButton2("Yes", PlayerAction.CLIENT_RECONNECT); message.setButton2("Yes", PlayerAction.CLIENT_RECONNECT);
showUserRequestDialog(message); showUserRequestDialog(message);

View file

@ -141,7 +141,7 @@ public class BigCard extends JComponent {
try { try {
for (String line : strings) { for (String line : strings) {
doc.insertString(doc.getLength(), line + "\n", doc.getStyle("regular")); doc.insertString(doc.getLength(), line + '\n', doc.getStyle("regular"));
} }
} catch (BadLocationException ble) { } catch (BadLocationException ble) {
} }

View file

@ -181,7 +181,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gImage.setColor(Color.BLACK); gImage.setColor(Color.BLACK);
gImage.drawImage(background, 0, 0, this); gImage.drawImage(background, 0, 0, this);
if (card.getManaCost().size() > 0) { if (!card.getManaCost().isEmpty()) {
ImageHelper.drawCosts(card.getManaCost(), gImage, FRAME_MAX_WIDTH - SYMBOL_MAX_XOFFSET, SYMBOL_MAX_YOFFSET, this); ImageHelper.drawCosts(card.getManaCost(), gImage, FRAME_MAX_WIDTH - SYMBOL_MAX_XOFFSET, SYMBOL_MAX_YOFFSET, this);
} }
@ -192,12 +192,12 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gImage.setFont(new Font("Arial", Font.PLAIN, NAME_FONT_MAX_SIZE)); gImage.setFont(new Font("Arial", Font.PLAIN, NAME_FONT_MAX_SIZE));
gImage.drawString(card.getName()+"TEST", CONTENT_MAX_XOFFSET, NAME_MAX_YOFFSET); gImage.drawString(card.getName()+"TEST", CONTENT_MAX_XOFFSET, NAME_MAX_YOFFSET);
if (card.getCardTypes().contains(CardType.CREATURE)) { if (card.getCardTypes().contains(CardType.CREATURE)) {
gImage.drawString(card.getPower() + "/" + card.getToughness(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP); gImage.drawString(card.getPower() + '/' + card.getToughness(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP);
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) { } else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
gImage.drawString(card.getLoyalty(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP); gImage.drawString(card.getLoyalty(), POWBOX_TEXT_MAX_LEFT, POWBOX_TEXT_MAX_TOP);
} }
if (card.getCardTypes().size() > 0) { if (!card.getCardTypes().isEmpty()) {
gImage.drawString(cardType, CONTENT_MAX_XOFFSET, TYPE_MAX_YOFFSET); gImage.drawString(cardType, CONTENT_MAX_XOFFSET, TYPE_MAX_YOFFSET);
} }
@ -211,7 +211,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gSmall.drawString(card.getLoyalty(), Config.dimensions.powBoxTextLeft, Config.dimensions.powBoxTextTop); gSmall.drawString(card.getLoyalty(), Config.dimensions.powBoxTextLeft, Config.dimensions.powBoxTextTop);
} }
if (card.getCardTypes().size() > 0) { if (!card.getCardTypes().isEmpty()) {
gSmall.drawString(cardType, Config.dimensions.contentXOffset, Config.dimensions.typeYOffset); gSmall.drawString(cardType, Config.dimensions.contentXOffset, Config.dimensions.typeYOffset);
} }
drawText(); drawText();
@ -228,27 +228,27 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (card instanceof StackAbilityView || card instanceof AbilityView) { if (card instanceof StackAbilityView || card instanceof AbilityView) {
for (String rule : getRules()) { for (String rule : getRules()) {
sb.append("\n").append(rule); sb.append('\n').append(rule);
} }
} else { } else {
sb.append(card.getName()); sb.append(card.getName());
if (card.getManaCost().size() > 0) { if (!card.getManaCost().isEmpty()) {
sb.append("\n").append(card.getManaCost()); sb.append('\n').append(card.getManaCost());
} }
sb.append("\n").append(cardType); sb.append('\n').append(cardType);
if (card.getColor().hasColor()) { if (card.getColor().hasColor()) {
sb.append("\n").append(card.getColor().toString()); sb.append('\n').append(card.getColor().toString());
} }
if (card.getCardTypes().contains(CardType.CREATURE)) { if (card.getCardTypes().contains(CardType.CREATURE)) {
sb.append("\n").append(card.getPower()).append("/").append(card.getToughness()); sb.append('\n').append(card.getPower()).append('/').append(card.getToughness());
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) { } else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
sb.append("\n").append(card.getLoyalty()); sb.append('\n').append(card.getLoyalty());
} }
for (String rule : getRules()) { for (String rule : getRules()) {
sb.append("\n").append(rule); sb.append('\n').append(rule);
} }
if (card.getExpansionSetCode() != null && card.getExpansionSetCode().length() > 0) { if (card.getExpansionSetCode() != null && !card.getExpansionSetCode().isEmpty()) {
sb.append("\n").append(card.getCardNumber()).append(" - "); sb.append('\n').append(card.getCardNumber()).append(" - ");
sb.append(Sets.getInstance().get(card.getExpansionSetCode()).getName()).append(" - "); sb.append(Sets.getInstance().get(card.getExpansionSetCode()).getName()).append(" - ");
sb.append(card.getRarity().toString()); sb.append(card.getRarity().toString());
} }
@ -277,7 +277,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
try { try {
for (String rule : getRules()) { for (String rule : getRules()) {
doc.insertString(doc.getLength(), rule + "\n", doc.getStyle("small")); doc.insertString(doc.getLength(), rule + '\n', doc.getStyle("small"));
} }
} catch (BadLocationException e) { } catch (BadLocationException e) {
} }
@ -301,17 +301,17 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StringBuilder sbType = new StringBuilder(); StringBuilder sbType = new StringBuilder();
for (String superType : card.getSuperTypes()) { for (String superType : card.getSuperTypes()) {
sbType.append(superType).append(" "); sbType.append(superType).append(' ');
} }
for (CardType cardType : card.getCardTypes()) { for (CardType cardType : card.getCardTypes()) {
sbType.append(cardType.toString()).append(" "); sbType.append(cardType.toString()).append(' ');
} }
if (card.getSubTypes().size() > 0) { if (!card.getSubTypes().isEmpty()) {
sbType.append("- "); sbType.append("- ");
for (String subType : card.getSubTypes()) { for (String subType : card.getSubTypes()) {
sbType.append(subType).append(" "); sbType.append(subType).append(' ');
} }
} }

View file

@ -163,7 +163,7 @@ public class CardArea extends JPanel implements MouseListener {
private void loadCardsMany(CardsView showCards, BigCard bigCard, UUID gameId) { private void loadCardsMany(CardsView showCards, BigCard bigCard, UUID gameId) {
int rowsOfCards = 20; int rowsOfCards = 20;
int columns = 1; int columns = 1;
if (showCards != null && showCards.size() > 0) { if (showCards != null && !showCards.isEmpty()) {
Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height); Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height);
int count = 0; int count = 0;
for (CardView card : showCards.values()) { for (CardView card : showCards.values()) {

View file

@ -225,7 +225,7 @@ public class Cards extends javax.swing.JPanel {
} }
if (!isVisibleIfEmpty) { if (!isVisibleIfEmpty) {
cardArea.setVisible(cards.size() > 0); cardArea.setVisible(!cards.isEmpty());
} }
sizeCards(getCardDimension()); sizeCards(getCardDimension());

View file

@ -322,7 +322,7 @@ public class CardsList extends javax.swing.JPanel implements MouseListener, ICar
cardArea.remove(card); cardArea.remove(card);
} }
if (cards != null && cards.size() > 0) { if (cards != null && !cards.isEmpty()) {
Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height); Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height);
List<CardView> sortedCards = new ArrayList<>(cards.values()); List<CardView> sortedCards = new ArrayList<>(cards.values());
switch (sortSetting.getSortBy()) { switch (sortSetting.getSortBy()) {

View file

@ -708,7 +708,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
@Override @Override
public String toString() { public String toString() {
return "(" + sort.toString() + "," + Boolean.toString(separateCreatures) + "," + Integer.toString(cardSize) + ")"; return '(' + sort.toString() + ',' + Boolean.toString(separateCreatures) + ',' + Integer.toString(cardSize) + ')';
} }
} }
@ -1077,7 +1077,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
for (Sort s : sortMenuItems.keySet()) { for (Sort s : sortMenuItems.keySet()) {
sortMenuItems.get(s).setSelected(cardSort == s); sortMenuItems.get(s).setSelected(cardSort == s);
} }
hideSelected.setEnabled(dragCardList().size() > 0); hideSelected.setEnabled(!dragCardList().isEmpty());
separateButton.setSelected(separateCreatures); separateButton.setSelected(separateCreatures);
menu.show(e.getComponent(), e.getX(), e.getY()); menu.show(e.getComponent(), e.getX(), e.getY());
} }
@ -1327,7 +1327,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
if (!s) { if (!s) {
String t = ""; String t = "";
for (CardType type : card.getCardTypes()) { for (CardType type : card.getCardTypes()) {
t += " " + type.toString(); t += ' ' + type.toString();
} }
s |= t.toLowerCase().contains(searchStr); s |= t.toLowerCase().contains(searchStr);
} }
@ -1385,14 +1385,14 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
// Type line // Type line
String t = ""; String t = "";
for (CardType type : card.getCardTypes()) { for (CardType type : card.getCardTypes()) {
t += " " + type.toString(); t += ' ' + type.toString();
} }
// Sub & Super Types // Sub & Super Types
for (String str : card.getSuperTypes()) { for (String str : card.getSuperTypes()) {
t += " " + str.toLowerCase(); t += ' ' + str.toLowerCase();
} }
for (String str : card.getSubTypes()) { for (String str : card.getSubTypes()) {
t += " " + str.toLowerCase(); t += ' ' + str.toLowerCase();
} }
for (String qty : qtys.keySet()) { for (String qty : qtys.keySet()) {
@ -1534,7 +1534,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
List<CardInfo> cardPool = CardRepository.instance.findCards(cardCriteria); List<CardInfo> cardPool = CardRepository.instance.findCards(cardCriteria);
if (cardPool.size() > 0) { if (!cardPool.isEmpty()) {
Card acard = cardPool.get(RandomUtil.nextInt(cardPool.size())).getMockCard(); Card acard = cardPool.get(RandomUtil.nextInt(cardPool.size())).getMockCard();
if (acard.getName().equals(card.getName())) { if (acard.getName().equals(card.getName())) {
@ -1656,7 +1656,7 @@ public class DragCardGrid extends JPanel implements DragCardSource, DragCardTarg
if (trackedCards.containsKey(info.getSetCode()) && trackedCards.get(info.getSetCode()).containsKey(info.getCardNum())) { if (trackedCards.containsKey(info.getSetCode()) && trackedCards.get(info.getSetCode()).containsKey(info.getCardNum())) {
ArrayList<CardView> candidates ArrayList<CardView> candidates
= trackedCards.get(info.getSetCode()).get(info.getCardNum()); = trackedCards.get(info.getSetCode()).get(info.getCardNum());
if (candidates.size() > 0) { if (!candidates.isEmpty()) {
gridStack.add(candidates.remove(0)); gridStack.add(candidates.remove(0));
thisMaxStackSize = Math.max(thisMaxStackSize, gridStack.size()); thisMaxStackSize = Math.max(thisMaxStackSize, gridStack.size());
} }

View file

@ -106,25 +106,25 @@ public class Permanent extends Card {
if (permanent.getOriginal() != null) { if (permanent.getOriginal() != null) {
sb.append("\n----- Originally -------\n"); sb.append("\n----- Originally -------\n");
sb.append(permanent.getOriginal().getName()); sb.append(permanent.getOriginal().getName());
if (permanent.getOriginal().getManaCost().size() > 0) { if (!permanent.getOriginal().getManaCost().isEmpty()) {
sb.append("\n").append(permanent.getOriginal().getManaCost()); sb.append('\n').append(permanent.getOriginal().getManaCost());
} }
sb.append("\n").append(getType(permanent.getOriginal())); sb.append('\n').append(getType(permanent.getOriginal()));
if (permanent.getOriginal().getColor().hasColor()) { if (permanent.getOriginal().getColor().hasColor()) {
sb.append("\n").append(permanent.getOriginal().getColor().toString()); sb.append('\n').append(permanent.getOriginal().getColor().toString());
} }
if (permanent.getOriginal().getCardTypes().contains(CardType.CREATURE)) { if (permanent.getOriginal().getCardTypes().contains(CardType.CREATURE)) {
sb.append("\n").append(permanent.getOriginal().getPower()).append("/").append(permanent.getOriginal().getToughness()); sb.append('\n').append(permanent.getOriginal().getPower()).append('/').append(permanent.getOriginal().getToughness());
} }
else if (permanent.getOriginal().getCardTypes().contains(CardType.PLANESWALKER)) { else if (permanent.getOriginal().getCardTypes().contains(CardType.PLANESWALKER)) {
sb.append("\n").append(permanent.getOriginal().getLoyalty()); sb.append('\n').append(permanent.getOriginal().getLoyalty());
} }
for (String rule: getRules()) { for (String rule: getRules()) {
sb.append("\n").append(rule); sb.append('\n').append(rule);
} }
if (permanent.getOriginal().getExpansionSetCode().length() > 0) { if (!permanent.getOriginal().getExpansionSetCode().isEmpty()) {
sb.append("\n").append(permanent.getCardNumber()).append(" - "); sb.append('\n').append(permanent.getCardNumber()).append(" - ");
sb.append("\n").append(Sets.getInstance().get(permanent.getOriginal().getExpansionSetCode()).getName()).append(" - "); sb.append('\n').append(Sets.getInstance().get(permanent.getOriginal().getExpansionSetCode()).getName()).append(" - ");
sb.append(permanent.getOriginal().getRarity().toString()); sb.append(permanent.getOriginal().getRarity().toString());
} }
// sb.append("\n").append(card.getId()); // sb.append("\n").append(card.getId());

View file

@ -51,7 +51,7 @@ public class MageTextArea extends JEditorPane {
text = text.replace("\r\n", "<div style='font-size:5pt'></div>"); text = text.replace("\r\n", "<div style='font-size:5pt'></div>");
final String basicText = ManaSymbols.replaceSymbolsWithHTML(text, ManaSymbols.Type.DIALOG); final String basicText = ManaSymbols.replaceSymbolsWithHTML(text, ManaSymbols.Type.DIALOG);
if (text.length() > 0) { if (!text.isEmpty()) {
buffer.append(basicText); buffer.append(basicText);
} }

View file

@ -296,7 +296,7 @@ public class AbilityPicker extends JXPanel implements MouseWheelListener {
text = text.replace("\r\n", "<div style='font-size:5pt'></div>"); text = text.replace("\r\n", "<div style='font-size:5pt'></div>");
//text += "<br>"; //text += "<br>";
if (text.length() > 0) { if (!text.isEmpty()) {
buffer.append(ManaSymbols.replaceSymbolsWithHTML(text, ManaSymbols.Type.DIALOG)); buffer.append(ManaSymbols.replaceSymbolsWithHTML(text, ManaSymbols.Type.DIALOG));
} }

View file

@ -802,6 +802,6 @@ public class RelativeLayout implements LayoutManager2, java.io.Serializable {
return getClass().getName() return getClass().getName()
+ "[axis=" + axis + "[axis=" + axis
+ ",gap=" + gap + ",gap=" + gap
+ "]"; + ']';
} }
} }

View file

@ -168,7 +168,7 @@ public class RatioAdjustingSliderPanel extends JPanel {
private static JLabel createChangingPercentageLabel(final JSlider slider) { private static JLabel createChangingPercentageLabel(final JSlider slider) {
final JLabel label = new JLabel(" " + String.valueOf(slider.getValue()) + "%"); final JLabel label = new JLabel(" " + String.valueOf(slider.getValue()) + '%');
slider.addChangeListener(e -> { slider.addChangeListener(e -> {
String value = String.valueOf(slider.getValue()); String value = String.valueOf(slider.getValue());
@ -178,7 +178,7 @@ public class RatioAdjustingSliderPanel extends JPanel {
labelBuilder.append(" "); labelBuilder.append(" ");
} }
labelBuilder.append(value); labelBuilder.append(value);
labelBuilder.append("%"); labelBuilder.append('%');
label.setText(labelBuilder.toString()); label.setText(labelBuilder.toString());
}); });
return label; return label;

View file

@ -97,7 +97,7 @@ public class DeckArea extends javax.swing.JPanel {
@Override @Override
public String toString() { public String toString() {
return maindeckSettings.toString() + "|" + sideboardSetings.toString() + "|" + dividerLocationNormal + "|" + dividerLocationLimited; return maindeckSettings.toString() + '|' + sideboardSetings.toString() + '|' + dividerLocationNormal + '|' + dividerLocationLimited;
} }
} }

View file

@ -584,12 +584,12 @@ public class DeckEditorPanel extends javax.swing.JPanel {
int second = s - (minute * 60); int second = s - (minute * 60);
String text; String text;
if (minute < 10) { if (minute < 10) {
text = "0" + Integer.toString(minute) + ":"; text = '0' + Integer.toString(minute) + ':';
} else { } else {
text = Integer.toString(minute) + ":"; text = Integer.toString(minute) + ':';
} }
if (second < 10) { if (second < 10) {
text = text + "0" + Integer.toString(second); text = text + '0' + Integer.toString(second);
} else { } else {
text = text + Integer.toString(second); text = text + Integer.toString(second);
} }
@ -599,7 +599,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
} }
if (timeToSubmit > 0) { if (timeToSubmit > 0) {
timeToSubmit--; timeToSubmit--;
btnSubmitTimer.setText("Submit (" + timeToSubmit + ")"); btnSubmitTimer.setText("Submit (" + timeToSubmit + ')');
btnSubmitTimer.setToolTipText("Submit your deck in " + timeToSubmit + " seconds!"); btnSubmitTimer.setToolTipText("Submit your deck in " + timeToSubmit + " seconds!");
} }
} }

View file

@ -56,17 +56,17 @@ public class CardHelper {
StringBuilder type = new StringBuilder(); StringBuilder type = new StringBuilder();
for (String superType : c.getSuperTypes()) { for (String superType : c.getSuperTypes()) {
type.append(superType); type.append(superType);
type.append(" "); type.append(' ');
} }
for (CardType cardType : c.getCardTypes()) { for (CardType cardType : c.getCardTypes()) {
type.append(cardType.toString()); type.append(cardType.toString());
type.append(" "); type.append(' ');
} }
if (c.getSubTypes().size() > 0) { if (!c.getSubTypes().isEmpty()) {
type.append("- "); type.append("- ");
for (String subType : c.getSubTypes()) { for (String subType : c.getSubTypes()) {
type.append(subType); type.append(subType);
type.append(" "); type.append(' ');
} }
} }
return type.toString(); return type.toString();

View file

@ -86,10 +86,10 @@ public class MageCardComparator implements Comparator<CardView> {
aCom = (float) -1; aCom = (float) -1;
bCom = (float) -1; bCom = (float) -1;
if (CardHelper.isCreature(a)) { if (CardHelper.isCreature(a)) {
aCom = new Float(a.getPower() + "." + (a.getToughness().startsWith("-") ? "0" : a.getToughness())); aCom = new Float(a.getPower() + '.' + (a.getToughness().startsWith("-") ? "0" : a.getToughness()));
} }
if (CardHelper.isCreature(b)) { if (CardHelper.isCreature(b)) {
bCom = new Float(b.getPower() + "." + (b.getToughness().startsWith("-") ? "0" : b.getToughness())); bCom = new Float(b.getPower() + '.' + (b.getToughness().startsWith("-") ? "0" : b.getToughness()));
} }
break; break;
// Rarity // Rarity

View file

@ -264,7 +264,7 @@ public class TableModel extends AbstractTableModel implements ICardGrid {
case 4: case 4:
return CardHelper.getType(c); return CardHelper.getType(c);
case 5: case 5:
return CardHelper.isCreature(c) ? c.getPower() + "/" return CardHelper.isCreature(c) ? c.getPower() + '/'
+ c.getToughness() : "-"; + c.getToughness() : "-";
case 6: case 6:
return c.getRarity().toString(); return c.getRarity().toString();

View file

@ -134,10 +134,10 @@ public class CardInfoWindowDialog extends MageDialog {
public void loadCards(ExileView exile, BigCard bigCard, UUID gameId) { public void loadCards(ExileView exile, BigCard bigCard, UUID gameId) {
boolean changed = cards.loadCards(exile, bigCard, gameId, true); boolean changed = cards.loadCards(exile, bigCard, gameId, true);
String titel = name + " (" + exile.size() + ")"; String titel = name + " (" + exile.size() + ')';
setTitle(titel); setTitle(titel);
this.setTitelBarToolTip(titel); this.setTitelBarToolTip(titel);
if (exile.size() > 0) { if (!exile.isEmpty()) {
show(); show();
if (changed) { if (changed) {
try { try {

View file

@ -398,7 +398,7 @@ public class ConnectDialog extends MageDialog {
// pref settings // pref settings
MageFrame.getInstance().setUserPrefsToConnection(connection); MageFrame.getInstance().setUserPrefsToConnection(connection);
logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort()); logger.debug("connecting: " + connection.getProxyType() + ' ' + connection.getProxyHost() + ' ' + connection.getProxyPort());
task = new ConnectTask(); task = new ConnectTask();
task.execute(); task.execute();
} finally { } finally {

View file

@ -100,7 +100,7 @@ public class GameEndDialog extends MageDialog {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (PlayerView player : gameEndView.getPlayers()) { for (PlayerView player : gameEndView.getPlayers()) {
sb.append(player.getName()).append(" Life: ").append(player.getLife()).append(" "); sb.append(player.getName()).append(" Life: ").append(player.getLife()).append(' ');
} }
this.txtLife.setText(sb.toString()); this.txtLife.setText(sb.toString());
@ -128,8 +128,8 @@ public class GameEndDialog extends MageDialog {
sdf.applyPattern( "yyyyMMdd_HHmmss" ); sdf.applyPattern( "yyyyMMdd_HHmmss" );
String fileName = new StringBuilder(dir).append(File.separator) String fileName = new StringBuilder(dir).append(File.separator)
.append(sdf.format(gameEndView.getStartTime())) .append(sdf.format(gameEndView.getStartTime()))
.append("_").append(gameEndView.getMatchView().getGameType()) .append('_').append(gameEndView.getMatchView().getGameType())
.append("_").append(gameEndView.getMatchView().getGames().size()) .append('_').append(gameEndView.getMatchView().getGames().size())
.append(".txt").toString(); .append(".txt").toString();
PrintWriter out = new PrintWriter(fileName); PrintWriter out = new PrintWriter(fileName);
out.print(gamePanel.getGameLog()); out.print(gamePanel.getGameLog());

View file

@ -507,7 +507,7 @@ public class NewTableDialog extends MageDialog {
while (players.size() != numPlayers) { while (players.size() != numPlayers) {
TablePlayerPanel playerPanel = new TablePlayerPanel(); TablePlayerPanel playerPanel = new TablePlayerPanel();
String playerType = "Human"; String playerType = "Human";
if (prefPlayerTypes.size() >= players.size() && players.size() > 0) { if (prefPlayerTypes.size() >= players.size() && !players.isEmpty()) {
playerType = prefPlayerTypes.get(players.size() - 1); playerType = prefPlayerTypes.get(players.size() - 1);
} }
playerPanel.init(players.size() + 2, playerType); playerPanel.init(players.size() + 2, playerType);
@ -673,7 +673,7 @@ public class NewTableDialog extends MageDialog {
StringBuilder playerTypesString = new StringBuilder(); StringBuilder playerTypesString = new StringBuilder();
for (Object player : players) { for (Object player : players) {
if (playerTypesString.length() > 0) { if (playerTypesString.length() > 0) {
playerTypesString.append(","); playerTypesString.append(',');
} }
TablePlayerPanel tpp = (TablePlayerPanel) player; TablePlayerPanel tpp = (TablePlayerPanel) player;
playerTypesString.append(tpp.getPlayerType()); playerTypesString.append(tpp.getPlayerType());

View file

@ -826,7 +826,7 @@ public class NewTournamentDialog extends MageDialog {
txtRandomPacks.setEnabled(false); txtRandomPacks.setEnabled(false);
txtRandomPacks.setLineWrap(true); txtRandomPacks.setLineWrap(true);
String randomPrefs = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_RANDOM_DRAFT, ""); String randomPrefs = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_RANDOM_DRAFT, "");
if (randomPrefs.length() > 0) { if (!randomPrefs.isEmpty()) {
txtRandomPacks.setText(randomPrefs); txtRandomPacks.setText(randomPrefs);
ArrayList<String> theList = new ArrayList<>(); ArrayList<String> theList = new ArrayList<>();
theList.addAll(Arrays.asList(randomPrefs.split(";"))); theList.addAll(Arrays.asList(randomPrefs.split(";")));
@ -836,7 +836,7 @@ public class NewTournamentDialog extends MageDialog {
StringBuilder packList = new StringBuilder(); StringBuilder packList = new StringBuilder();
for (ExpansionInfo exp : allExpansions) { for (ExpansionInfo exp : allExpansions) {
packList.append(exp.getCode()); packList.append(exp.getCode());
packList.append(";"); packList.append(';');
} }
txtRandomPacks.setText(packList.toString()); txtRandomPacks.setText(packList.toString());
} }
@ -860,7 +860,7 @@ public class NewTournamentDialog extends MageDialog {
StringBuilder packList = new StringBuilder(); StringBuilder packList = new StringBuilder();
for (String str : randomPackSelector.getSelectedPacks()) { for (String str : randomPackSelector.getSelectedPacks()) {
packList.append(str); packList.append(str);
packList.append(";"); packList.append(';');
} }
this.txtRandomPacks.setText(packList.toString()); this.txtRandomPacks.setText(packList.toString());
this.pack(); this.pack();
@ -1026,7 +1026,7 @@ public class NewTournamentDialog extends MageDialog {
} }
private void loadBoosterPacks(String packString) { private void loadBoosterPacks(String packString) {
if (packString.length()>0) { 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 ){
@ -1088,7 +1088,7 @@ public class NewTournamentDialog extends MageDialog {
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());
} }

View file

@ -188,7 +188,7 @@ public class DraftPanel extends javax.swing.JPanel {
// If we are logging the draft create a file that will contain // If we are logging the draft create a file that will contain
// the log. // the log.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
logFilename = "Draft_" + sdf.format(new Date()) + "_" + draftId + ".txt"; logFilename = "Draft_" + sdf.format(new Date()) + '_' + draftId + ".txt";
try { try {
Files.write(pathToDraftLog(), "".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); Files.write(pathToDraftLog(), "".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException ex) { } catch (IOException ex) {
@ -366,12 +366,12 @@ public class DraftPanel extends javax.swing.JPanel {
int second = s - (minute * 60); int second = s - (minute * 60);
String text; String text;
if (minute < 10) { if (minute < 10) {
text = "0" + Integer.toString(minute) + ":"; text = '0' + Integer.toString(minute) + ':';
} else { } else {
text = Integer.toString(minute) + ":"; text = Integer.toString(minute) + ':';
} }
if (second < 10) { if (second < 10) {
text = text + "0" + Integer.toString(second); text = text + '0' + Integer.toString(second);
} else { } else {
text = text + Integer.toString(second); text = text + Integer.toString(second);
} }

View file

@ -406,7 +406,7 @@ public final class GamePanel extends javax.swing.JPanel {
private void saveDividerLocations() { private void saveDividerLocations() {
// save panel sizes and divider locations. // save panel sizes and divider locations.
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb); PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb);
PreferencesDialog.saveValue(PreferencesDialog.KEY_GAMEPANEL_DIVIDER_LOCATION_0, Integer.toString(this.jSplitPane0.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_GAMEPANEL_DIVIDER_LOCATION_0, Integer.toString(this.jSplitPane0.getDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_GAMEPANEL_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_GAMEPANEL_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation()));
@ -417,7 +417,7 @@ public final class GamePanel extends javax.swing.JPanel {
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
if (rec != null) { if (rec != null) {
String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null); String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null);
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
// use divider positions only if screen size is the same as it was the time the settings were saved // use divider positions only if screen size is the same as it was the time the settings were saved
if (size != null && size.equals(sb)) { if (size != null && size.equals(sb)) {
@ -723,7 +723,7 @@ public final class GamePanel extends javax.swing.JPanel {
if (!handCards.containsKey(chosenHandKey)) { if (!handCards.containsKey(chosenHandKey)) {
chosenHandKey = YOUR_HAND; chosenHandKey = YOUR_HAND;
} }
} else if (chosenHandKey.isEmpty() && handCards.size() > 0) { } else if (chosenHandKey.isEmpty() && !handCards.isEmpty()) {
chosenHandKey = handCards.keySet().iterator().next(); chosenHandKey = handCards.keySet().iterator().next();
} }
if (chosenHandKey != null && handCards.containsKey(chosenHandKey)) { if (chosenHandKey != null && handCards.containsKey(chosenHandKey)) {
@ -764,7 +764,7 @@ public final class GamePanel extends javax.swing.JPanel {
} }
if (game.getSpellsCastCurrentTurn() > 0 && PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_SHOW_STORM_COUNTER, "true").equals("true")) { if (game.getSpellsCastCurrentTurn() > 0 && PreferencesDialog.getCachedValue(PreferencesDialog.KEY_GAME_SHOW_STORM_COUNTER, "true").equals("true")) {
this.txtSpellsCast.setVisible(true); this.txtSpellsCast.setVisible(true);
this.txtSpellsCast.setText(" " + Integer.toString(game.getSpellsCastCurrentTurn()) + " "); this.txtSpellsCast.setText(' ' + Integer.toString(game.getSpellsCastCurrentTurn()) + ' ');
} else { } else {
this.txtSpellsCast.setVisible(false); this.txtSpellsCast.setVisible(false);
} }
@ -854,7 +854,7 @@ public final class GamePanel extends javax.swing.JPanel {
showRevealed(game); showRevealed(game);
showLookedAt(game); showLookedAt(game);
if (game.getCombat().size() > 0) { if (!game.getCombat().isEmpty()) {
CombatManager.getInstance().showCombat(game.getCombat(), gameId); CombatManager.getInstance().showCombat(game.getCombat(), gameId);
} else { } else {
CombatManager.getInstance().hideCombat(gameId); CombatManager.getInstance().hideCombat(gameId);
@ -1164,7 +1164,7 @@ public final class GamePanel extends javax.swing.JPanel {
updateGame(gameView); updateGame(gameView);
Map<String, Serializable> options0 = options == null ? new HashMap<>() : options; Map<String, Serializable> options0 = options == null ? new HashMap<>() : options;
ShowCardsDialog dialog = null; ShowCardsDialog dialog = null;
if (cardView != null && cardView.size() > 0) { if (cardView != null && !cardView.isEmpty()) {
dialog = showCards(message, cardView, required, options0, popupMenuType); dialog = showCards(message, cardView, required, options0, popupMenuType);
options0.put("dialog", dialog); options0.put("dialog", dialog);
} }
@ -1279,7 +1279,7 @@ public final class GamePanel extends javax.swing.JPanel {
pickChoice.showDialog(choice, objectId, choiceWindowState); pickChoice.showDialog(choice, objectId, choiceWindowState);
if (choice.isKeyChoice()) { if (choice.isKeyChoice()) {
if (pickChoice.isAutoSelect()) { if (pickChoice.isAutoSelect()) {
SessionHandler.sendPlayerString(gameId, "#" + choice.getChoiceKey()); SessionHandler.sendPlayerString(gameId, '#' + choice.getChoiceKey());
} else { } else {
SessionHandler.sendPlayerString(gameId, choice.getChoiceKey()); SessionHandler.sendPlayerString(gameId, choice.getChoiceKey());
} }
@ -2130,7 +2130,7 @@ public final class GamePanel extends javax.swing.JPanel {
choices, choices,
this.chosenHandKey); this.chosenHandKey);
if (newChosenHandKey != null && newChosenHandKey.length() > 0) { if (newChosenHandKey != null && !newChosenHandKey.isEmpty()) {
this.chosenHandKey = newChosenHandKey; this.chosenHandKey = newChosenHandKey;
CardsView cards = handCards.get(chosenHandKey); CardsView cards = handCards.get(chosenHandKey);
handContainer.loadCards(cards, bigCard, gameId); handContainer.loadCards(cards, bigCard, gameId);

View file

@ -377,11 +377,11 @@ public class HelperPanel extends JPanel {
public void handleAutoAnswerPopupMenuEvent(ActionEvent e) { public void handleAutoAnswerPopupMenuEvent(ActionEvent e) {
switch (e.getActionCommand()) { switch (e.getActionCommand()) {
case CMD_AUTO_ANSWER_ID_YES: case CMD_AUTO_ANSWER_ID_YES:
SessionHandler.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_YES, gameId, originalId.toString() + "#" + message); SessionHandler.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_YES, gameId, originalId.toString() + '#' + message);
clickButton(btnLeft); clickButton(btnLeft);
break; break;
case CMD_AUTO_ANSWER_ID_NO: case CMD_AUTO_ANSWER_ID_NO:
SessionHandler.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_NO, gameId, originalId.toString() + "#" + message); SessionHandler.sendPlayerAction(REQUEST_AUTO_ANSWER_ID_NO, gameId, originalId.toString() + '#' + message);
clickButton(btnRight); clickButton(btnRight);
break; break;
case CMD_AUTO_ANSWER_NAME_YES: case CMD_AUTO_ANSWER_NAME_YES:

View file

@ -360,7 +360,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
int h = priorityTimeLeft / 3600; int h = priorityTimeLeft / 3600;
int m = (priorityTimeLeft % 3600) / 60; int m = (priorityTimeLeft % 3600) / 60;
int s = priorityTimeLeft % 60; int s = priorityTimeLeft % 60;
return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m + ":" + (s < 10 ? "0" : "") + s; return (h < 10 ? "0" : "") + h + ':' + (m < 10 ? "0" : "") + m + ':' + (s < 10 ? "0" : "") + s;
} }
protected void update(ManaPoolView pool) { protected void update(ManaPoolView pool) {

View file

@ -43,7 +43,7 @@ public class MagePreferences {
} }
private static String prefixedKey(String prefix, String key) { private static String prefixedKey(String prefix, String key) {
return prefix + "/" + key; return prefix + '/' + key;
} }
public static String getUserName(String serverAddress) { public static String getUserName(String serverAddress) {

View file

@ -161,11 +161,11 @@ public class PlayersChatPanel extends javax.swing.JPanel {
JTableHeader th = jTablePlayers.getTableHeader(); JTableHeader th = jTablePlayers.getTableHeader();
TableColumnModel tcm = th.getColumnModel(); TableColumnModel tcm = th.getColumnModel();
tcm.getColumn(jTablePlayers.convertColumnIndexToView(1)).setHeaderValue("Players (" + this.players.length + ")"); tcm.getColumn(jTablePlayers.convertColumnIndexToView(1)).setHeaderValue("Players (" + this.players.length + ')');
tcm.getColumn(jTablePlayers.convertColumnIndexToView(8)).setHeaderValue( tcm.getColumn(jTablePlayers.convertColumnIndexToView(8)).setHeaderValue(
"Games " + roomUserInfo.getNumberActiveGames() "Games " + roomUserInfo.getNumberActiveGames()
+ (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (") + (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (")
+ " limit: " + roomUserInfo.getNumberMaxGames() + ")"); + " limit: " + roomUserInfo.getNumberMaxGames() + ')');
th.repaint(); th.repaint();
this.fireTableDataChanged(); this.fireTableDataChanged();
} }

View file

@ -187,7 +187,7 @@ public class TablesPanel extends javax.swing.JPanel {
String pwdColumn = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_PASSWORD); String pwdColumn = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_PASSWORD);
switch (action) { switch (action) {
case "Join": case "Join":
if (owner.equals(SessionHandler.getUserName()) || owner.startsWith(SessionHandler.getUserName() + ",")) { if (owner.equals(SessionHandler.getUserName()) || owner.startsWith(SessionHandler.getUserName() + ',')) {
try { try {
JDesktopPane desktopPane = (JDesktopPane) MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE); JDesktopPane desktopPane = (JDesktopPane) MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE);
JInternalFrame[] windows = desktopPane.getAllFramesInLayer(javax.swing.JLayeredPane.DEFAULT_LAYER); JInternalFrame[] windows = desktopPane.getAllFramesInLayer(javax.swing.JLayeredPane.DEFAULT_LAYER);
@ -259,7 +259,7 @@ public class TablesPanel extends javax.swing.JPanel {
switch (action) { switch (action) {
case "Replay": case "Replay":
List<UUID> gameList = matchesModel.getListofGames(modelRow); List<UUID> gameList = matchesModel.getListofGames(modelRow);
if (gameList != null && gameList.size() > 0) { if (gameList != null && !gameList.isEmpty()) {
if (gameList.size() == 1) { if (gameList.size() == 1) {
SessionHandler.replayGame(gameList.get(0)); SessionHandler.replayGame(gameList.get(0));
} else { } else {
@ -350,7 +350,7 @@ public class TablesPanel extends javax.swing.JPanel {
private void saveDividerLocations() { private void saveDividerLocations() {
// save panel sizes and divider locations. // save panel sizes and divider locations.
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb); PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb);
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_2, Integer.toString(this.jSplitPaneTables.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_2, Integer.toString(this.jSplitPaneTables.getDividerLocation()));
@ -387,7 +387,7 @@ public class TablesPanel extends javax.swing.JPanel {
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
if (rec != null) { if (rec != null) {
String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null); String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null);
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
// use divider positions only if screen size is the same as it was the time the settings were saved // use divider positions only if screen size is the same as it was the time the settings were saved
if (size != null && size.equals(sb)) { if (size != null && size.equals(sb)) {
String location = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_1, null); String location = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TABLES_DIVIDER_LOCATION_1, null);

View file

@ -174,7 +174,7 @@ public class TournamentPanel extends javax.swing.JPanel {
private void saveDividerLocations() { private void saveDividerLocations() {
// save panel sizes and divider locations. // save panel sizes and divider locations.
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb); PreferencesDialog.saveValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, sb);
PreferencesDialog.saveValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.getDividerLocation()));
PreferencesDialog.saveValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_2, Integer.toString(this.jSplitPane2.getDividerLocation())); PreferencesDialog.saveValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_2, Integer.toString(this.jSplitPane2.getDividerLocation()));
@ -184,7 +184,7 @@ public class TournamentPanel extends javax.swing.JPanel {
Rectangle rec = MageFrame.getDesktop().getBounds(); Rectangle rec = MageFrame.getDesktop().getBounds();
if (rec != null) { if (rec != null) {
String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null); String size = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_MAGE_PANEL_LAST_SIZE, null);
String sb = Double.toString(rec.getWidth()) + "x" + Double.toString(rec.getHeight()); String sb = Double.toString(rec.getWidth()) + 'x' + Double.toString(rec.getHeight());
// use divider positions only if screen size is the same as it was the time the settings were saved // use divider positions only if screen size is the same as it was the time the settings were saved
if (size != null && size.equals(sb)) { if (size != null && size.equals(sb)) {
String location = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_1, null); String location = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_TOURNAMENT_DIVIDER_LOCATION_1, null);
@ -244,7 +244,7 @@ public class TournamentPanel extends javax.swing.JPanel {
c = c.getParent(); c = c.getParent();
} }
if (c != null) { if (c != null) {
((TournamentPane) c).setTitle("Tournament [" + tournament.getTournamentName() + "]"); ((TournamentPane) c).setTitle("Tournament [" + tournament.getTournamentName() + ']');
} }
txtName.setText(tournament.getTournamentName()); txtName.setText(tournament.getTournamentName());
txtType.setText(tournament.getTournamentType()); txtType.setText(tournament.getTournamentType());
@ -260,7 +260,7 @@ public class TournamentPanel extends javax.swing.JPanel {
if (tournament.getStepStartTime() != null) { if (tournament.getStepStartTime() != null) {
timeLeft = Format.getDuration(tournament.getConstructionTime() - (tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime()) / 1000); timeLeft = Format.getDuration(tournament.getConstructionTime() - (tournament.getServerTime().getTime() - tournament.getStepStartTime().getTime()) / 1000);
} }
txtTournamentState.setText(new StringBuilder(tournament.getTournamentState()).append(" (").append(timeLeft).append(")").toString()); txtTournamentState.setText(new StringBuilder(tournament.getTournamentState()).append(" (").append(timeLeft).append(')').toString());
break; break;
case "Dueling": case "Dueling":
case "Drafting": case "Drafting":

View file

@ -59,7 +59,7 @@ public class CardsViewUtil {
CardsView cards = new CardsView(); CardsView cards = new CardsView();
for (SimpleCardView simple: view.values()) { for (SimpleCardView simple: view.values()) {
String key = simple.getExpansionSetCode() + "_" + simple.getCardNumber(); String key = simple.getExpansionSetCode() + '_' + simple.getCardNumber();
Card card = loadedCards.get(key); Card card = loadedCards.get(key);
if(card == null) if(card == null)
{ {

View file

@ -62,13 +62,13 @@ public class Format {
seconds = seconds % 3600; seconds = seconds % 3600;
long m = seconds / 60; long m = seconds / 60;
long s = seconds % 60; long s = seconds % 60;
sb.append(h).append(":"); sb.append(h).append(':');
if (m<10) { if (m<10) {
sb.append("0"); sb.append('0');
} }
sb.append(m).append(":"); sb.append(m).append(':');
if (s<10) { if (s<10) {
sb.append("0"); sb.append('0');
} }
sb.append(s); sb.append(s);
return sb.toString(); return sb.toString();

View file

@ -86,7 +86,7 @@ public class ImageHelper {
} }
public static void drawCosts(List<String> costs, Graphics2D g, int xOffset, int yOffset, ImageObserver o) { public static void drawCosts(List<String> costs, Graphics2D g, int xOffset, int yOffset, ImageObserver o) {
if (costs.size() > 0) { if (!costs.isEmpty()) {
int costLeft = xOffset; int costLeft = xOffset;
for (int i = costs.size() - 1; i >= 0; i--) { for (int i = costs.size() - 1; i >= 0; i--) {
String symbol = costs.get(i); String symbol = costs.get(i);

View file

@ -49,7 +49,7 @@ public class MageTableRowSorter extends TableRowSorter<TableModel> {
@Override @Override
public void toggleSortOrder(int column) { public void toggleSortOrder(int column) {
List<? extends SortKey> sortKeys = getSortKeys(); List<? extends SortKey> sortKeys = getSortKeys();
if (sortKeys.size() > 0) { if (!sortKeys.isEmpty()) {
if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) { if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) {
setSortKeys(null); setSortKeys(null);
return; return;

View file

@ -112,7 +112,7 @@ public class MusicPlayer {
volume = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN); volume = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
sourceDataLine.start(); sourceDataLine.start();
} catch (Exception e) { } catch (Exception e) {
log.error("Couldn't load file: " + file + " " + e); log.error("Couldn't load file: " + file + ' ' + e);
} }
} }

View file

@ -135,7 +135,7 @@ public class ArrowBuilder {
if (map.containsKey(gameId)) { if (map.containsKey(gameId)) {
Map<Type, List<Arrow>> innerMap = map.get(gameId); Map<Type, List<Arrow>> innerMap = map.get(gameId);
java.util.List<Arrow> arrows = innerMap.get(type); java.util.List<Arrow> arrows = innerMap.get(type);
if (arrows != null && arrows.size() > 0) { if (arrows != null && !arrows.isEmpty()) {
JPanel p = getArrowsPanel(gameId); JPanel p = getArrowsPanel(gameId);
synchronized (map) { synchronized (map) {
for (Arrow arrow : arrows) { for (Arrow arrow : arrows) {

View file

@ -222,7 +222,7 @@ public class GuiDisplayUtil {
buffer.append("<tr><td valign='top'><b>"); buffer.append("<tr><td valign='top'><b>");
buffer.append(card.getDisplayName()); buffer.append(card.getDisplayName());
if (card.isGameObject()) { if (card.isGameObject()) {
buffer.append(" [").append(card.getId().toString().substring(0, 3)).append("]"); buffer.append(" [").append(card.getId().toString().substring(0, 3)).append(']');
} }
buffer.append("</b></td><td align='right' valign='top' style='width:"); buffer.append("</b></td><td align='right' valign='top' style='width:");
buffer.append(symbolCount * GUISizeHelper.cardTooltipFontSize); buffer.append(symbolCount * GUISizeHelper.cardTooltipFontSize);
@ -232,7 +232,7 @@ public class GuiDisplayUtil {
} }
buffer.append("</td></tr></table>"); buffer.append("</td></tr></table>");
buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'><tr><td style='margin-left: 1px'>"); buffer.append("<table cellspacing=0 cellpadding=0 border=0 width='100%'><tr><td style='margin-left: 1px'>");
String imageSize = " width=" + GUISizeHelper.cardTooltipFontSize + " height=" + GUISizeHelper.cardTooltipFontSize + ">"; String imageSize = " width=" + GUISizeHelper.cardTooltipFontSize + " height=" + GUISizeHelper.cardTooltipFontSize + '>';
if (card.getColor().isWhite()) { if (card.getColor().isWhite()) {
buffer.append("<img src='").append(getResourcePath("card/color_ind_white.png")).append("' alt='W' ").append(imageSize); buffer.append("<img src='").append(getResourcePath("card/color_ind_white.png")).append("' alt='W' ").append(imageSize);
} }
@ -281,7 +281,7 @@ public class GuiDisplayUtil {
String pt = ""; String pt = "";
if (CardUtil.isCreature(card)) { if (CardUtil.isCreature(card)) {
pt = card.getPower() + "/" + card.getToughness(); pt = card.getPower() + '/' + card.getToughness();
} else if (CardUtil.isPlaneswalker(card)) { } else if (CardUtil.isPlaneswalker(card)) {
pt = card.getLoyalty(); pt = card.getLoyalty();
} }
@ -291,7 +291,7 @@ public class GuiDisplayUtil {
buffer.append("<td align='right'>"); buffer.append("<td align='right'>");
if (!card.isControlledByOwner()) { if (!card.isControlledByOwner()) {
if (card instanceof PermanentView) { if (card instanceof PermanentView) {
buffer.append("[").append(((PermanentView) card).getNameOwner()).append("] "); buffer.append('[').append(((PermanentView) card).getNameOwner()).append("] ");
} else { } else {
buffer.append("[only controlled] "); buffer.append("[only controlled] ");
} }
@ -330,7 +330,7 @@ public class GuiDisplayUtil {
} }
} }
} }
if (textLines.lines.size() > 0) { if (!textLines.lines.isEmpty()) {
for (String textLine : textLines.lines) { for (String textLine : textLines.lines) {
if (textLine != null && !textLine.replace(".", "").trim().isEmpty()) { if (textLine != null && !textLine.replace(".", "").trim().isEmpty()) {
rule.append("<p style='margin: 2px'>").append(textLine).append("</p>"); rule.append("<p style='margin: 2px'>").append(textLine).append("</p>");
@ -339,7 +339,7 @@ public class GuiDisplayUtil {
} }
String legal = rule.toString(); String legal = rule.toString();
if (legal.length() > 0) { if (!legal.isEmpty()) {
legal = legal.replaceAll("\\{this\\}", card.getName().isEmpty() ? "this" : card.getName()); legal = legal.replaceAll("\\{this\\}", card.getName().isEmpty() ? "this" : card.getName());
legal = legal.replaceAll("\\{source\\}", card.getName().isEmpty() ? "this" : card.getName()); legal = legal.replaceAll("\\{source\\}", card.getName().isEmpty() ? "this" : card.getName());
buffer.append(ManaSymbols.replaceSymbolsWithHTML(legal, ManaSymbols.Type.TOOLTIP)); buffer.append(ManaSymbols.replaceSymbolsWithHTML(legal, ManaSymbols.Type.TOOLTIP));
@ -361,16 +361,16 @@ public class GuiDisplayUtil {
private static String getTypes(CardView card) { private static String getTypes(CardView card) {
String types = ""; String types = "";
for (String superType : card.getSuperTypes()) { for (String superType : card.getSuperTypes()) {
types += superType + " "; types += superType + ' ';
} }
for (CardType cardType : card.getCardTypes()) { for (CardType cardType : card.getCardTypes()) {
types += cardType.toString() + " "; types += cardType.toString() + ' ';
} }
if (card.getSubTypes().size() > 0) { if (!card.getSubTypes().isEmpty()) {
types += "- "; types += "- ";
} }
for (String subType : card.getSubTypes()) { for (String subType : card.getSubTypes()) {
types += subType + " "; types += subType + ' ';
} }
return types.trim(); return types.trim();
} }

View file

@ -59,8 +59,8 @@ public class TableUtil {
for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) { for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
TableColumn column = table.getColumnModel().getColumn(table.convertColumnIndexToView(i)); TableColumn column = table.getColumnModel().getColumn(table.convertColumnIndexToView(i));
if (!firstValue) { if (!firstValue) {
columnWidthSettings.append(","); columnWidthSettings.append(',');
columnOrderSettings.append(","); columnOrderSettings.append(',');
} else { } else {
firstValue = false; firstValue = false;
} }

View file

@ -65,7 +65,7 @@ public class MyComboBoxEditor extends BasicComboBoxEditor {
@Override @Override
public Object getItem() { public Object getItem() {
return "[" + this.selectedItem.toString() + "]"; return '[' + this.selectedItem.toString() + ']';
} }
@Override @Override

View file

@ -53,7 +53,7 @@ public class SaveObjectUtil {
} }
} }
String time = now(DATE_PATTERN); String time = now(DATE_PATTERN);
File f = new File("income" + File.separator + name + "_" + time + ".save"); File f = new File("income" + File.separator + name + '_' + time + ".save");
if (!f.exists()) { if (!f.exists()) {
f.createNewFile(); f.createNewFile();
} }

View file

@ -36,7 +36,7 @@ public class UpdateMemUsageTask extends SwingWorker<Void, Float> {
@Override @Override
protected void process(List<Float> chunks) { protected void process(List<Float> chunks) {
if (chunks != null && chunks.size() > 0) { if (chunks != null && !chunks.isEmpty()) {
Float memUsage = chunks.get(chunks.size() - 1); Float memUsage = chunks.get(chunks.size() - 1);
if (memUsage != null) { if (memUsage != null) {
jLabelToDisplayInfo.setText(Math.round(memUsage) + "% Mem free"); jLabelToDisplayInfo.setText(Math.round(memUsage) + "% Mem free");

View file

@ -681,17 +681,17 @@ public abstract class CardPanel extends MagePermanent implements MouseListener,
StringBuilder sbType = new StringBuilder(); StringBuilder sbType = new StringBuilder();
for (String superType : card.getSuperTypes()) { for (String superType : card.getSuperTypes()) {
sbType.append(superType).append(" "); sbType.append(superType).append(' ');
} }
for (CardType cardType : card.getCardTypes()) { for (CardType cardType : card.getCardTypes()) {
sbType.append(cardType.toString()).append(" "); sbType.append(cardType.toString()).append(' ');
} }
if (card.getSubTypes().size() > 0) { if (!card.getSubTypes().isEmpty()) {
sbType.append("- "); sbType.append("- ");
for (String subType : card.getSubTypes()) { for (String subType : card.getSubTypes()) {
sbType.append(subType).append(" "); sbType.append(subType).append(' ');
} }
} }
@ -702,30 +702,30 @@ public abstract class CardPanel extends MagePermanent implements MouseListener,
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (card instanceof StackAbilityView || card instanceof AbilityView) { if (card instanceof StackAbilityView || card instanceof AbilityView) {
for (String rule : card.getRules()) { for (String rule : card.getRules()) {
sb.append("\n").append(rule); sb.append('\n').append(rule);
} }
} else { } else {
sb.append(card.getName()); sb.append(card.getName());
if (card.getManaCost().size() > 0) { if (!card.getManaCost().isEmpty()) {
sb.append("\n").append(card.getManaCost()); sb.append('\n').append(card.getManaCost());
} }
sb.append("\n").append(cardType); sb.append('\n').append(cardType);
if (card.getColor().hasColor()) { if (card.getColor().hasColor()) {
sb.append("\n").append(card.getColor().toString()); sb.append('\n').append(card.getColor().toString());
} }
if (card.getCardTypes().contains(CardType.CREATURE)) { if (card.getCardTypes().contains(CardType.CREATURE)) {
sb.append("\n").append(card.getPower()).append("/").append(card.getToughness()); sb.append('\n').append(card.getPower()).append('/').append(card.getToughness());
} else if (card.getCardTypes().contains(CardType.PLANESWALKER)) { } else if (card.getCardTypes().contains(CardType.PLANESWALKER)) {
sb.append("\n").append(card.getLoyalty()); sb.append('\n').append(card.getLoyalty());
} }
if (card.getRules() == null) { if (card.getRules() == null) {
card.overrideRules(new ArrayList<>()); card.overrideRules(new ArrayList<>());
} }
for (String rule : card.getRules()) { for (String rule : card.getRules()) {
sb.append("\n").append(rule); sb.append('\n').append(rule);
} }
if (card.getExpansionSetCode() != null && card.getExpansionSetCode().length() > 0) { if (card.getExpansionSetCode() != null && !card.getExpansionSetCode().isEmpty()) {
sb.append("\n").append(card.getCardNumber()).append(" - "); sb.append('\n').append(card.getCardNumber()).append(" - ");
sb.append(card.getExpansionSetCode()).append(" - "); sb.append(card.getExpansionSetCode()).append(" - ");
sb.append(card.getRarity().toString()); sb.append(card.getRarity().toString());
} }

View file

@ -241,7 +241,7 @@ public class CardPanelComponentImpl extends CardPanel {
// PT Text // PT Text
ptText = new GlowText(); ptText = new GlowText();
if (CardUtil.isCreature(gameCard)) { if (CardUtil.isCreature(gameCard)) {
ptText.setText(gameCard.getPower() + "/" + gameCard.getToughness()); ptText.setText(gameCard.getPower() + '/' + gameCard.getToughness());
} else if (CardUtil.isPlaneswalker(gameCard)) { } else if (CardUtil.isPlaneswalker(gameCard)) {
ptText.setText(gameCard.getLoyalty()); ptText.setText(gameCard.getLoyalty());
} }
@ -580,9 +580,9 @@ public class CardPanelComponentImpl extends CardPanel {
// Update card text // Update card text
if (CardUtil.isCreature(card) && CardUtil.isPlaneswalker(card)) { if (CardUtil.isCreature(card) && CardUtil.isPlaneswalker(card)) {
ptText.setText(card.getPower() + "/" + card.getToughness() + " (" + card.getLoyalty() + ")"); ptText.setText(card.getPower() + '/' + card.getToughness() + " (" + card.getLoyalty() + ')');
} else if (CardUtil.isCreature(card)) { } else if (CardUtil.isCreature(card)) {
ptText.setText(card.getPower() + "/" + card.getToughness()); ptText.setText(card.getPower() + '/' + card.getToughness());
} else if (CardUtil.isPlaneswalker(card)) { } else if (CardUtil.isPlaneswalker(card)) {
ptText.setText(card.getLoyalty()); ptText.setText(card.getLoyalty());
} else { } else {

View file

@ -380,15 +380,15 @@ public abstract class CardRenderer {
} else { } else {
StringBuilder sbType = new StringBuilder(); StringBuilder sbType = new StringBuilder();
for (String superType : cardView.getSuperTypes()) { for (String superType : cardView.getSuperTypes()) {
sbType.append(superType).append(" "); sbType.append(superType).append(' ');
} }
for (CardType cardType : cardView.getCardTypes()) { for (CardType cardType : cardView.getCardTypes()) {
sbType.append(cardType.toString()).append(" "); sbType.append(cardType.toString()).append(' ');
} }
if (cardView.getSubTypes().size() > 0) { if (!cardView.getSubTypes().isEmpty()) {
sbType.append("- "); sbType.append("- ");
for (String subType : cardView.getSubTypes()) { for (String subType : cardView.getSubTypes()) {
sbType.append(subType).append(" "); sbType.append(subType).append(' ');
} }
} }
return sbType.toString(); return sbType.toString();

View file

@ -89,7 +89,7 @@ public class ManaSymbols {
setImages.put(set, rarityImages); setImages.put(set, rarityImages);
for (String rarityCode : codes) { for (String rarityCode : codes) {
File file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET + set + "-" + rarityCode + ".jpg"); File file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET + set + '-' + rarityCode + ".jpg");
try { try {
Image image = UI.getImageIcon(file.getAbsolutePath()).getImage(); Image image = UI.getImageIcon(file.getAbsolutePath()).getImage();
int width = image.getWidth(null); int width = image.getWidth(null);
@ -114,11 +114,11 @@ public class ManaSymbols {
} }
for (String code : codes) { for (String code : codes) {
file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET_SMALL + set + "-" + code + ".png"); file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET_SMALL + set + '-' + code + ".png");
if (file.exists()) { if (file.exists()) {
continue; continue;
} }
file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET + set + "-" + code + ".jpg"); file = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET + set + '-' + code + ".jpg");
Image image = UI.getImageIcon(file.getAbsolutePath()).getImage(); Image image = UI.getImageIcon(file.getAbsolutePath()).getImage();
try { try {
int width = image.getWidth(null); int width = image.getWidth(null);
@ -130,7 +130,7 @@ public class ManaSymbols {
} }
Rectangle r = new Rectangle(15 + dx, (int) (height * (15.0f + dx) / width)); Rectangle r = new Rectangle(15 + dx, (int) (height * (15.0f + dx) / width));
BufferedImage resized = ImageHelper.getResizedImage(BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB), r); BufferedImage resized = ImageHelper.getResizedImage(BufferedImageBuilder.bufferImage(image, BufferedImage.TYPE_INT_ARGB), r);
File newFile = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET_SMALL + File.separator + set + "-" + code + ".png"); File newFile = new File(getSymbolsPath() + Constants.RESOURCE_PATH_SET_SMALL + File.separator + set + '-' + code + ".png");
ImageIO.write(resized, "png", newFile); ImageIO.write(resized, "png", newFile);
} }
} catch (Exception e) { } catch (Exception e) {
@ -171,7 +171,7 @@ public class ManaSymbols {
resourcePath = Constants.RESOURCE_PATH_MANA_MEDIUM; resourcePath = Constants.RESOURCE_PATH_MANA_MEDIUM;
} }
for (String symbol : symbols) { for (String symbol : symbols) {
File file = new File(getSymbolsPath() + resourcePath + "/" + symbol + ".gif"); File file = new File(getSymbolsPath() + resourcePath + '/' + symbol + ".gif");
try { try {
if (size == 15 || size == 25) { if (size == 15 || size == 25) {
@ -315,7 +315,7 @@ public class ManaSymbols {
if (symbolFilesFound) { if (symbolFilesFound) {
replaced = REPLACE_SYMBOLS_PATTERN.matcher(value).replaceAll( replaced = REPLACE_SYMBOLS_PATTERN.matcher(value).replaceAll(
"<img src='file:" + getSymbolsPath(true) + "/symbols/" + resourcePath + "/$1$2.gif' alt='$1$2' width=" + symbolSize "<img src='file:" + getSymbolsPath(true) + "/symbols/" + resourcePath + "/$1$2.gif' alt='$1$2' width=" + symbolSize
+ " height=" + symbolSize + ">"); + " height=" + symbolSize + '>');
} }
replaced = replaced.replace("|source|", "{source}"); replaced = replaced.replace("|source|", "{source}");
replaced = replaced.replace("|this|", "{this}"); replaced = replaced.replace("|this|", "{this}");
@ -328,7 +328,7 @@ public class ManaSymbols {
int factor = size / 15 + 1; int factor = size / 15 + 1;
Integer width = setImagesExist.get(_set).width * factor; Integer width = setImagesExist.get(_set).width * factor;
Integer height = setImagesExist.get(_set).height * factor; Integer height = setImagesExist.get(_set).height * factor;
return "<img src='file:" + getSymbolsPath() + "/sets/small/" + _set + "-" + rarity + ".png' alt='" + rarity + "' height='" + height + "' width='" + width + "' >"; return "<img src='file:" + getSymbolsPath() + "/sets/small/" + _set + '-' + rarity + ".png' alt='" + rarity + "' height='" + height + "' width='" + width + "' >";
} else { } else {
return set; return set;
} }

View file

@ -638,7 +638,7 @@ public class ModernCardRenderer extends CardRenderer {
} }
g.setColor(textColor); g.setColor(textColor);
g.setFont(ptTextFont); g.setFont(ptTextFont);
String ptText = cardView.getPower() + "/" + cardView.getToughness(); String ptText = cardView.getPower() + '/' + cardView.getToughness();
int ptTextWidth = g.getFontMetrics().stringWidth(ptText); int ptTextWidth = g.getFontMetrics().stringWidth(ptText);
g.drawString(ptText, g.drawString(ptText,
x + (partWidth - ptTextWidth) / 2, curY - ptTextOffset - 1); x + (partWidth - ptTextWidth) / 2, curY - ptTextOffset - 1);

View file

@ -87,7 +87,7 @@ public class TextboxRule {
// Do it in reverse order for proper handling of regions where // Do it in reverse order for proper handling of regions where
// there are multiple attributes stacked (EG: bold + italic) // there are multiple attributes stacked (EG: bold + italic)
AttributedString attributedRule = new AttributedString(text); AttributedString attributedRule = new AttributedString(text);
if (text.length() != 0) { if (!text.isEmpty()) {
attributedRule.addAttribute(TextAttribute.FONT, normal); attributedRule.addAttribute(TextAttribute.FONT, normal);
for (int i = regions.size() - 1; i >= 0; --i) { for (int i = regions.size() - 1; i >= 0; --i) {
regions.get(i).applyToAttributedString(attributedRule, normal, italic); regions.get(i).applyToAttributedString(attributedRule, normal, italic);

View file

@ -179,7 +179,7 @@ public class CardPluginImpl implements CardPlugin {
break; break;
} }
List<CounterView> counters = firstPanel.getOriginalPermanent().getCounters(); List<CounterView> counters = firstPanel.getOriginalPermanent().getCounters();
if (counters != null && counters.size() > 0) { if (counters != null && !counters.isEmpty()) {
// don't put to first panel if it has counters // don't put to first panel if it has counters
insertIndex = i; insertIndex = i;
break; break;
@ -191,7 +191,7 @@ public class CardPluginImpl implements CardPlugin {
continue; continue;
} }
counters = permanent.getOriginalPermanent().getCounters(); counters = permanent.getOriginalPermanent().getCounters();
if (counters != null && counters.size() > 0) { if (counters != null && !counters.isEmpty()) {
// if a land has counter, put it to the right // if a land has counter, put it to the right
insertIndex = i + 1; insertIndex = i + 1;
continue; continue;

View file

@ -22,5 +22,5 @@ public class Constants {
String IMAGE_PROPERTIES_FILE = "image.url.properties"; String IMAGE_PROPERTIES_FILE = "image.url.properties";
} }
public static final String CARD_IMAGE_PATH_TEMPLATE = "." + File.separator + "plugins" + File.separator + "images/{set}/{name}.{collector}.full.jpg"; public static final String CARD_IMAGE_PATH_TEMPLATE = '.' + File.separator + "plugins" + File.separator + "images/{set}/{name}.{collector}.full.jpg";
} }

View file

@ -167,7 +167,7 @@ public class DownloadJob extends AbstractLaternaBean {
@Override @Override
public String toString() { public String toString() {
return proxy != null ? proxy.type().toString() + " " : "" + url; return proxy != null ? proxy.type().toString() + ' ' : "" + url;
} }
}; };
@ -196,7 +196,7 @@ public class DownloadJob extends AbstractLaternaBean {
@Override @Override
public String toString() { public String toString() {
return proxy != null ? proxy.type().toString() + " " : "" + url; return proxy != null ? proxy.type().toString() + ' ' : "" + url;
} }
}; };
} }

View file

@ -78,8 +78,8 @@ public class CardFrames implements Iterable<DownloadJob> {
private DownloadJob generateDownloadJob(String dirName, String name) { private DownloadJob generateDownloadJob(String dirName, String name) {
File dst = new File(outDir, name + ".png"); File dst = new File(outDir, name + ".png");
String url = BASE_DOWNLOAD_URL + dirName + "/" + name + ".png"; String url = BASE_DOWNLOAD_URL + dirName + '/' + name + ".png";
return new DownloadJob("frames-" + dirName + "-" + name, fromURL(url), toFile(dst)); return new DownloadJob("frames-" + dirName + '-' + name, fromURL(url), toFile(dst));
} }
private void useDefaultDir() { private void useDefaultDir() {

View file

@ -163,12 +163,12 @@ public class GathererSets implements Iterable<DownloadJob> {
} }
private DownloadJob generateDownloadJob(String set, String rarity, String urlRarity) { private DownloadJob generateDownloadJob(String set, String rarity, String urlRarity) {
File dst = new File(outDir, set + "-" + rarity + ".jpg"); File dst = new File(outDir, set + '-' + rarity + ".jpg");
if (symbolsReplacements.containsKey(set)) { if (symbolsReplacements.containsKey(set)) {
set = symbolsReplacements.get(set); set = symbolsReplacements.get(set);
} }
String url = "http://gatherer.wizards.com/Handlers/Image.ashx?type=symbol&set=" + set + "&size=small&rarity=" + urlRarity; String url = "http://gatherer.wizards.com/Handlers/Image.ashx?type=symbol&set=" + set + "&size=small&rarity=" + urlRarity;
return new DownloadJob(set + "-" + rarity, fromURL(url), toFile(dst)); return new DownloadJob(set + '-' + rarity, fromURL(url), toFile(dst));
} }
private void changeOutDir(String path) { private void changeOutDir(String path) {

View file

@ -54,62 +54,64 @@ public class GathererSymbols implements Iterable<DownloadJob> {
@Override @Override
protected DownloadJob computeNext() { protected DownloadJob computeNext() {
String sym; while (true) {
if (symIndex < symbols.length) { String sym;
sym = symbols[symIndex++]; if (symIndex < symbols.length) {
} else if (numeric <= maxNumeric) { sym = symbols[symIndex++];
sym = "" + (numeric++); } else if (numeric <= maxNumeric) {
} else { sym = "" + (numeric++);
sizeIndex++; } else {
if (sizeIndex == sizes.length) { sizeIndex++;
return endOfData(); if (sizeIndex == sizes.length) {
return endOfData();
}
symIndex = 0;
numeric = 0;
dir = new File(outDir, sizes[sizeIndex]);
continue;
}
String symbol = sym.replaceAll("/", "");
File dst = new File(dir, symbol + ".gif");
/**
* Handle a bug on Gatherer where a few symbols are missing at the large size.
* Fall back to using the medium symbol for those cases.
*/
int modSizeIndex = sizeIndex;
if (sizeIndex == 2) {
switch (sym) {
case "WP":
case "UP":
case "BP":
case "RP":
case "GP":
case "E":
case "C":
modSizeIndex = 1;
break;
default:
// Nothing to do, symbol is available in the large size
}
} }
symIndex = 0; switch (symbol) {
numeric = 0; case "T":
dir = new File(outDir, sizes[sizeIndex]); symbol = "tap";
return computeNext(); break;
} case "Q":
String symbol = sym.replaceAll("/", ""); symbol = "untap";
File dst = new File(dir, symbol + ".gif"); break;
case "S":
/** symbol = "snow";
* Handle a bug on Gatherer where a few symbols are missing at the large size.
* Fall back to using the medium symbol for those cases.
*/
int modSizeIndex = sizeIndex;
if (sizeIndex == 2) {
switch (sym) {
case "WP":
case "UP":
case "BP":
case "RP":
case "GP":
case "E":
case "C":
modSizeIndex = 1;
break; break;
default:
// Nothing to do, symbol is available in the large size
} }
String url = format(urlFmt, sizes[modSizeIndex], symbol);
return new DownloadJob(sym, fromURL(url), toFile(dst));
} }
switch (symbol) {
case "T":
symbol = "tap";
break;
case "Q":
symbol = "untap";
break;
case "S":
symbol = "snow";
break;
}
String url = format(urlFmt, sizes[modSizeIndex], symbol);
return new DownloadJob(sym, fromURL(url), toFile(dst));
} }
}; };
} }

View file

@ -174,20 +174,20 @@ public class MagicCardsImageSource implements CardImageSource {
String preferedLanguage = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PREF_LANGUAGE, "en"); String preferedLanguage = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_CARD_IMAGES_PREF_LANGUAGE, "en");
StringBuilder url = new StringBuilder("http://magiccards.info/scans/").append(preferedLanguage).append("/"); StringBuilder url = new StringBuilder("http://magiccards.info/scans/").append(preferedLanguage).append('/');
url.append(set.toLowerCase()).append("/").append(collectorId); url.append(set.toLowerCase()).append('/').append(collectorId);
if (card.isTwoFacedCard()) { if (card.isTwoFacedCard()) {
url.append(card.isSecondSide() ? "b" : "a"); url.append(card.isSecondSide() ? "b" : "a");
} }
if (card.isSplitCard()) { if (card.isSplitCard()) {
url.append("a"); url.append('a');
} }
if (card.isFlipCard()) { if (card.isFlipCard()) {
if (card.isFlippedSide()) { // download rotated by 180 degree image if (card.isFlippedSide()) { // download rotated by 180 degree image
url.append("b"); url.append('b');
} else { } else {
url.append("a"); url.append('a');
} }
} }
url.append(".jpg"); url.append(".jpg");
@ -200,16 +200,16 @@ public class MagicCardsImageSource implements CardImageSource {
String name = card.getName(); String name = card.getName();
// add type to name if it's not 0 // add type to name if it's not 0
if (card.getType() > 0) { if (card.getType() > 0) {
name = name + " " + card.getType(); name = name + ' ' + card.getType();
} }
name = name.replaceAll(" ", "-").replace(",", "").toLowerCase(); name = name.replaceAll(" ", "-").replace(",", "").toLowerCase();
String set = "not-supported-set"; String set = "not-supported-set";
if (setNameTokenReplacement.containsKey(card.getSet())) { if (setNameTokenReplacement.containsKey(card.getSet())) {
set = setNameTokenReplacement.get(card.getSet()); set = setNameTokenReplacement.get(card.getSet());
} else { } else {
set += "-" + card.getSet(); set += '-' + card.getSet();
} }
return "http://magiccards.info/extras/token/" + set + "/" + name + ".jpg"; return "http://magiccards.info/extras/token/" + set + '/' + name + ".jpg";
} }
@Override @Override

View file

@ -74,7 +74,7 @@ public class MagidexImageSource implements CardImageSource {
} }
// This will properly escape the url // This will properly escape the url
URI uri = new URI("http", "magidex.com", "/extstatic/card/" + cardSet + "/" + cardDownloadName + ".jpg", null, null); URI uri = new URI("http", "magidex.com", "/extstatic/card/" + cardSet + '/' + cardDownloadName + ".jpg", null, null);
return uri.toASCIIString(); return uri.toASCIIString();
} }

View file

@ -73,7 +73,7 @@ public class MtgImageSource implements CardImageSource {
throw new Exception("Wrong parameters for image: collector id: " + collectorId + ",card set: " + cardSet); throw new Exception("Wrong parameters for image: collector id: " + collectorId + ",card set: " + cardSet);
} }
StringBuilder url = new StringBuilder("http://mtgimage.com/set/"); StringBuilder url = new StringBuilder("http://mtgimage.com/set/");
url.append(cardSet.toUpperCase()).append("/"); url.append(cardSet.toUpperCase()).append('/');
if (card.isSplitCard()) { if (card.isSplitCard()) {
url.append(card.getDownloadName().replaceAll(" // ", "")); url.append(card.getDownloadName().replaceAll(" // ", ""));
@ -86,9 +86,9 @@ public class MtgImageSource implements CardImageSource {
} }
if (card.isFlipCard()) { if (card.isFlipCard()) {
if (card.isFlippedSide()) { // download rotated by 180 degree image if (card.isFlippedSide()) { // download rotated by 180 degree image
url.append("b"); url.append('b');
} else { } else {
url.append("a"); url.append('a');
} }
} }
url.append(".jpg"); url.append(".jpg");

View file

@ -115,7 +115,7 @@ public class MythicspoilerComSource implements CardImageSource {
Connection.ProxyType proxyType = Connection.ProxyType.valueByText(prefs.get("proxyType", "None")); Connection.ProxyType proxyType = Connection.ProxyType.valueByText(prefs.get("proxyType", "None"));
for (String setName : setNames.split("\\^")) { for (String setName : setNames.split("\\^")) {
String URLSetName = URLEncoder.encode(setName, "UTF-8"); String URLSetName = URLEncoder.encode(setName, "UTF-8");
String baseUrl = "http://mythicspoiler.com/" + URLSetName + "/"; String baseUrl = "http://mythicspoiler.com/" + URLSetName + '/';
Map<String, String> pageLinks = getSetLinksFromPage(cardSet, aliasesStart, prefs, proxyType, baseUrl, baseUrl); Map<String, String> pageLinks = getSetLinksFromPage(cardSet, aliasesStart, prefs, proxyType, baseUrl, baseUrl);
setLinks.putAll(pageLinks); setLinks.putAll(pageLinks);
@ -166,7 +166,7 @@ public class MythicspoilerComSource implements CardImageSource {
Elements cardsImages = doc.select("img[src^=cards/]"); // starts with cards/ Elements cardsImages = doc.select("img[src^=cards/]"); // starts with cards/
if (!aliasesStart.isEmpty()) { if (!aliasesStart.isEmpty()) {
for (String text : aliasesStart) { for (String text : aliasesStart) {
cardsImages.addAll(doc.select("img[src^=" + text + "]")); cardsImages.addAll(doc.select("img[src^=" + text + ']'));
} }
} }
@ -179,8 +179,8 @@ public class MythicspoilerComSource implements CardImageSource {
cardName = cardLink.substring(0, cardLink.length() - 4); cardName = cardLink.substring(0, cardLink.length() - 4);
} }
if (cardName != null && !cardName.isEmpty()) { if (cardName != null && !cardName.isEmpty()) {
if (cardNameAliases.containsKey(cardSet + "-" + cardName)) { if (cardNameAliases.containsKey(cardSet + '-' + cardName)) {
cardName = cardNameAliases.get(cardSet + "-" + cardName); cardName = cardNameAliases.get(cardSet + '-' + cardName);
} else if (cardName.endsWith("1") || cardName.endsWith("2") || cardName.endsWith("3") || cardName.endsWith("4") || cardName.endsWith("5")) { } else if (cardName.endsWith("1") || cardName.endsWith("2") || cardName.endsWith("3") || cardName.endsWith("4") || cardName.endsWith("5")) {
if (!cardName.startsWith("forest") if (!cardName.startsWith("forest")
&& !cardName.startsWith("swamp") && !cardName.startsWith("swamp")

View file

@ -27,6 +27,9 @@
*/ */
package org.mage.plugins.card.dl.sources; package org.mage.plugins.card.dl.sources;
import org.apache.log4j.Logger;
import org.mage.plugins.card.images.CardDownloadData;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@ -36,8 +39,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger;
import org.mage.plugins.card.images.CardDownloadData;
/** /**
* *
@ -161,19 +162,19 @@ public class TokensMtgImageSource implements CardImageSource {
TokenData tokenData; TokenData tokenData;
if (type == 0) { if (type == 0) {
if (matchedTokens.size() > 1) { if (matchedTokens.size() > 1) {
logger.info("Multiple images were found for token " + name + ", set " + set + "."); logger.info("Multiple images were found for token " + name + ", set " + set + '.');
} }
tokenData = matchedTokens.get(0); tokenData = matchedTokens.get(0);
} else { } else {
if (type > matchedTokens.size()) { if (type > matchedTokens.size()) {
logger.warn("Not enough images for token with type " + type + ", name " + name + ", set " + set + "."); logger.warn("Not enough images for token with type " + type + ", name " + name + ", set " + set + '.');
return null; return null;
} }
tokenData = matchedTokens.get(card.getType() - 1); tokenData = matchedTokens.get(card.getType() - 1);
} }
String url = "http://tokens.mtg.onl/tokens/" + tokenData.getExpansionSetCode().trim() + "_" String url = "http://tokens.mtg.onl/tokens/" + tokenData.getExpansionSetCode().trim() + '_'
+ tokenData.getNumber().trim() + "-" + tokenData.getName().trim() + ".jpg"; + tokenData.getNumber().trim() + '-' + tokenData.getName().trim() + ".jpg";
url = url.replace(' ', '-'); url = url.replace(' ', '-');
return url; return url;
} }
@ -184,30 +185,18 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData = new ArrayList<>(); tokensData = new ArrayList<>();
// get tokens data from resource file // get tokens data from resource file
InputStream inputStream = null; try(InputStream inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv")) {
try {
inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv");
List<TokenData> fileTokensData = parseTokensData(inputStream); List<TokenData> fileTokensData = parseTokensData(inputStream);
tokensData.addAll(fileTokensData); tokensData.addAll(fileTokensData);
} catch (Exception exception) { } catch (Exception exception) {
logger.warn("Failed to get tokens description from resource file tokens-mtg-onl-list.csv", exception); logger.warn("Failed to get tokens description from resource file tokens-mtg-onl-list.csv", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
} }
// description on site may contain new information // description on site may contain new information
// try to add it // try to add it
try { URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv");
URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv"); try(InputStream inputStream = url.openStream()) {
inputStream = url.openStream();
List<TokenData> siteTokensData = parseTokensData(inputStream); List<TokenData> siteTokensData = parseTokensData(inputStream);
List<TokenData> newTokensData = new ArrayList<>(); List<TokenData> newTokensData = new ArrayList<>();
for (TokenData siteData : siteTokensData) { for (TokenData siteData : siteTokensData) {
boolean isNew = true; boolean isNew = true;
@ -227,14 +216,6 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData.addAll(newTokensData); tokensData.addAll(newTokensData);
} catch (Exception exception) { } catch (Exception exception) {
logger.warn("Failed to get tokens description from tokens.mtg.onl", exception); logger.warn("Failed to get tokens description from tokens.mtg.onl", exception);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
logger.error("Input stream close failed:", e);
}
}
} }
} }
} }
@ -245,12 +226,9 @@ public class TokensMtgImageSource implements CardImageSource {
private List<TokenData> parseTokensData(InputStream inputStream) throws IOException { private List<TokenData> parseTokensData(InputStream inputStream) throws IOException {
List<TokenData> newTokensData = new ArrayList<>(); List<TokenData> newTokensData = new ArrayList<>();
InputStreamReader inputReader = null; try(InputStreamReader inputReader = new InputStreamReader(inputStream, "Cp1252");
BufferedReader reader = null; BufferedReader reader = new BufferedReader(inputReader)) {
try {
// we have to specify encoding to read special comma // we have to specify encoding to read special comma
inputReader = new InputStreamReader(inputStream, "Cp1252");
reader = new BufferedReader(inputReader);
reader.readLine(); // skip header reader.readLine(); // skip header
String line = reader.readLine(); String line = reader.readLine();
@ -282,21 +260,6 @@ public class TokensMtgImageSource implements CardImageSource {
line = reader.readLine(); line = reader.readLine();
} }
} finally {
if (inputReader != null) {
try {
inputReader.close();
} catch (Exception e) {
logger.error("Input reader close failed:", e);
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
logger.error("Buffered reader close failed:", e);
}
}
} }
return newTokensData; return newTokensData;

View file

@ -410,11 +410,11 @@ public class WizardCardsImageSource implements CardImageSource {
private String normalizeName(String name) { private String normalizeName(String name) {
//Split card //Split card
if(name.contains("//")) { if(name.contains("//")) {
name = name.substring(0, name.indexOf("(") - 1); name = name.substring(0, name.indexOf('(') - 1);
} }
//Special timeshifted name //Special timeshifted name
if(name.startsWith("XX")) { if(name.startsWith("XX")) {
name = name.substring(name.indexOf("(") + 1, name.length() - 1); name = name.substring(name.indexOf('(') + 1, name.length() - 1);
} }
return name.replace("\u2014", "-").replace("\u2019", "'") return name.replace("\u2014", "-").replace("\u2019", "'")
.replace("\u00C6", "AE").replace("\u00E6", "ae") .replace("\u00C6", "AE").replace("\u00E6", "ae")
@ -456,7 +456,7 @@ public class WizardCardsImageSource implements CardImageSource {
} else { } else {
link = setLinks.get(Integer.toString(number - 21)); link = setLinks.get(Integer.toString(number - 21));
if (link != null) { if (link != null) {
link = link.replace(Integer.toString(number - 20), (Integer.toString(number - 20) + "a")); link = link.replace(Integer.toString(number - 20), (Integer.toString(number - 20) + 'a'));
} }
} }
} }

View file

@ -1,45 +1,5 @@
package org.mage.plugins.card.images; package org.mage.plugins.card.images;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.AccessDeniedException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultBoundedRangeModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import mage.cards.repository.CardInfo; import mage.cards.repository.CardInfo;
import mage.client.constants.Constants; import mage.client.constants.Constants;
import mage.client.dialog.PreferencesDialog; import mage.client.dialog.PreferencesDialog;
@ -51,18 +11,27 @@ import net.java.truevfs.access.TFileOutputStream;
import net.java.truevfs.access.TVFS; import net.java.truevfs.access.TVFS;
import net.java.truevfs.kernel.spec.FsSyncException; import net.java.truevfs.kernel.spec.FsSyncException;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.mage.plugins.card.dl.sources.AltMtgOnlTokensImageSource; import org.mage.plugins.card.dl.sources.*;
import org.mage.plugins.card.dl.sources.CardImageSource;
import org.mage.plugins.card.dl.sources.GrabbagImageSource;
import org.mage.plugins.card.dl.sources.MagicCardsImageSource;
import org.mage.plugins.card.dl.sources.MagidexImageSource;
import org.mage.plugins.card.dl.sources.MtgOnlTokensImageSource;
import org.mage.plugins.card.dl.sources.MythicspoilerComSource;
import org.mage.plugins.card.dl.sources.TokensMtgImageSource;
import org.mage.plugins.card.dl.sources.WizardCardsImageSource;
import org.mage.plugins.card.properties.SettingsManager; import org.mage.plugins.card.properties.SettingsManager;
import org.mage.plugins.card.utils.CardImageUtils; import org.mage.plugins.card.utils.CardImageUtils;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.file.AccessDeniedException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
public class DownloadPictures extends DefaultBoundedRangeModel implements Runnable { public class DownloadPictures extends DefaultBoundedRangeModel implements Runnable {
private static final Logger logger = Logger.getLogger(DownloadPictures.class); private static final Logger logger = Logger.getLogger(DownloadPictures.class);
@ -356,12 +325,12 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
int tokenImages = 0; int tokenImages = 0;
for (CardDownloadData card : cardsToDownload) { for (CardDownloadData card : cardsToDownload) {
logger.debug((card.isToken() ? "Token" : "Card") + " image to download: " + card.getName() + " (" + card.getSet() + ")"); logger.debug((card.isToken() ? "Token" : "Card") + " image to download: " + card.getName() + " (" + card.getSet() + ')');
if (card.isToken()) { if (card.isToken()) {
tokenImages++; tokenImages++;
} }
} }
logger.info("Check download images (total card images: " + numberCardImages + ", total token images: " + numberAllTokenImages + ")"); logger.info("Check download images (total card images: " + numberCardImages + ", total token images: " + numberAllTokenImages + ')');
logger.info(" => Missing card images: " + (cardsToDownload.size() - tokenImages)); logger.info(" => Missing card images: " + (cardsToDownload.size() - tokenImages));
logger.info(" => Missing token images: " + tokenImages); logger.info(" => Missing token images: " + tokenImages);
return new ArrayList<>(cardsToDownload); return new ArrayList<>(cardsToDownload);
@ -376,11 +345,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
return list; return list;
} }
BufferedReader reader = null;
InputStreamReader input = null; try(InputStreamReader input = new InputStreamReader(in);
try { BufferedReader reader = new BufferedReader(input)) {
input = new InputStreamReader(in);
reader = new BufferedReader(input);
String line; String line;
line = reader.readLine(); line = reader.readLine();
@ -425,22 +392,6 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} catch (Exception ex) { } catch (Exception ex) {
logger.error(ex); logger.error(ex);
throw new RuntimeException("DownloadPictures : readFile() error"); throw new RuntimeException("DownloadPictures : readFile() error");
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
logger.error("Input close failed:", e);
}
}
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
logger.error("Reader close failed:", e);
}
}
} }
return list; return list;
} }
@ -494,7 +445,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
CardDownloadData card = cardsToDownload.get(i); CardDownloadData card = cardsToDownload.get(i);
logger.debug("Downloading card: " + card.getName() + " (" + card.getSet() + ")"); logger.debug("Downloading card: " + card.getName() + " (" + card.getSet() + ')');
String url; String url;
if (ignoreUrls.contains(card.getSet()) || card.isToken()) { if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
@ -519,7 +470,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} catch (Exception ex) { } catch (Exception ex) {
} }
} else if (cardImageSource.getTotalImages() == -1) { } else if (cardImageSource.getTotalImages() == -1) {
logger.info("Card not available on " + cardImageSource.getSourceName() + ": " + card.getName() + " (" + card.getSet() + ")"); logger.info("Card not available on " + cardImageSource.getSourceName() + ": " + card.getName() + " (" + card.getSet() + ')');
synchronized (sync) { synchronized (sync) {
update(cardIndex + 1, cardsToDownload.size()); update(cardIndex + 1, cardsToDownload.size());
} }
@ -589,7 +540,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
try { try {
filePath.append(Constants.IO.imageBaseDir); filePath.append(Constants.IO.imageBaseDir);
if (!useSpecifiedPaths && card != null) { if (!useSpecifiedPaths && card != null) {
filePath.append(card.hashCode()).append(".").append(card.getName().replace(":", "").replace("//", "-")).append(".jpg"); filePath.append(card.hashCode()).append('.').append(card.getName().replace(":", "").replace("//", "-")).append(".jpg");
temporaryFile = new File(filePath.toString()); temporaryFile = new File(filePath.toString());
} }
String imagePath; String imagePath;
@ -699,7 +650,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
if (card != null && !useSpecifiedPaths) { if (card != null && !useSpecifiedPaths) {
logger.warn("Image download for " + card.getName() logger.warn("Image download for " + card.getName()
+ (!card.getDownloadName().equals(card.getName()) ? " downloadname: " + card.getDownloadName() : "") + (!card.getDownloadName().equals(card.getName()) ? " downloadname: " + card.getDownloadName() : "")
+ "(" + card.getSet() + ") failed - responseCode: " + responseCode + " url: " + url.toString()); + '(' + card.getSet() + ") failed - responseCode: " + responseCode + " url: " + url.toString());
} }
if (logger.isDebugEnabled()) { // Shows the returned html from the request to the web server if (logger.isDebugEnabled()) { // Shows the returned html from the request to the web server
logger.debug("Returned HTML ERROR:\n" + convertStreamToString(((HttpURLConnection) httpConn).getErrorStream())); logger.debug("Returned HTML ERROR:\n" + convertStreamToString(((HttpURLConnection) httpConn).getErrorStream()));
@ -707,7 +658,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} }
} catch (AccessDeniedException e) { } catch (AccessDeniedException e) {
logger.error("The file " + (outputFile != null ? outputFile.toString() : "to add the image of " + card.getName() + "(" + card.getSet() + ")") + " can't be accessed. Try rebooting your system to remove the file lock."); logger.error("The file " + (outputFile != null ? outputFile.toString() : "to add the image of " + card.getName() + '(' + card.getSet() + ')') + " can't be accessed. Try rebooting your system to remove the file lock.");
} catch (Exception e) { } catch (Exception e) {
logger.error(e, e); logger.error(e, e);
} finally { } finally {

View file

@ -255,11 +255,11 @@ public class ImageCache {
* Returns the map key for a card, without any suffixes for the image size. * Returns the map key for a card, without any suffixes for the image size.
*/ */
private static String getKey(CardView card, String name, String suffix) { private static String getKey(CardView card, String name, String suffix) {
return name + "#" + card.getExpansionSetCode() + "#" + card.getType() + "#" + card.getCardNumber() + "#" return name + '#' + card.getExpansionSetCode() + '#' + card.getType() + '#' + card.getCardNumber() + '#'
+ (card.getTokenSetCode() == null ? "" : card.getTokenSetCode()) + (card.getTokenSetCode() == null ? "" : card.getTokenSetCode())
+ suffix + suffix
+ (card.getUsesVariousArt() ? "#usesVariousArt" : "") + (card.getUsesVariousArt() ? "#usesVariousArt" : "")
+ (card.getTokenDescriptor() != null ? "#" + card.getTokenDescriptor() : "#"); + (card.getTokenDescriptor() != null ? '#' + card.getTokenDescriptor() : "#");
} }
// /** // /**

View file

@ -168,11 +168,11 @@ public class CardImageUtils {
String imageDir = getImageDir(card, imagesPath); String imageDir = getImageDir(card, imagesPath);
String imageName; String imageName;
String type = card.getType() != 0 ? " " + Integer.toString(card.getType()) : ""; String type = card.getType() != 0 ? ' ' + Integer.toString(card.getType()) : "";
String name = card.getFileName().isEmpty() ? card.getName().replace(":", "").replace("//", "-") : card.getFileName(); String name = card.getFileName().isEmpty() ? card.getName().replace(":", "").replace("//", "-") : card.getFileName();
if (card.getUsesVariousArt()) { if (card.getUsesVariousArt()) {
imageName = name + "." + card.getCollectorId() + ".full.jpg"; imageName = name + '.' + card.getCollectorId() + ".full.jpg";
} else { } else {
imageName = name + type + ".full.jpg"; imageName = name + type + ".full.jpg";
} }

View file

@ -78,7 +78,7 @@ public final class Constants {
public enum SessionState { public enum SessionState {
DISCONNECTED, CONNECTED, CONNECTING, DISCONNECTING, SERVER_STARTING; DISCONNECTED, CONNECTED, CONNECTING, DISCONNECTING, SERVER_STARTING
} }
public enum Option { public enum Option {

View file

@ -23,7 +23,7 @@ public class EntityManagerTest {
System.out.print(" arguments=[ "); System.out.print(" arguments=[ ");
if (log.getArguments() != null) { if (log.getArguments() != null) {
for (String argument : log.getArguments()) { for (String argument : log.getArguments()) {
System.out.print("arg=" + argument + " "); System.out.print("arg=" + argument + ' ');
} }
} }
System.out.println("]"); System.out.println("]");

View file

@ -94,7 +94,7 @@ public class Connection {
@Override @Override
public String toString() { public String toString() {
return host + ":" + Integer.toString(port) + "/" + serialization + parameter; return host + ':' + Integer.toString(port) + '/' + serialization + parameter;
} }
public String getURI() { public String getURI() {
@ -102,13 +102,13 @@ public class Connection {
try { try {
InetAddress inet = getLocalAddress(); InetAddress inet = getLocalAddress();
if (inet != null) { if (inet != null) {
return transport + "://" + inet.getHostAddress() + ":" + port + "/" + serialization + parameter; return transport + "://" + inet.getHostAddress() + ':' + port + '/' + serialization + parameter;
} }
} catch (SocketException ex) { } catch (SocketException ex) {
// just use localhost if can't find local ip // just use localhost if can't find local ip
} }
} }
return transport + "://" + host + ":" + port + "/" + serialization + parameter; return transport + "://" + host + ':' + port + '/' + serialization + parameter;
} }
public ProxyType getProxyType() { public ProxyType getProxyType() {

View file

@ -158,7 +158,7 @@ public class SessionImpl implements Session {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Unable to connect to server.\n"); sb.append("Unable to connect to server.\n");
for (StackTraceElement element : t.getStackTrace()) { for (StackTraceElement element : t.getStackTrace()) {
sb.append(element.toString()).append("\n"); sb.append(element.toString()).append('\n');
} }
client.showMessage(sb.toString()); client.showMessage(sb.toString());
} }
@ -171,11 +171,11 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() { return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override @Override
public boolean run() throws Throwable { public boolean run() throws Throwable {
logger.info("Trying to register as " + getUserName() + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Trying to register as " + getUserName() + " to XMAGE server at " + connection.getHost() + ':' + connection.getPort());
boolean registerResult = server.registerUser(sessionId, connection.getUsername(), boolean registerResult = server.registerUser(sessionId, connection.getUsername(),
connection.getPassword(), connection.getEmail()); connection.getPassword(), connection.getEmail());
if (registerResult) { if (registerResult) {
logger.info("Registered as " + getUserName() + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Registered as " + getUserName() + " to MAGE server at " + connection.getHost() + ':' + connection.getPort());
} }
return registerResult; return registerResult;
} }
@ -187,10 +187,10 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() { return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override @Override
public boolean run() throws Throwable { public boolean run() throws Throwable {
logger.info("Trying to ask for an auth token to " + getEmail() + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Trying to ask for an auth token to " + getEmail() + " to XMAGE server at " + connection.getHost() + ':' + connection.getPort());
boolean result = server.emailAuthToken(sessionId, connection.getEmail()); boolean result = server.emailAuthToken(sessionId, connection.getEmail());
if (result) { if (result) {
logger.info("An auth token is emailed to " + getEmail() + " from MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("An auth token is emailed to " + getEmail() + " from MAGE server at " + connection.getHost() + ':' + connection.getPort());
} }
return result; return result;
} }
@ -202,10 +202,10 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() { return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override @Override
public boolean run() throws Throwable { public boolean run() throws Throwable {
logger.info("Trying reset the password in XMAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Trying reset the password in XMAGE server at " + connection.getHost() + ':' + connection.getPort());
boolean result = server.resetPassword(sessionId, connection.getEmail(), connection.getAuthToken(), connection.getPassword()); boolean result = server.resetPassword(sessionId, connection.getEmail(), connection.getAuthToken(), connection.getPassword());
if (result) { if (result) {
logger.info("Password is successfully reset in MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Password is successfully reset in MAGE server at " + connection.getHost() + ':' + connection.getPort());
} }
return result; return result;
} }
@ -218,7 +218,7 @@ public class SessionImpl implements Session {
&& handleRemotingTaskExceptions(new RemotingTask() { && handleRemotingTaskExceptions(new RemotingTask() {
@Override @Override
public boolean run() throws Throwable { public boolean run() throws Throwable {
logger.info("Trying to log-in as " + getUserName() + " to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Trying to log-in as " + getUserName() + " to XMAGE server at " + connection.getHost() + ':' + connection.getPort());
boolean registerResult; boolean registerResult;
if (connection.getAdminPassword() == null) { if (connection.getAdminPassword() == null) {
// for backward compatibility. don't remove twice call - first one does nothing but for version checking // for backward compatibility. don't remove twice call - first one does nothing but for version checking
@ -234,8 +234,8 @@ public class SessionImpl implements Session {
if (!connection.getUsername().equals("Admin")) { if (!connection.getUsername().equals("Admin")) {
updateDatabase(connection.isForceDBComparison(), serverState); updateDatabase(connection.isForceDBComparison(), serverState);
} }
logger.info("Logged-in as " + getUserName() + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Logged-in as " + getUserName() + " to MAGE server at " + connection.getHost() + ':' + connection.getPort());
client.connected(getUserName() + "@" + connection.getHost() + ":" + connection.getPort() + " "); client.connected(getUserName() + '@' + connection.getHost() + ':' + connection.getPort() + ' ');
return true; return true;
} }
disconnect(false); disconnect(false);
@ -260,7 +260,7 @@ public class SessionImpl implements Session {
boolean result = handleRemotingTaskExceptions(new RemotingTask() { boolean result = handleRemotingTaskExceptions(new RemotingTask() {
@Override @Override
public boolean run() throws Throwable { public boolean run() throws Throwable {
logger.info("Trying to connect to XMAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Trying to connect to XMAGE server at " + connection.getHost() + ':' + connection.getPort());
System.setProperty("http.nonProxyHosts", "code.google.com"); System.setProperty("http.nonProxyHosts", "code.google.com");
System.setProperty("socksNonProxyHosts", "code.google.com"); System.setProperty("socksNonProxyHosts", "code.google.com");
@ -391,14 +391,14 @@ public class SessionImpl implements Session {
Set callbackConnectors = callbackClient.getCallbackConnectors(callbackHandler); Set callbackConnectors = callbackClient.getCallbackConnectors(callbackHandler);
if (callbackConnectors.size() != 1) { if (callbackConnectors.size() != 1) {
logger.warn("There should be one callback Connector (number existing = " + callbackConnectors.size() + ")"); logger.warn("There should be one callback Connector (number existing = " + callbackConnectors.size() + ')');
} }
callbackClient.invoke(null); callbackClient.invoke(null);
sessionId = callbackClient.getSessionId(); sessionId = callbackClient.getSessionId();
sessionState = SessionState.CONNECTED; sessionState = SessionState.CONNECTED;
logger.info("Connected to MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.info("Connected to MAGE server at " + connection.getHost() + ':' + connection.getPort());
return true; return true;
} }
}); });
@ -451,7 +451,7 @@ public class SessionImpl implements Session {
break; break;
} }
if (t.getCause() != null && logger.isDebugEnabled()) { if (t.getCause() != null && logger.isDebugEnabled()) {
message = "\n" + t.getCause().getMessage() + message; message = '\n' + t.getCause().getMessage() + message;
logger.debug(t.getCause().getMessage()); logger.debug(t.getCause().getMessage());
} }
@ -1434,7 +1434,7 @@ public class SessionImpl implements Session {
@Override @Override
public boolean endUserSession(String userSessionId) { public boolean endUserSession(String userSessionId) {
try { try {
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to mute userSessionId " + userSessionId + "?", "WARNING", if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to mute userSessionId " + userSessionId + '?', "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (isConnected()) { if (isConnected()) {
server.endUserSession(sessionId, userSessionId); server.endUserSession(sessionId, userSessionId);
@ -1470,7 +1470,7 @@ public class SessionImpl implements Session {
@Override @Override
public boolean setActivation(String userName, boolean active) { public boolean setActivation(String userName, boolean active) {
try { try {
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to set active to " + active + " for user: " + userName + "?", "WARNING", if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to set active to " + active + " for user: " + userName + '?', "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (isConnected()) { if (isConnected()) {
server.setActivation(sessionId, userName, active); server.setActivation(sessionId, userName, active);
@ -1496,7 +1496,7 @@ public class SessionImpl implements Session {
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
return setActivation(userName, false); return setActivation(userName, false);
} }
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to toggle activation for user: " + userName + "?", "WARNING", if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to toggle activation for user: " + userName + '?', "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (isConnected()) { if (isConnected()) {
server.toggleActivation(sessionId, userName); server.toggleActivation(sessionId, userName);
@ -1542,8 +1542,8 @@ public class SessionImpl implements Session {
} }
private void handleInvalidDeckException(InvalidDeckException iex) { private void handleInvalidDeckException(InvalidDeckException iex) {
logger.warn(iex.getMessage() + "\n" + iex.getInvalid()); logger.warn(iex.getMessage() + '\n' + iex.getInvalid());
client.showError(iex.getMessage() + "\n" + iex.getInvalid()); client.showError(iex.getMessage() + '\n' + iex.getInvalid());
} }
private void handleGameException(GameException ex) { private void handleGameException(GameException ex) {
@ -1588,7 +1588,7 @@ public class SessionImpl implements Session {
if (isConnected()) { if (isConnected()) {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
if (!server.ping(sessionId, pingInfo)) { if (!server.ping(sessionId, pingInfo)) {
logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() + ":" + connection.getPort()); logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() + ':' + connection.getPort());
throw new MageException("Ping failed"); throw new MageException("Ping failed");
} }
pingTime.add(System.nanoTime() - startTime); pingTime.add(System.nanoTime() - startTime);
@ -1602,7 +1602,7 @@ public class SessionImpl implements Session {
sum += time; sum += time;
} }
milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS); milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS);
pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms" : "<1ms") + ")"; pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms" : "<1ms") + ')';
} }
return true; return true;
} catch (MageException ex) { } catch (MageException ex) {

View file

@ -77,7 +77,7 @@ public class MageVersion implements Serializable, Comparable<MageVersion> {
@Override @Override
public String toString() { public String toString() {
return major + "." + minor + "." + patch + info + minorPatch; return major + "." + minor + '.' + patch + info + minorPatch;
} }
@Override @Override

View file

@ -397,7 +397,7 @@ public class CardView extends SimpleCardView {
for (SpellAbility spellAbility : spell.getSpellAbilities()) { for (SpellAbility spellAbility : spell.getSpellAbilities()) {
for (UUID modeId : spellAbility.getModes().getSelectedModes()) { for (UUID modeId : spellAbility.getModes().getSelectedModes()) {
Mode mode = spellAbility.getModes().get(modeId); Mode mode = spellAbility.getModes().get(modeId);
if (mode.getTargets().size() > 0) { if (!mode.getTargets().isEmpty()) {
setTargets(mode.getTargets()); setTargets(mode.getTargets());
} }
} }
@ -732,7 +732,7 @@ public class CardView extends SimpleCardView {
@Override @Override
public String toString() { public String toString() {
return getName() + " [" + getId() + "]"; return getName() + " [" + getId() + ']';
} }
public boolean isFaceDown() { public boolean isFaceDown() {

View file

@ -133,7 +133,7 @@ public class CardsView extends LinkedHashMap<UUID, CardView> {
} }
abilityView = new AbilityView(ability, sourceObject.getName(), sourceCardView); abilityView = new AbilityView(ability, sourceObject.getName(), sourceCardView);
} }
if (ability.getTargets().size() > 0) { if (!ability.getTargets().isEmpty()) {
abilityView.setTargets(ability.getTargets()); abilityView.setTargets(ability.getTargets());
} else { } else {
List<UUID> abilityTargets = new ArrayList<>(); List<UUID> abilityTargets = new ArrayList<>();

View file

@ -45,15 +45,15 @@ public class ChatMessage implements Serializable {
private MessageType messageType; private MessageType messageType;
public enum MessageColor { public enum MessageColor {
BLACK, RED, GREEN, BLUE, ORANGE, YELLOW; BLACK, RED, GREEN, BLUE, ORANGE, YELLOW
} }
public enum MessageType { public enum MessageType {
USER_INFO, STATUS, GAME, TALK, WHISPER; USER_INFO, STATUS, GAME, TALK, WHISPER
} }
public enum SoundToPlay { public enum SoundToPlay {
PlayerLeft, PlayerQuitTournament, PlayerSubmittedDeck, PlayerWhispered; PlayerLeft, PlayerQuitTournament, PlayerSubmittedDeck, PlayerWhispered
} }
public ChatMessage(String username, String message, String time, MessageColor color) { public ChatMessage(String username, String message, String time, MessageColor color) {

View file

@ -79,11 +79,11 @@ public class GameEndView implements Serializable {
} }
if (you != null) { if (you != null) {
if (you.hasWon()) { if (you.hasWon()) {
gameInfo = new StringBuilder("You won the game on turn ").append(game.getTurnNum()).append(".").toString(); gameInfo = new StringBuilder("You won the game on turn ").append(game.getTurnNum()).append('.').toString();
} else if (winner > 0) { } else if (winner > 0) {
gameInfo = new StringBuilder("You lost the game on turn ").append(game.getTurnNum()).append(".").toString(); gameInfo = new StringBuilder("You lost the game on turn ").append(game.getTurnNum()).append('.').toString();
} else { } else {
gameInfo = new StringBuilder("Game is a draw on Turn ").append(game.getTurnNum()).append(".").toString(); gameInfo = new StringBuilder("Game is a draw on Turn ").append(game.getTurnNum()).append('.').toString();
} }
} }
matchView = new MatchView(table); matchView = new MatchView(table);

View file

@ -138,7 +138,7 @@ public class GameView implements Serializable {
if (designation != null) { if (designation != null) {
stack.put(stackObject.getId(), new CardView(designation, (StackAbility) stackObject)); stack.put(stackObject.getId(), new CardView(designation, (StackAbility) stackObject));
} else { } else {
LOGGER.fatal("Designation object not found: " + object.getName() + " " + object.toString() + " " + object.getClass().toString()); LOGGER.fatal("Designation object not found: " + object.getName() + ' ' + object.toString() + ' ' + object.getClass().toString());
} }
} else if (object instanceof StackAbility) { } else if (object instanceof StackAbility) {
@ -147,7 +147,7 @@ public class GameView implements Serializable {
stack.put(stackObject.getId(), new CardView(((StackAbility) stackObject))); stack.put(stackObject.getId(), new CardView(((StackAbility) stackObject)));
checkPaid(stackObject.getId(), ((StackAbility) stackObject)); checkPaid(stackObject.getId(), ((StackAbility) stackObject));
} else { } else {
LOGGER.fatal("Object can't be cast to StackAbility: " + object.getName() + " " + object.toString() + " " + object.getClass().toString()); LOGGER.fatal("Object can't be cast to StackAbility: " + object.getName() + ' ' + object.toString() + ' ' + object.getClass().toString());
} }
} else { } else {
// can happen if a player times out while ability is on the stack // can happen if a player times out while ability is on the stack
@ -191,7 +191,7 @@ public class GameView implements Serializable {
if (priorityPlayer != null && createdForPlayer != null && createdForPlayerId != null && createdForPlayer.isGameUnderControl() if (priorityPlayer != null && createdForPlayer != null && createdForPlayerId != null && createdForPlayer.isGameUnderControl()
&& (createdForPlayerId.equals(priorityPlayer.getId()) // player controls the turn && (createdForPlayerId.equals(priorityPlayer.getId()) // player controls the turn
|| createdForPlayer.getPlayersUnderYourControl().contains(priorityPlayer.getId()))) { // player controls active players turn || createdForPlayer.getPlayersUnderYourControl().contains(priorityPlayer.getId()))) { // player controls active players turn
this.special = state.getSpecialActions().getControlledBy(priorityPlayer.getId(), priorityPlayer.isInPayManaMode()).size() > 0; this.special = !state.getSpecialActions().getControlledBy(priorityPlayer.getId(), priorityPlayer.isInPayManaMode()).isEmpty();
} }
} else { } else {
this.special = false; this.special = false;

View file

@ -78,7 +78,7 @@ public class MatchView implements Serializable {
this.gameType = match.getOptions().getGameType(); this.gameType = match.getOptions().getGameType();
if (table.getName() != null && !table.getName().isEmpty()) { if (table.getName() != null && !table.getName().isEmpty()) {
this.deckType = match.getOptions().getDeckType() + " [" + table.getName() + "]"; this.deckType = match.getOptions().getDeckType() + " [" + table.getName() + ']';
} else { } else {
this.deckType = match.getOptions().getDeckType(); this.deckType = match.getOptions().getDeckType();
} }
@ -102,9 +102,9 @@ public class MatchView implements Serializable {
int lostGames = match.getNumGames() - (matchPlayer.getWins() + match.getDraws()); int lostGames = match.getNumGames() - (matchPlayer.getWins() + match.getDraws());
sb1.append(", "); sb1.append(", ");
sb2.append(matchPlayer.getName()).append(" ["); sb2.append(matchPlayer.getName()).append(" [");
sb2.append(matchPlayer.getWins()).append("-"); sb2.append(matchPlayer.getWins()).append('-');
if (match.getDraws() > 0) { if (match.getDraws() > 0) {
sb2.append(match.getDraws()).append("-"); sb2.append(match.getDraws()).append('-');
} }
sb2.append(lostGames).append("], "); sb2.append(lostGames).append("], ");
} }
@ -127,14 +127,14 @@ public class MatchView implements Serializable {
this.matchName = table.getName(); this.matchName = table.getName();
this.gameType = table.getGameType(); this.gameType = table.getGameType();
if (table.getTournament().getOptions().getNumberRounds() > 0) { if (table.getTournament().getOptions().getNumberRounds() > 0) {
this.gameType = new StringBuilder(this.gameType).append(" ").append(table.getTournament().getOptions().getNumberRounds()).append(" Rounds").toString(); this.gameType = new StringBuilder(this.gameType).append(' ').append(table.getTournament().getOptions().getNumberRounds()).append(" Rounds").toString();
} }
StringBuilder sbDeckType = new StringBuilder(table.getDeckType()); StringBuilder sbDeckType = new StringBuilder(table.getDeckType());
if (!table.getTournament().getBoosterInfo().isEmpty()) { if (!table.getTournament().getBoosterInfo().isEmpty()) {
sbDeckType.append(" ").append(table.getTournament().getBoosterInfo()); sbDeckType.append(' ').append(table.getTournament().getBoosterInfo());
} }
if (table.getName() != null && !table.getName().isEmpty()) { if (table.getName() != null && !table.getName().isEmpty()) {
sbDeckType.append(table.getDeckType()).append(" [").append(table.getName()).append("]"); sbDeckType.append(table.getDeckType()).append(" [").append(table.getName()).append(']');
} }
this.deckType = sbDeckType.toString(); this.deckType = sbDeckType.toString();
StringBuilder sb1 = new StringBuilder(); StringBuilder sb1 = new StringBuilder();
@ -143,9 +143,9 @@ public class MatchView implements Serializable {
} }
this.players = sb1.toString(); this.players = sb1.toString();
StringBuilder sb2 = new StringBuilder(); StringBuilder sb2 = new StringBuilder();
if (table.getTournament().getRounds().size() > 0) { if (!table.getTournament().getRounds().isEmpty()) {
for (TournamentPlayer tPlayer : table.getTournament().getPlayers()) { for (TournamentPlayer tPlayer : table.getTournament().getPlayers()) {
sb2.append(tPlayer.getPlayer().getName()).append(": ").append(tPlayer.getResults()).append(" "); sb2.append(tPlayer.getPlayer().getName()).append(": ").append(tPlayer.getResults()).append(' ');
} }
} else { } else {
sb2.append("Canceled"); sb2.append("Canceled");

View file

@ -72,7 +72,7 @@ public class PermanentView extends CardView {
this.morphed = permanent.isMorphed(); this.morphed = permanent.isMorphed();
this.manifested = permanent.isManifested(); this.manifested = permanent.isManifested();
this.damage = permanent.getDamage(); this.damage = permanent.getDamage();
if (permanent.getAttachments().size() > 0) { if (!permanent.getAttachments().isEmpty()) {
attachments = new ArrayList<>(); attachments = new ArrayList<>();
attachments.addAll(permanent.getAttachments()); attachments.addAll(permanent.getAttachments());
} }

View file

@ -258,7 +258,7 @@ public class PlayerView implements Serializable {
} }
public boolean hasAttachments() { public boolean hasAttachments() {
return attachments != null && attachments.size() > 0; return attachments != null && !attachments.isEmpty();
} }
public int getStatesSavedSize() { public int getStatesSavedSize() {

View file

@ -101,7 +101,7 @@ public class StackAbilityView extends CardView {
List<String> names = new ArrayList<>(); List<String> names = new ArrayList<>();
for (UUID modeId : ability.getModes().getSelectedModes()) { for (UUID modeId : ability.getModes().getSelectedModes()) {
Mode mode = ability.getModes().get(modeId); Mode mode = ability.getModes().get(modeId);
if (mode.getTargets().size() > 0) { if (!mode.getTargets().isEmpty()) {
setTargets(mode.getTargets()); setTargets(mode.getTargets());
} else { } else {
List<UUID> targetList = new ArrayList<>(); List<UUID> targetList = new ArrayList<>();
@ -111,7 +111,7 @@ public class StackAbilityView extends CardView {
targetList.add(((FixedTarget) targetPointer).getTarget()); targetList.add(((FixedTarget) targetPointer).getTarget());
} }
} }
if (targetList.size() > 0) { if (!targetList.isEmpty()) {
overrideTargets(targetList); overrideTargets(targetList);
for (UUID uuid : targetList) { for (UUID uuid : targetList) {

View file

@ -73,7 +73,7 @@ public class TableView implements Serializable {
this.tableName = table.getName(); this.tableName = table.getName();
String tableNameInfo = null; String tableNameInfo = null;
if (tableName != null && !tableName.isEmpty()) { if (tableName != null && !tableName.isEmpty()) {
tableNameInfo = " [" + table.getName() + "]"; tableNameInfo = " [" + table.getName() + ']';
} }
this.controllerName = table.getControllerName(); this.controllerName = table.getControllerName();
this.tableState = table.getState(); this.tableState = table.getState();
@ -95,7 +95,7 @@ public class TableView implements Serializable {
if (!table.isTournament()) { if (!table.isTournament()) {
// MATCH // MATCH
if (table.getState()==TableState.WAITING || table.getState()==TableState.READY_TO_START) { if (table.getState()==TableState.WAITING || table.getState()==TableState.READY_TO_START) {
tableStateText = table.getState().toString() + " (" + table.getMatch().getPlayers().size() + "/" + table.getSeats().length + ")"; tableStateText = table.getState().toString() + " (" + table.getMatch().getPlayers().size() + '/' + table.getSeats().length + ')';
} else { } else {
tableStateText = table.getState().toString(); tableStateText = table.getState().toString();
} }
@ -107,10 +107,10 @@ public class TableView implements Serializable {
for (MatchPlayer matchPlayer : table.getMatch().getPlayers()) { for (MatchPlayer matchPlayer : table.getMatch().getPlayers()) {
if (matchPlayer.getPlayer() == null) { if (matchPlayer.getPlayer() == null) {
sb.append(", ").append("[unknown]"); sb.append(", ").append("[unknown]");
sbScore.append("-").append(matchPlayer.getWins()); sbScore.append('-').append(matchPlayer.getWins());
} else if (!matchPlayer.getName().equals(table.getControllerName())) { } else if (!matchPlayer.getName().equals(table.getControllerName())) {
sb.append(", ").append(matchPlayer.getName()); sb.append(", ").append(matchPlayer.getName());
sbScore.append("-").append(matchPlayer.getWins()); sbScore.append('-').append(matchPlayer.getWins());
} else { } else {
sbScore.insert(0, matchPlayer.getWins()).insert(0, " Score: "); sbScore.insert(0, matchPlayer.getWins()).insert(0, " Score: ");
} }
@ -140,7 +140,7 @@ public class TableView implements Serializable {
} else { } else {
// TOURNAMENT // TOURNAMENT
if (table.getTournament().getOptions().getNumberRounds() > 0) { if (table.getTournament().getOptions().getNumberRounds() > 0) {
this.gameType = new StringBuilder(this.gameType).append(" ").append(table.getTournament().getOptions().getNumberRounds()).append(" Rounds").toString(); this.gameType = new StringBuilder(this.gameType).append(' ').append(table.getTournament().getOptions().getNumberRounds()).append(" Rounds").toString();
} }
StringBuilder sb1 = new StringBuilder(); StringBuilder sb1 = new StringBuilder();
for (TournamentPlayer tp : table.getTournament().getPlayers()) { for (TournamentPlayer tp : table.getTournament().getPlayers()) {
@ -152,10 +152,10 @@ public class TableView implements Serializable {
StringBuilder infoText = new StringBuilder(); StringBuilder infoText = new StringBuilder();
StringBuilder stateText = new StringBuilder(table.getState().toString()); StringBuilder stateText = new StringBuilder(table.getState().toString());
infoText.append("Wins:").append(table.getTournament().getOptions().getMatchOptions().getWinsNeeded()); infoText.append("Wins:").append(table.getTournament().getOptions().getMatchOptions().getWinsNeeded());
infoText.append(" Seats: ").append(table.getTournament().getPlayers().size()).append("/").append(table.getNumberOfSeats()); infoText.append(" Seats: ").append(table.getTournament().getPlayers().size()).append('/').append(table.getNumberOfSeats());
switch (table.getState()) { switch (table.getState()) {
case WAITING: case WAITING:
stateText.append(" (").append(table.getTournament().getPlayers().size()).append("/").append(table.getNumberOfSeats()).append(")"); stateText.append(" (").append(table.getTournament().getPlayers().size()).append('/').append(table.getNumberOfSeats()).append(')');
case READY_TO_START: case READY_TO_START:
case STARTING: case STARTING:
infoText.append(" Time: ").append(table.getTournament().getOptions().getMatchOptions().getMatchTimeLimit().toString()); infoText.append(" Time: ").append(table.getTournament().getOptions().getMatchOptions().getMatchTimeLimit().toString());
@ -172,13 +172,13 @@ public class TableView implements Serializable {
case DRAFTING: case DRAFTING:
Draft draft = table.getTournament().getDraft(); Draft draft = table.getTournament().getDraft();
if (draft != null) { if (draft != null) {
stateText.append(" ").append(draft.getBoosterNum()).append("/").append(draft.getCardNum() - 1); stateText.append(' ').append(draft.getBoosterNum()).append('/').append(draft.getCardNum() - 1);
} }
default: default:
} }
this.additionalInfo = infoText.toString(); this.additionalInfo = infoText.toString();
this.tableStateText = stateText.toString(); this.tableStateText = stateText.toString();
this.deckType = table.getDeckType() + " " + table.getTournament().getBoosterInfo() + (tableNameInfo != null ? tableNameInfo : ""); this.deckType = table.getDeckType() + ' ' + table.getTournament().getBoosterInfo() + (tableNameInfo != null ? tableNameInfo : "");
this.skillLevel = table.getTournament().getOptions().getMatchOptions().getSkillLevel(); this.skillLevel = table.getTournament().getOptions().getMatchOptions().getSkillLevel();
this.quitRatio = Integer.toString(table.getTournament().getOptions().getQuitRatio()); this.quitRatio = Integer.toString(table.getTournament().getOptions().getQuitRatio());
this.limited = table.getTournament().getOptions().getMatchOptions().isLimited(); this.limited = table.getTournament().getOptions().getMatchOptions().isLimited();

View file

@ -70,14 +70,14 @@ public class TournamentGameView implements Serializable {
if (game.hasEnded()) { if (game.hasEnded()) {
if (game.getEndTime() != null) { if (game.getEndTime() != null) {
duelingTime = " (" + DateFormat.getDuration((game.getEndTime().getTime() - game.getStartTime().getTime())/1000) + ")"; duelingTime = " (" + DateFormat.getDuration((game.getEndTime().getTime() - game.getStartTime().getTime())/1000) + ')';
} }
this.state = "Finished" + duelingTime; this.state = "Finished" + duelingTime;
this.result = game.getWinner(); this.result = game.getWinner();
} }
else { else {
if (game.getStartTime() != null) { if (game.getStartTime() != null) {
duelingTime = " (" + DateFormat.getDuration((new Date().getTime() - game.getStartTime().getTime())/1000) + ")"; duelingTime = " (" + DateFormat.getDuration((new Date().getTime() - game.getStartTime().getTime())/1000) + ')';
} }
this.state = "Dueling" + duelingTime; this.state = "Dueling" + duelingTime;
this.result = ""; this.result = "";

View file

@ -51,7 +51,7 @@ public class TournamentPlayerView implements Serializable, Comparable {
StringBuilder sb = new StringBuilder(tournamentPlayer.getState().toString()); StringBuilder sb = new StringBuilder(tournamentPlayer.getState().toString());
String stateInfo = tournamentPlayer.getStateInfo(); String stateInfo = tournamentPlayer.getStateInfo();
if (!stateInfo.isEmpty()) { if (!stateInfo.isEmpty()) {
sb.append(" (").append(stateInfo).append(")"); sb.append(" (").append(stateInfo).append(')');
} }
sb.append(tournamentPlayer.getDisconnectInfo()); sb.append(tournamentPlayer.getDisconnectInfo());
this.state = sb.toString(); this.state = sb.toString();

View file

@ -67,7 +67,7 @@ public class TournamentView implements Serializable {
typeText.append(" / ").append(tournament.getOptions().getMatchOptions().getDeckType()); typeText.append(" / ").append(tournament.getOptions().getMatchOptions().getDeckType());
} }
if (tournament.getNumberRounds() > 0) { if (tournament.getNumberRounds() > 0) {
typeText.append(" ").append(tournament.getNumberRounds()).append(" rounds"); typeText.append(' ').append(tournament.getNumberRounds()).append(" rounds");
} }
tournamentType = typeText.toString(); tournamentType = typeText.toString();
startTime = tournament.getStartTime(); startTime = tournament.getStartTime();
@ -79,7 +79,7 @@ public class TournamentView implements Serializable {
tournamentState = tournament.getTournamentState(); tournamentState = tournament.getTournamentState();
if (tournament.getTournamentState().equals("Drafting") && tournament.getDraft() != null) { if (tournament.getTournamentState().equals("Drafting") && tournament.getDraft() != null) {
runningInfo = "booster/card: " + tournament.getDraft().getBoosterNum() +"/" + (tournament.getDraft().getCardNum() -1); runningInfo = "booster/card: " + tournament.getDraft().getBoosterNum() + '/' + (tournament.getDraft().getCardNum() -1);
} else { } else {
runningInfo = ""; runningInfo = "";
} }

View file

@ -1,22 +1,15 @@
package org.mage.plugins.counter; package org.mage.plugins.counter;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import mage.interfaces.PluginException; import mage.interfaces.PluginException;
import mage.interfaces.plugin.CounterPlugin; import mage.interfaces.plugin.CounterPlugin;
import net.xeoh.plugins.base.annotations.PluginImplementation; import net.xeoh.plugins.base.annotations.PluginImplementation;
import net.xeoh.plugins.base.annotations.events.Init; import net.xeoh.plugins.base.annotations.events.Init;
import net.xeoh.plugins.base.annotations.events.PluginLoaded; import net.xeoh.plugins.base.annotations.events.PluginLoaded;
import net.xeoh.plugins.base.annotations.meta.Author; import net.xeoh.plugins.base.annotations.meta.Author;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import java.io.*;
/** /**
* Implementation of {@link CounterPlugin}.<br/> * Implementation of {@link CounterPlugin}.<br/>
* Stores data in data folder. * Stores data in data folder.
@ -72,12 +65,10 @@ public class CounterPluginImpl implements CounterPlugin {
public void addGamePlayed() throws PluginException { public void addGamePlayed() throws PluginException {
if (!isLoaded) return; if (!isLoaded) return;
File data = new File(PLUGIN_DATA_FOLDER_PATH + File.separator + DATA_STORAGE_FILE); File data = new File(PLUGIN_DATA_FOLDER_PATH + File.separator + DATA_STORAGE_FILE);
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
if (data.exists()) { if (data.exists()) {
int prev = 0; int prev = 0;
try {
ois = new ObjectInputStream(new FileInputStream(data)); try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(data))) {
Object o = ois.readObject(); Object o = ois.readObject();
CounterBean c; CounterBean c;
if (o instanceof CounterBean) { if (o instanceof CounterBean) {
@ -90,13 +81,10 @@ public class CounterPluginImpl implements CounterPlugin {
throw new PluginException(e); throw new PluginException(e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (ois != null) try { ois.close(); } catch (Exception e) {}
} }
try { try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(data))) {
synchronized (this) { synchronized (this) {
oos = new ObjectOutputStream(new FileOutputStream(data));
CounterBean c = new CounterBean(); CounterBean c = new CounterBean();
c.setGamesPlayed(prev+1); c.setGamesPlayed(prev+1);
oos.writeObject(c); oos.writeObject(c);
@ -104,8 +92,6 @@ public class CounterPluginImpl implements CounterPlugin {
} }
} catch (IOException e) { } catch (IOException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (oos != null) try { oos.close(); } catch (Exception e) {}
} }
} else { } else {
log.error("Counter plugin: data file doesn't exist, please restart plugin."); log.error("Counter plugin: data file doesn't exist, please restart plugin.");
@ -120,10 +106,8 @@ public class CounterPluginImpl implements CounterPlugin {
return 0; return 0;
} }
if (data.exists()) { if (data.exists()) {
ObjectInputStream ois = null; try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(data))) {
try {
synchronized (this) { synchronized (this) {
ois = new ObjectInputStream(new FileInputStream(data));
Object o = ois.readObject(); Object o = ois.readObject();
CounterBean c = null; CounterBean c = null;
if (o instanceof CounterBean) { if (o instanceof CounterBean) {
@ -138,8 +122,6 @@ public class CounterPluginImpl implements CounterPlugin {
throw new PluginException(e); throw new PluginException(e);
} catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
throw new PluginException(e); throw new PluginException(e);
} finally {
if (ois != null) try { ois.close(); } catch (Exception e) {}
} }
} else { } else {
log.error("Counter plugin: data file doesn't exist, please restart plugin."); log.error("Counter plugin: data file doesn't exist, please restart plugin.");

View file

@ -423,7 +423,7 @@ public class ConnectDialog extends JDialog {
connection.setProxyPassword(new String(this.txtPasswordField.getPassword())); connection.setProxyPassword(new String(this.txtPasswordField.getPassword()));
} }
logger.debug("connecting: " + connection.getProxyType() + " " + connection.getProxyHost() + " " + connection.getProxyPort()); logger.debug("connecting: " + connection.getProxyType() + ' ' + connection.getProxyHost() + ' ' + connection.getProxyPort());
task = new ConnectTask(); task = new ConnectTask();
task.execute(); task.execute();

View file

@ -575,14 +575,14 @@ class UpdateUsersTask extends SwingWorker<Void, List<UserView>> {
for (UserView u2 : usersToCheck) { for (UserView u2 : usersToCheck) {
if (u1.getUserName().equals(u2.getUserName())) { if (u1.getUserName().equals(u2.getUserName())) {
found = true; found = true;
String s = u1.getUserName() + "," + u1.getHost(); String s = u1.getUserName() + ',' + u1.getHost();
if (peopleIps.get(s) == null) { if (peopleIps.get(s) == null) {
logger.warn("Found new user: " + u1.getUserName() + "," + u1.getHost()); logger.warn("Found new user: " + u1.getUserName() + ',' + u1.getHost());
peopleIps.put(s, "1"); peopleIps.put(s, "1");
} }
s = u2.getUserName() + "," + u2.getHost(); s = u2.getUserName() + ',' + u2.getHost();
if (peopleIps.get(s) == null) { if (peopleIps.get(s) == null) {
logger.warn("Found new user: " + u1.getUserName() + "," + u1.getHost()); logger.warn("Found new user: " + u1.getUserName() + ',' + u1.getHost());
peopleIps.put(s, "1"); peopleIps.put(s, "1");
} }
break; break;

View file

@ -142,16 +142,16 @@ public class Commander extends Constructed {
} else { } else {
for (Card commander : deck.getSideboard()) { for (Card commander : deck.getSideboard()) {
if (bannedCommander.contains(commander.getName())) { if (bannedCommander.contains(commander.getName())) {
invalid.put("Commander", "Commander banned (" + commander.getName() + ")"); invalid.put("Commander", "Commander banned (" + commander.getName() + ')');
valid = false; valid = false;
} }
if ((!commander.getCardType().contains(CardType.CREATURE) || !commander.getSupertype().contains("Legendary")) if ((!commander.getCardType().contains(CardType.CREATURE) || !commander.getSupertype().contains("Legendary"))
&& (!commander.getCardType().contains(CardType.PLANESWALKER) || !commander.getAbilities().contains(CanBeYourCommanderAbility.getInstance()))) { && (!commander.getCardType().contains(CardType.PLANESWALKER) || !commander.getAbilities().contains(CanBeYourCommanderAbility.getInstance()))) {
invalid.put("Commander", "Commander invalid (" + commander.getName() + ")"); invalid.put("Commander", "Commander invalid (" + commander.getName() + ')');
valid = false; valid = false;
} }
if (deck.getSideboard().size() == 2 && !commander.getAbilities().contains(PartnerAbility.getInstance())) { if (deck.getSideboard().size() == 2 && !commander.getAbilities().contains(PartnerAbility.getInstance())) {
invalid.put("Commander", "Commander without Partner (" + commander.getName() + ")"); invalid.put("Commander", "Commander without Partner (" + commander.getName() + ')');
valid = false; valid = false;
} }
FilterMana commanderColor = CardUtil.getColorIdentity(commander); FilterMana commanderColor = CardUtil.getColorIdentity(commander);
@ -174,7 +174,7 @@ public class Commander extends Constructed {
} }
for (Card card : deck.getCards()) { for (Card card : deck.getCards()) {
if (!cardHasValidColor(colorIdentity, card)) { if (!cardHasValidColor(colorIdentity, card)) {
invalid.put(card.getName(), "Invalid color (" + colorIdentity.toString() + ")"); invalid.put(card.getName(), "Invalid color (" + colorIdentity.toString() + ')');
valid = false; valid = false;
} }
} }

View file

@ -189,11 +189,11 @@ public class TinyLeaders extends Constructed {
} }
} }
} else { } else {
invalid.put("Commander", "Commander banned (" + commander.getName() + ")"); invalid.put("Commander", "Commander banned (" + commander.getName() + ')');
valid = false; valid = false;
} }
} else { } else {
invalid.put("Commander", "Commander invalide (" + commander.getName() + ")"); invalid.put("Commander", "Commander invalide (" + commander.getName() + ')');
valid = false; valid = false;
} }
} else { } else {
@ -221,22 +221,22 @@ public class TinyLeaders extends Constructed {
private boolean isCardFormatValid(Card card, Card commander, FilterMana color) { private boolean isCardFormatValid(Card card, Card commander, FilterMana color) {
if (!cardHasValideColor(color, card)) { if (!cardHasValideColor(color, card)) {
invalid.put(card.getName(), "Invalid color (" + commander.getName() + ")"); invalid.put(card.getName(), "Invalid color (" + commander.getName() + ')');
return false; return false;
} }
//905.5b - Converted mana cost must be 3 or less //905.5b - Converted mana cost must be 3 or less
if (card instanceof SplitCard) { if (card instanceof SplitCard) {
if (((SplitCard) card).getLeftHalfCard().getManaCost().convertedManaCost() > 3) { if (((SplitCard) card).getLeftHalfCard().getManaCost().convertedManaCost() > 3) {
invalid.put(card.getName(), "Invalid cost (" + ((SplitCard) card).getLeftHalfCard().getManaCost().convertedManaCost() + ")"); invalid.put(card.getName(), "Invalid cost (" + ((SplitCard) card).getLeftHalfCard().getManaCost().convertedManaCost() + ')');
return false; return false;
} }
if (((SplitCard) card).getRightHalfCard().getManaCost().convertedManaCost() > 3) { if (((SplitCard) card).getRightHalfCard().getManaCost().convertedManaCost() > 3) {
invalid.put(card.getName(), "Invalid cost (" + ((SplitCard) card).getRightHalfCard().getManaCost().convertedManaCost() + ")"); invalid.put(card.getName(), "Invalid cost (" + ((SplitCard) card).getRightHalfCard().getManaCost().convertedManaCost() + ')');
return false; return false;
} }
} else if (card.getManaCost().convertedManaCost() > 3) { } else if (card.getManaCost().convertedManaCost() > 3) {
invalid.put(card.getName(), "Invalid cost (" + card.getManaCost().convertedManaCost() + ")"); invalid.put(card.getName(), "Invalid cost (" + card.getManaCost().convertedManaCost() + ')');
return false; return false;
} }
return true; return true;

View file

@ -244,9 +244,9 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
logger.info(new StringBuilder("[").append(game.getPlayer(playerId).getName()).append("], life = ").append(player.getLife()).toString()); logger.info(new StringBuilder("[").append(game.getPlayer(playerId).getName()).append("], life = ").append(player.getLife()).toString());
StringBuilder sb = new StringBuilder("-> Hand: ["); StringBuilder sb = new StringBuilder("-> Hand: [");
for (Card card : player.getHand().getCards(game)) { for (Card card : player.getHand().getCards(game)) {
sb.append(card.getName()).append(";"); sb.append(card.getName()).append(';');
} }
logger.info(sb.append("]").toString()); logger.info(sb.append(']').toString());
sb.setLength(0); sb.setLength(0);
sb.append("-> Permanents: ["); sb.append("-> Permanents: [");
for (Permanent permanent : game.getBattlefield().getAllPermanents()) { for (Permanent permanent : game.getBattlefield().getAllPermanents()) {
@ -258,10 +258,10 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
if (permanent.isAttacking()) { if (permanent.isAttacking()) {
sb.append("(attacking)"); sb.append("(attacking)");
} }
sb.append(";"); sb.append(';');
} }
} }
logger.info(sb.append("]").toString()); logger.info(sb.append(']').toString());
} }
protected void act(Game game) { protected void act(Game game) {
@ -272,7 +272,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
while (actions.peek() != null) { while (actions.peek() != null) {
Ability ability = actions.poll(); Ability ability = actions.poll();
logger.info(new StringBuilder("===> Act [").append(game.getPlayer(playerId).getName()).append("] Action: ").append(ability.toString()).toString()); logger.info(new StringBuilder("===> Act [").append(game.getPlayer(playerId).getName()).append("] Action: ").append(ability.toString()).toString());
if (ability.getTargets().size() > 0) { if (!ability.getTargets().isEmpty()) {
for (Target target : ability.getTargets()) { for (Target target : ability.getTargets()) {
for (UUID id : target.getTargets()) { for (UUID id : target.getTargets()) {
target.updateTarget(id, game); target.updateTarget(id, game);
@ -318,7 +318,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
//int bestScore = addActionsTimed(new FilterAbility()); //int bestScore = addActionsTimed(new FilterAbility());
currentScore = GameStateEvaluator2.evaluate(playerId, game); currentScore = GameStateEvaluator2.evaluate(playerId, game);
addActionsTimed(); addActionsTimed();
if (root.children.size() > 0) { if (!root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
//GameStateEvaluator2.evaluate(playerId, root.getGame()); //GameStateEvaluator2.evaluate(playerId, root.getGame());
int bestScore = root.getScore(); int bestScore = root.getScore();
@ -329,16 +329,16 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
//System.out.println("[" + game.getPlayer(playerId).getName() + "] Action: not better score"); //System.out.println("[" + game.getPlayer(playerId).getName() + "] Action: not better score");
//} //}
} else { } else {
logger.info("[" + game.getPlayer(playerId).getName() + "] Action: skip Root.score = " + root.getScore() + " currentScore = " + currentScore); logger.info('[' + game.getPlayer(playerId).getName() + "] Action: skip Root.score = " + root.getScore() + " currentScore = " + currentScore);
} }
} }
} }
protected boolean getNextAction(Game game) { protected boolean getNextAction(Game game) {
if (root != null && root.children.size() > 0) { if (root != null && !root.children.isEmpty()) {
SimulationNode2 test = root; SimulationNode2 test = root;
root = root.children.get(0); root = root.children.get(0);
while (root.children.size() > 0 && !root.playerId.equals(playerId)) { while (!root.children.isEmpty() && !root.playerId.equals(playerId)) {
test = root; test = root;
root = root.children.get(0); root = root.children.get(0);
} }
@ -372,7 +372,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
} }
protected int minimaxAB(SimulationNode2 node, int depth, int alpha, int beta) { protected int minimaxAB(SimulationNode2 node, int depth, int alpha, int beta) {
logger.trace("Sim minimaxAB [" + depth + "] -- a: " + alpha + " b: " + beta + " <" + (node != null ? node.getScore() : "null") + ">"); logger.trace("Sim minimaxAB [" + depth + "] -- a: " + alpha + " b: " + beta + " <" + (node != null ? node.getScore() : "null") + '>');
UUID currentPlayerId = node.getGame().getPlayerList().get(); UUID currentPlayerId = node.getGame().getPlayerList().get();
SimulationNode2 bestChild = null; SimulationNode2 bestChild = null;
for (SimulationNode2 child : node.getChildren()) { for (SimulationNode2 child : node.getChildren()) {
@ -525,7 +525,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
UUID currentPlayerId = node.getGame().getPlayerList().get(); UUID currentPlayerId = node.getGame().getPlayerList().get();
//logger.info("reached - " + val + ", playerId=" + playerId + ", node.pid="+currentPlayerId); //logger.info("reached - " + val + ", playerId=" + playerId + ", node.pid="+currentPlayerId);
return val; return val;
} else if (node.getChildren().size() > 0) { } else if (!node.getChildren().isEmpty()) {
logger.trace("Add actions -- something added children:" + node.getChildren().size()); logger.trace("Add actions -- something added children:" + node.getChildren().size());
val = minimaxAB(node, depth - 1, alpha, beta); val = minimaxAB(node, depth - 1, alpha, beta);
return val; return val;
@ -542,7 +542,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
if (game.gameOver(null)) { if (game.gameOver(null)) {
val = GameStateEvaluator2.evaluate(playerId, game); val = GameStateEvaluator2.evaluate(playerId, game);
} else if (node.getChildren().size() > 0) { } else if (!node.getChildren().isEmpty()) {
//declared attackers or blockers or triggered abilities //declared attackers or blockers or triggered abilities
logger.debug("Add actions -- attack/block/trigger added children:" + node.getChildren().size()); logger.debug("Add actions -- attack/block/trigger added children:" + node.getChildren().size());
val = minimaxAB(node, depth - 1, alpha, beta); val = minimaxAB(node, depth - 1, alpha, beta);
@ -568,8 +568,8 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
SimulationNode2 bestNode = null; SimulationNode2 bestNode = null;
List<Ability> allActions = currentPlayer.simulatePriority(game); List<Ability> allActions = currentPlayer.simulatePriority(game);
optimize(game, allActions); optimize(game, allActions);
if (logger.isInfoEnabled() && allActions.size() > 0 && depth == maxDepth) { if (logger.isInfoEnabled() && !allActions.isEmpty() && depth == maxDepth) {
logger.info("ADDED ACTIONS (" + allActions.size() + ") " + " " + allActions); logger.info("ADDED ACTIONS (" + allActions.size() + ") " + ' ' + allActions);
} }
int counter = 0; int counter = 0;
int bestValSubNodes = Integer.MIN_VALUE; int bestValSubNodes = Integer.MIN_VALUE;
@ -606,18 +606,18 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
} else { } else {
val = addActions(newNode, depth - 1, alpha, beta); val = addActions(newNode, depth - 1, alpha, beta);
} }
logger.debug("Sim Prio " + BLANKS.substring(0, 2 + (maxDepth - depth) * 3) + "[" + depth + "]#" + counter + " <" + val + "> - (" + action.toString() + ") "); logger.debug("Sim Prio " + BLANKS.substring(0, 2 + (maxDepth - depth) * 3) + '[' + depth + "]#" + counter + " <" + val + "> - (" + action.toString() + ") ");
if (logger.isInfoEnabled() && depth >= maxDepth) { if (logger.isInfoEnabled() && depth >= maxDepth) {
StringBuilder sb = new StringBuilder("Sim Prio [").append(depth).append("] #").append(counter) StringBuilder sb = new StringBuilder("Sim Prio [").append(depth).append("] #").append(counter)
.append(" <").append(val).append("> (").append(action) .append(" <").append(val).append("> (").append(action)
.append(action.isModal() ? " Mode = " + action.getModes().getMode().toString() : "") .append(action.isModal() ? " Mode = " + action.getModes().getMode().toString() : "")
.append(listTargets(game, action.getTargets())).append(")") .append(listTargets(game, action.getTargets())).append(')')
.append(logger.isTraceEnabled() ? " #" + newNode.hashCode() : ""); .append(logger.isTraceEnabled() ? " #" + newNode.hashCode() : "");
SimulationNode2 logNode = newNode; SimulationNode2 logNode = newNode;
while (logNode.getChildren() != null && logNode.getChildren().size() > 0) { while (logNode.getChildren() != null && !logNode.getChildren().isEmpty()) {
logNode = logNode.getChildren().get(0); logNode = logNode.getChildren().get(0);
if (logNode.getAbilities() != null && logNode.getAbilities().size() > 0) { if (logNode.getAbilities() != null && !logNode.getAbilities().isEmpty()) {
sb.append(" -> [").append(logNode.getDepth()).append("]").append(logNode.getAbilities().toString()).append("<").append(logNode.getScore()).append(">"); sb.append(" -> [").append(logNode.getDepth()).append(']').append(logNode.getAbilities().toString()).append('<').append(logNode.getScore()).append('>');
} }
} }
logger.info(sb); logger.info(sb);
@ -634,7 +634,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
alpha = val; alpha = val;
bestNode = newNode; bestNode = newNode;
bestNode.setScore(val); bestNode.setScore(val);
if (newNode.getChildren().size() > 0) { if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat()); bestNode.setCombat(newNode.getChildren().get(0).getCombat());
} }
/* /*
@ -660,7 +660,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
beta = val; beta = val;
bestNode = newNode; bestNode = newNode;
bestNode.setScore(val); bestNode.setScore(val);
if (newNode.getChildren().size() > 0) { if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat()); bestNode.setCombat(newNode.getChildren().get(0).getCombat());
} }
} }
@ -1437,7 +1437,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
if (targets != null) { if (targets != null) {
for (Target target : targets) { for (Target target : targets) {
sb.append("[").append(target.getTargetedName(game)).append("]"); sb.append('[').append(target.getTargetedName(game)).append(']');
} }
if (sb.length() > 0) { if (sb.length() > 0) {
sb.insert(0, " targeting "); sb.insert(0, " targeting ");

View file

@ -164,7 +164,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
addActionsTimed(); addActionsTimed();
logger.trace("After add actions timed: root.children.size = " + root.children.size()); logger.trace("After add actions timed: root.children.size = " + root.children.size());
if (root.children.size() > 0) { if (!root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
// int bestScore = root.getScore(); // int bestScore = root.getScore();
// if (bestScore > currentScore || allowBadMoves) { // if (bestScore > currentScore || allowBadMoves) {
@ -174,7 +174,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
if (root.abilities.size() == 1) { if (root.abilities.size() == 1) {
for (Ability ability : root.abilities) { for (Ability ability : root.abilities) {
if (ability.getManaCosts().convertedManaCost() == 0 && ability.getCosts().isEmpty()) { if (ability.getManaCosts().convertedManaCost() == 0 && ability.getCosts().isEmpty()) {
if (actionCache.contains(ability.getRule() + "_" + ability.getSourceId())) { if (actionCache.contains(ability.getRule() + '_' + ability.getSourceId())) {
doThis = false; // don't do it again doThis = false; // don't do it again
} }
} }
@ -184,11 +184,11 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
actions = new LinkedList<>(root.abilities); actions = new LinkedList<>(root.abilities);
combat = root.combat; combat = root.combat;
for (Ability ability : actions) { for (Ability ability : actions) {
actionCache.add(ability.getRule() + "_" + ability.getSourceId()); actionCache.add(ability.getRule() + '_' + ability.getSourceId());
} }
} }
} else { } else {
logger.info("[" + game.getPlayer(playerId).getName() + "][pre] Action: skip"); logger.info('[' + game.getPlayer(playerId).getName() + "][pre] Action: skip");
} }
} else { } else {
logger.debug("Next Action exists!"); logger.debug("Next Action exists!");
@ -204,17 +204,17 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
logger.debug("Sim Calculate post combat actions ----------------------------------------------------------------------------------------"); logger.debug("Sim Calculate post combat actions ----------------------------------------------------------------------------------------");
addActionsTimed(); addActionsTimed();
if (root != null && root.children.size() > 0) { if (root != null && !root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
int bestScore = root.getScore(); int bestScore = root.getScore();
if (bestScore > currentScore || allowBadMoves) { if (bestScore > currentScore || allowBadMoves) {
actions = new LinkedList<>(root.abilities); actions = new LinkedList<>(root.abilities);
combat = root.combat; combat = root.combat;
} else { } else {
logger.debug("[" + game.getPlayer(playerId).getName() + "] no better score current: " + currentScore + " bestScore: " + bestScore); logger.debug('[' + game.getPlayer(playerId).getName() + "] no better score current: " + currentScore + " bestScore: " + bestScore);
} }
} else { } else {
logger.debug("[" + game.getPlayer(playerId).getName() + "][post] Action: skip"); logger.debug('[' + game.getPlayer(playerId).getName() + "][post] Action: skip");
} }
} }
} }
@ -236,15 +236,15 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
if (depth <= 0 || SimulationNode2.nodeCount > maxNodes || game.gameOver(null)) { if (depth <= 0 || SimulationNode2.nodeCount > maxNodes || game.gameOver(null)) {
val = GameStateEvaluator2.evaluate(playerId, game); val = GameStateEvaluator2.evaluate(playerId, game);
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("Add Actions -- reached end state <").append(val).append(">"); StringBuilder sb = new StringBuilder("Add Actions -- reached end state <").append(val).append('>');
SimulationNode2 logNode = node; SimulationNode2 logNode = node;
do { do {
sb.append(new StringBuilder(" <- [" + logNode.getDepth() + "]" + (logNode.getAbilities() != null ? logNode.getAbilities().toString() : "[empty]"))); sb.append(new StringBuilder(" <- [" + logNode.getDepth() + ']' + (logNode.getAbilities() != null ? logNode.getAbilities().toString() : "[empty]")));
logNode = logNode.getParent(); logNode = logNode.getParent();
} while ((logNode.getParent() != null)); } while ((logNode.getParent() != null));
logger.trace(sb); logger.trace(sb);
} }
} else if (node.getChildren().size() > 0) { } else if (!node.getChildren().isEmpty()) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("Add Action [").append(depth) StringBuilder sb = new StringBuilder("Add Action [").append(depth)
.append("] -- something added children ") .append("] -- something added children ")
@ -253,7 +253,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
for (SimulationNode2 logNode : node.getChildren()) { for (SimulationNode2 logNode : node.getChildren()) {
sb.append(logNode.getAbilities() != null ? logNode.getAbilities().toString() : "null").append(", "); sb.append(logNode.getAbilities() != null ? logNode.getAbilities().toString() : "null").append(", ");
} }
sb.append(")"); sb.append(')');
logger.debug(sb); logger.debug(sb);
} }
val = minimaxAB(node, depth - 1, alpha, beta); val = minimaxAB(node, depth - 1, alpha, beta);
@ -299,7 +299,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
val = GameStateEvaluator2.evaluate(playerId, game); val = GameStateEvaluator2.evaluate(playerId, game);
*/ */
} }
} else if (node.getChildren().size() > 0) { } else if (!node.getChildren().isEmpty()) {
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
StringBuilder sb = new StringBuilder("Add Action [").append(depth) StringBuilder sb = new StringBuilder("Add Action [").append(depth)
.append("] -- trigger ") .append("] -- trigger ")
@ -308,7 +308,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
for (SimulationNode2 logNode : node.getChildren()) { for (SimulationNode2 logNode : node.getChildren()) {
sb.append(logNode.getAbilities() != null ? logNode.getAbilities().toString() : "null").append(", "); sb.append(logNode.getAbilities() != null ? logNode.getAbilities().toString() : "null").append(", ");
} }
sb.append(")"); sb.append(')');
logger.debug(sb); logger.debug(sb);
} }
@ -411,7 +411,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
beta = val; beta = val;
bestNode = newNode; bestNode = newNode;
bestNode.setScore(val); bestNode.setScore(val);
if (newNode.getChildren().size() > 0) { if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat()); bestNode.setCombat(newNode.getChildren().get(0).getCombat());
} }
} }
@ -419,7 +419,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
alpha = val; alpha = val;
bestNode = newNode; bestNode = newNode;
bestNode.setScore(val); bestNode.setScore(val);
if (newNode.getChildren().size() > 0) { if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat()); bestNode.setCombat(newNode.getChildren().get(0).getCombat());
} }
} }
@ -460,7 +460,7 @@ public class ComputerPlayer7 extends ComputerPlayer6 {
} }
Game sim = game.copy(); Game sim = game.copy();
for (CombatGroup group : engagement.getGroups()) { for (CombatGroup group : engagement.getGroups()) {
if (group.getAttackers().size() > 0) { if (!group.getAttackers().isEmpty()) {
UUID attackerId = group.getAttackers().get(0); UUID attackerId = group.getAttackers().get(0);
for (UUID blockerId : group.getBlockers()) { for (UUID blockerId : group.getBlockers()) {
sim.getPlayer(defenderId).declareBlocker(defenderId, blockerId, attackerId, sim); sim.getPlayer(defenderId).declareBlocker(defenderId, blockerId, attackerId, sim);

View file

@ -64,7 +64,7 @@ public class GameStateEvaluator2 {
int onePermScore = evaluatePermanent(permanent, game); int onePermScore = evaluatePermanent(permanent, game);
playerScore += onePermScore; playerScore += onePermScore;
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
sbPlayer.append(permanent.getName()).append("[").append(onePermScore).append("] "); sbPlayer.append(permanent.getName()).append('[').append(onePermScore).append("] ");
} }
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
@ -78,7 +78,7 @@ public class GameStateEvaluator2 {
int onePermScore = evaluatePermanent(permanent, game); int onePermScore = evaluatePermanent(permanent, game);
opponentScore += onePermScore; opponentScore += onePermScore;
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
sbOpponent.append(permanent.getName()).append("[").append(onePermScore).append("] "); sbOpponent.append(permanent.getName()).append('[').append(onePermScore).append("] ");
} }
} }
if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) {
@ -97,7 +97,7 @@ public class GameStateEvaluator2 {
handScore *= 5; handScore *= 5;
int score = lifeScore + permanentScore + handScore; int score = lifeScore + permanentScore + handScore;
logger.debug(score + " total Score (life:" + lifeScore + " permanents:" + permanentScore + " hand:" + handScore + ")"); logger.debug(score + " total Score (life:" + lifeScore + " permanents:" + permanentScore + " hand:" + handScore + ')');
return score; return score;
} }

View file

@ -60,7 +60,7 @@ public class SimulatedAction2 {
} }
public boolean usesStack() { public boolean usesStack() {
if (abilities != null && abilities.size() > 0) { if (abilities != null && !abilities.isEmpty()) {
return abilities.get(abilities.size() -1).isUsesStack(); return abilities.get(abilities.size() -1).isUsesStack();
} }
return true; return true;

View file

@ -103,7 +103,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
if (logger.isTraceEnabled()) { if (logger.isTraceEnabled()) {
for (Ability a : allActions) { for (Ability a : allActions) {
logger.info("ability==" + a); logger.info("ability==" + a);
if (a.getTargets().size() > 0) { if (!a.getTargets().isEmpty()) {
MageObject mageObject = game.getObject(a.getFirstTarget()); MageObject mageObject = game.getObject(a.getFirstTarget());
if (mageObject != null) { if (mageObject != null) {
logger.info(" target=" + mageObject.getName()); logger.info(" target=" + mageObject.getName());
@ -170,14 +170,14 @@ public class SimulatedPlayer2 extends ComputerPlayer {
} }
} }
// add the specific value for x // add the specific value for x
newAbility.getManaCostsToPay().add(new ManaCostsImpl(new StringBuilder("{").append(xAmount).append("}").toString())); newAbility.getManaCostsToPay().add(new ManaCostsImpl(new StringBuilder("{").append(xAmount).append('}').toString()));
newAbility.getManaCostsToPay().setX(xAmount); newAbility.getManaCostsToPay().setX(xAmount);
if (varCost != null) { if (varCost != null) {
varCost.setPaid(); varCost.setPaid();
} }
card.adjustTargets(newAbility, game); card.adjustTargets(newAbility, game);
// add the different possible target option for the specific X value // add the different possible target option for the specific X value
if (newAbility.getTargets().getUnchosen().size() > 0) { if (!newAbility.getTargets().getUnchosen().isEmpty()) {
addTargetOptions(options, newAbility, targetNum, game); addTargetOptions(options, newAbility, targetNum, game);
} }
} }
@ -240,7 +240,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
} }
List<Ability> filtered = new ArrayList<>(); List<Ability> filtered = new ArrayList<>();
for (Ability option : options) { for (Ability option : options) {
if (option.getTargets().size() > 0 && option.getTargets().get(0).getMaxNumberOfTargets() == 1) { if (!option.getTargets().isEmpty() && option.getTargets().get(0).getMaxNumberOfTargets() == 1) {
Card card = game.getCard(ability.getSourceId()); Card card = game.getCard(ability.getSourceId());
for (String s : suggested) { for (String s : suggested) {
String[] groups = s.split(";"); String[] groups = s.split(";");
@ -338,7 +338,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
binary.setLength(0); binary.setLength(0);
binary.append(Integer.toBinaryString(i)); binary.append(Integer.toBinaryString(i));
while (binary.length() < attackersList.size()) { while (binary.length() < attackersList.size()) {
binary.insert(0, "0"); binary.insert(0, '0');
} }
for (int j = 0; j < attackersList.size(); j++) { for (int j = 0; j < attackersList.size(); j++) {
if (binary.charAt(j) == '1') { if (binary.charAt(j) == '1') {

View file

@ -161,7 +161,7 @@ public class CombatUtil {
UUID attackerId = game.getCombat().getAttackerId(); UUID attackerId = game.getCombat().getAttackerId();
UUID defenderId = game.getCombat().getDefenders().iterator().next(); UUID defenderId = game.getCombat().getDefenders().iterator().next();
if (attackerId == null || defenderId == null) { if (attackerId == null || defenderId == null) {
log.warn("Couldn't find attacker or defender: " + attackerId + " " + defenderId); log.warn("Couldn't find attacker or defender: " + attackerId + ' ' + defenderId);
return new CombatInfo(); return new CombatInfo();
} }
@ -298,7 +298,7 @@ public class CombatUtil {
UUID attackerId = game.getCombat().getAttackerId(); UUID attackerId = game.getCombat().getAttackerId();
UUID defenderId = game.getCombat().getDefenders().iterator().next(); UUID defenderId = game.getCombat().getDefenders().iterator().next();
if (attackerId == null || defenderId == null) { if (attackerId == null || defenderId == null) {
log.warn("Couldn't find attacker or defender: " + attackerId + " " + defenderId); log.warn("Couldn't find attacker or defender: " + attackerId + ' ' + defenderId);
return new CombatInfo(); return new CombatInfo();
} }

View file

@ -199,7 +199,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override @Override
public boolean choose(Outcome outcome, Target target, UUID sourceId, Game game, Map<String, Serializable> options) { public boolean choose(Outcome outcome, Target target, UUID sourceId, Game game, Map<String, Serializable> options) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("chooseTarget: " + outcome.toString() + ":" + target.toString()); log.debug("chooseTarget: " + outcome.toString() + ':' + target.toString());
} }
// sometimes a target selection can be made from a player that does not control the ability // sometimes a target selection can be made from a player that does not control the ability
UUID abilityControllerId = playerId; UUID abilityControllerId = playerId;
@ -212,7 +212,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
if (target.getOriginalTarget() instanceof TargetDiscard) { if (target.getOriginalTarget() instanceof TargetDiscard) {
findPlayables(game); findPlayables(game);
if (unplayable.size() > 0) { if (!unplayable.isEmpty()) {
for (int i = unplayable.size() - 1; i >= 0; i--) { for (int i = unplayable.size() - 1; i >= 0; i--) {
if (target.canTarget(unplayable.values().toArray(new Card[0])[i].getId(), game)) { if (target.canTarget(unplayable.values().toArray(new Card[0])[i].getId(), game)) {
target.add(unplayable.values().toArray(new Card[0])[i].getId(), game); target.add(unplayable.values().toArray(new Card[0])[i].getId(), game);
@ -222,7 +222,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
} }
} }
if (hand.size() > 0) { if (!hand.isEmpty()) {
for (int i = 0; i < hand.size(); i++) { for (int i = 0; i < hand.size(); i++) {
if (target.canTarget(hand.toArray(new UUID[0])[i], game)) { if (target.canTarget(hand.toArray(new UUID[0])[i], game)) {
target.add(hand.toArray(new UUID[0])[i], game); target.add(hand.toArray(new UUID[0])[i], game);
@ -450,7 +450,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override @Override
public boolean chooseTarget(Outcome outcome, Target target, Ability source, Game game) { public boolean chooseTarget(Outcome outcome, Target target, Ability source, Game game) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("chooseTarget: " + outcome.toString() + ":" + target.toString()); log.debug("chooseTarget: " + outcome.toString() + ':' + target.toString());
} }
// sometimes a target selection can be made from a player that does not control the ability // sometimes a target selection can be made from a player that does not control the ability
UUID abilityControllerId = playerId; UUID abilityControllerId = playerId;
@ -467,7 +467,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
Cards cards = new CardsImpl(target.possibleTargets(source.getSourceId(), getId(), game)); Cards cards = new CardsImpl(target.possibleTargets(source.getSourceId(), getId(), game));
ArrayList<Card> cardsInHand = new ArrayList<>(cards.getCards(game)); ArrayList<Card> cardsInHand = new ArrayList<>(cards.getCards(game));
while (!target.isChosen() while (!target.isChosen()
&& target.possibleTargets(source.getSourceId(), getId(), game).size() > 0 && !target.possibleTargets(source.getSourceId(), getId(), game).isEmpty()
&& target.getMaxNumberOfTargets() > target.getTargets().size()) { && target.getMaxNumberOfTargets() > target.getTargets().size()) {
Card card = pickBestCard(cardsInHand, null, target, source, game); Card card = pickBestCard(cardsInHand, null, target, source, game);
if (card != null) { if (card != null) {
@ -482,7 +482,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
} else { } else {
findPlayables(game); findPlayables(game);
if (unplayable.size() > 0) { if (!unplayable.isEmpty()) {
for (int i = unplayable.size() - 1; i >= 0; i--) { for (int i = unplayable.size() - 1; i >= 0; i--) {
if (target.canTarget(getId(), unplayable.values().toArray(new Card[0])[i].getId(), source, game)) { if (target.canTarget(getId(), unplayable.values().toArray(new Card[0])[i].getId(), source, game)) {
target.addTarget(unplayable.values().toArray(new Card[0])[i].getId(), source, game); target.addTarget(unplayable.values().toArray(new Card[0])[i].getId(), source, game);
@ -492,7 +492,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
} }
} }
if (hand.size() > 0) { if (!hand.isEmpty()) {
for (int i = 0; i < hand.size(); i++) { for (int i = 0; i < hand.size(); i++) {
if (target.canTarget(getId(), hand.toArray(new UUID[0])[i], source, game)) { if (target.canTarget(getId(), hand.toArray(new UUID[0])[i], source, game)) {
target.addTarget(hand.toArray(new UUID[0])[i], source, game); target.addTarget(hand.toArray(new UUID[0])[i], source, game);
@ -674,7 +674,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
return target.isChosen(); return target.isChosen();
} }
if (target.getOriginalTarget() instanceof TargetSpell) { if (target.getOriginalTarget() instanceof TargetSpell) {
if (game.getStack().size() > 0) { if (!game.getStack().isEmpty()) {
Iterator<StackObject> it = game.getStack().iterator(); Iterator<StackObject> it = game.getStack().iterator();
while (it.hasNext()) { while (it.hasNext()) {
StackObject o = it.next(); StackObject o = it.next();
@ -708,7 +708,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
} }
} }
if (game.getStack().size() > 0) { if (!game.getStack().isEmpty()) {
Iterator<StackObject> it = game.getStack().iterator(); Iterator<StackObject> it = game.getStack().iterator();
while (it.hasNext()) { while (it.hasNext()) {
StackObject stackObject = it.next(); StackObject stackObject = it.next();
@ -817,7 +817,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override @Override
public boolean chooseTargetAmount(Outcome outcome, TargetAmount target, Ability source, Game game) { public boolean chooseTargetAmount(Outcome outcome, TargetAmount target, Ability source, Game game) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("chooseTarget: " + outcome.toString() + ":" + target.toString()); log.debug("chooseTarget: " + outcome.toString() + ':' + target.toString());
} }
UUID opponentId = game.getOpponents(playerId).iterator().next(); UUID opponentId = game.getOpponents(playerId).iterator().next();
if (target.getOriginalTarget() instanceof TargetCreatureOrPlayerAmount) { if (target.getOriginalTarget() instanceof TargetCreatureOrPlayerAmount) {
@ -878,7 +878,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
break; break;
case PRECOMBAT_MAIN: case PRECOMBAT_MAIN:
findPlayables(game); findPlayables(game);
if (playableAbilities.size() > 0) { if (!playableAbilities.isEmpty()) {
for (ActivatedAbility ability : playableAbilities) { for (ActivatedAbility ability : playableAbilities) {
if (ability.canActivate(playerId, game)) { if (ability.canActivate(playerId, game)) {
if (ability.getEffects().hasOutcome(Outcome.PutLandInPlay)) { if (ability.getEffects().hasOutcome(Outcome.PutLandInPlay)) {
@ -909,7 +909,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
case POSTCOMBAT_MAIN: case POSTCOMBAT_MAIN:
findPlayables(game); findPlayables(game);
if (game.getStack().isEmpty()) { if (game.getStack().isEmpty()) {
if (playableNonInstant.size() > 0) { if (!playableNonInstant.isEmpty()) {
for (Card card : playableNonInstant) { for (Card card : playableNonInstant) {
if (card.getSpellAbility().canActivate(playerId, game)) { if (card.getSpellAbility().canActivate(playerId, game)) {
if (this.activateAbility(card.getSpellAbility(), game)) { if (this.activateAbility(card.getSpellAbility(), game)) {
@ -918,7 +918,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
} }
} }
if (playableAbilities.size() > 0) { if (!playableAbilities.isEmpty()) {
for (ActivatedAbility ability : playableAbilities) { for (ActivatedAbility ability : playableAbilities) {
if (ability.canActivate(playerId, game)) { if (ability.canActivate(playerId, game)) {
if (!(ability.getEffects().get(0) instanceof BecomesCreatureSourceEffect)) { if (!(ability.getEffects().get(0) instanceof BecomesCreatureSourceEffect)) {
@ -975,7 +975,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
} }
lands.add(landCard); lands.add(landCard);
} }
while (lands.size() > 0 && this.canPlayLand()) { while (!lands.isEmpty() && this.canPlayLand()) {
if (lands.size() == 1) { if (lands.size() == 1) {
this.playLand(lands.iterator().next(), game, false); this.playLand(lands.iterator().next(), game, false);
} else { } else {
@ -1030,7 +1030,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (Card card : nonLands) { for (Card card : nonLands) {
ManaOptions options = card.getManaCost().getOptions(); ManaOptions options = card.getManaCost().getOptions();
if (card.getManaCost().getVariableCosts().size() > 0) { if (!card.getManaCost().getVariableCosts().isEmpty()) {
//don't use variable mana costs unless there is at least 3 extra mana for X //don't use variable mana costs unless there is at least 3 extra mana for X
for (Mana option : options) { for (Mana option : options) {
option.add(Mana.GenericMana(3)); option.add(Mana.GenericMana(3));
@ -1062,7 +1062,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
continue; continue;
} }
ManaOptions abilityOptions = ability.getManaCosts().getOptions(); ManaOptions abilityOptions = ability.getManaCosts().getOptions();
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
//don't use variable mana costs unless there is at least 3 extra mana for X //don't use variable mana costs unless there is at least 3 extra mana for X
for (Mana option : abilityOptions) { for (Mana option : abilityOptions) {
option.add(Mana.GenericMana(3)); option.add(Mana.GenericMana(3));
@ -1386,7 +1386,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (Permanent permanent : game.getBattlefield().getActivePermanents(this.getId(), game)) { for (Permanent permanent : game.getBattlefield().getActivePermanents(this.getId(), game)) {
if (game.getOpponents(this.getId()).contains(permanent.getControllerId()) if (game.getOpponents(this.getId()).contains(permanent.getControllerId())
&& permanent.getCardType().contains(CardType.CREATURE) && permanent.getCardType().contains(CardType.CREATURE)
&& permanent.getSubtype(game).size() > 0) { && !permanent.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(permanent.getSubtype(game).get(0))) { if (choice.getChoices().contains(permanent.getSubtype(game).get(0))) {
choice.setChoice(permanent.getSubtype(game).get(0)); choice.setChoice(permanent.getSubtype(game).get(0));
break; break;
@ -1398,7 +1398,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (UUID opponentId : game.getOpponents(this.getId())) { for (UUID opponentId : game.getOpponents(this.getId())) {
Player opponent = game.getPlayer(opponentId); Player opponent = game.getPlayer(opponentId);
for (Card card : opponent.getGraveyard().getCards(game)) { for (Card card : opponent.getGraveyard().getCards(game)) {
if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype(game).size() > 0) { if (card != null && card.getCardType().contains(CardType.CREATURE) && !card.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(card.getSubtype(game).get(0))) { if (choice.getChoices().contains(card.getSubtype(game).get(0))) {
choice.setChoice(card.getSubtype(game).get(0)); choice.setChoice(card.getSubtype(game).get(0));
break; break;
@ -1414,7 +1414,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
// choose a creature type of hand or library // choose a creature type of hand or library
for (UUID cardId : this.getHand()) { for (UUID cardId : this.getHand()) {
Card card = game.getCard(cardId); Card card = game.getCard(cardId);
if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype(game).size() > 0) { if (card != null && card.getCardType().contains(CardType.CREATURE) && !card.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(card.getSubtype(game).get(0))) { if (choice.getChoices().contains(card.getSubtype(game).get(0))) {
choice.setChoice(card.getSubtype(game).get(0)); choice.setChoice(card.getSubtype(game).get(0));
break; break;
@ -1424,7 +1424,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
if (!choice.isChosen()) { if (!choice.isChosen()) {
for (UUID cardId : this.getLibrary().getCardList()) { for (UUID cardId : this.getLibrary().getCardList()) {
Card card = game.getCard(cardId); Card card = game.getCard(cardId);
if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype(game).size() > 0) { if (card != null && card.getCardType().contains(CardType.CREATURE) && !card.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(card.getSubtype(game).get(0))) { if (choice.getChoices().contains(card.getSubtype(game).get(0))) {
choice.setChoice(card.getSubtype(game).get(0)); choice.setChoice(card.getSubtype(game).get(0));
break; break;
@ -1545,7 +1545,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
MageObject object = game.getObject(ability.getSourceId()); MageObject object = game.getObject(ability.getSourceId());
if (object != null) { if (object != null) {
LinkedHashMap<UUID, ActivatedAbility> useableAbilities = getSpellAbilities(object, game.getState().getZone(object.getId()), game); LinkedHashMap<UUID, ActivatedAbility> useableAbilities = getSpellAbilities(object, game.getState().getZone(object.getId()), game);
if (useableAbilities != null && useableAbilities.size() > 0) { if (useableAbilities != null && !useableAbilities.isEmpty()) {
game.fireGetChoiceEvent(playerId, name, object, new ArrayList<>(useableAbilities.values())); game.fireGetChoiceEvent(playerId, name, object, new ArrayList<>(useableAbilities.values()));
// TODO: Improve this // TODO: Improve this
return (SpellAbility) useableAbilities.values().iterator().next(); return (SpellAbility) useableAbilities.values().iterator().next();
@ -1584,7 +1584,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
public TriggeredAbility chooseTriggeredAbility(List<TriggeredAbility> abilities, Game game) { public TriggeredAbility chooseTriggeredAbility(List<TriggeredAbility> abilities, Game game) {
log.debug("chooseTriggeredAbility: " + abilities.toString()); log.debug("chooseTriggeredAbility: " + abilities.toString());
//TODO: improve this //TODO: improve this
if (abilities.size() > 0) { if (!abilities.isEmpty()) {
return abilities.get(0); return abilities.get(0);
} }
return null; return null;
@ -1729,7 +1729,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override @Override
public void construct(Tournament tournament, Deck deck) { public void construct(Tournament tournament, Deck deck) {
if (deck != null && deck.getCards().size() < 40 && deck.getSideboard().size() > 0) { if (deck != null && deck.getCards().size() < 40 && !deck.getSideboard().isEmpty()) {
//pick the top 23 cards //pick the top 23 cards
if (chosenColors == null) { if (chosenColors == null) {
for (Card card : deck.getSideboard()) { for (Card card : deck.getSideboard()) {
@ -1999,7 +1999,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (int i = 1; i < powerElements; i++) { for (int i = 1; i < powerElements; i++) {
String binary = Integer.toBinaryString(i); String binary = Integer.toBinaryString(i);
while (binary.length() < attackersList.size()) { while (binary.length() < attackersList.size()) {
binary = "0" + binary; binary = '0' + binary;
} }
List<Permanent> trialAttackers = new ArrayList<>(); List<Permanent> trialAttackers = new ArrayList<>();
for (int j = 0; j < attackersList.size(); j++) { for (int j = 0; j < attackersList.size(); j++) {
@ -2119,7 +2119,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(message).append(": "); sb.append(message).append(": ");
for (MageObject object : list) { for (MageObject object : list) {
sb.append(object.getName()).append(","); sb.append(object.getName()).append(',');
} }
log.info(sb.toString()); log.info(sb.toString());
} }
@ -2128,7 +2128,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(message).append(": "); sb.append(message).append(": ");
for (Ability ability : list) { for (Ability ability : list) {
sb.append(ability.getRule()).append(","); sb.append(ability.getRule()).append(',');
} }
log.debug(sb.toString()); log.debug(sb.toString());
} }

View file

@ -215,7 +215,7 @@ public class ComputerPlayerMCTS extends ComputerPlayer implements Player {
UUID opponentId = game.getCombat().getDefenders().iterator().next(); UUID opponentId = game.getCombat().getDefenders().iterator().next();
for (UUID attackerId: combat.getAttackers()) { for (UUID attackerId: combat.getAttackers()) {
this.declareAttacker(attackerId, opponentId, game, false); this.declareAttacker(attackerId, opponentId, game, false);
sb.append(game.getPermanent(attackerId).getName()).append(","); sb.append(game.getPermanent(attackerId).getName()).append(',');
} }
logger.info(sb.toString()); logger.info(sb.toString());
MCTSNode.logHitMiss(); MCTSNode.logHitMiss();
@ -233,9 +233,9 @@ public class ComputerPlayerMCTS extends ComputerPlayer implements Player {
sb.append(game.getPermanent(groups.get(i).getAttackers().get(0)).getName()).append(" with: "); sb.append(game.getPermanent(groups.get(i).getAttackers().get(0)).getName()).append(" with: ");
for (UUID blockerId: combat.getGroups().get(i).getBlockers()) { for (UUID blockerId: combat.getGroups().get(i).getBlockers()) {
this.declareBlocker(this.getId(), blockerId, groups.get(i).getAttackers().get(0), game); this.declareBlocker(this.getId(), blockerId, groups.get(i).getAttackers().get(0), game);
sb.append(game.getPermanent(blockerId).getName()).append(","); sb.append(game.getPermanent(blockerId).getName()).append(',');
} }
sb.append("|"); sb.append('|');
} }
} }
logger.info(sb.toString()); logger.info(sb.toString());
@ -448,7 +448,7 @@ public class ComputerPlayerMCTS extends ComputerPlayer implements Player {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append(game.getTurn().getValue(game.getTurnNum())); sb.append(game.getTurn().getValue(game.getTurnNum()));
for (Player player: game.getPlayers().values()) { for (Player player: game.getPlayers().values()) {
sb.append("[player ").append(player.getName()).append(":").append(player.getLife()).append("]"); sb.append("[player ").append(player.getName()).append(':').append(player.getLife()).append(']');
} }
logger.info(sb.toString()); logger.info(sb.toString());
} }

View file

@ -567,9 +567,9 @@ public class MCTSNode {
public static void logHitMiss() { public static void logHitMiss() {
if (USE_ACTION_CACHE) { if (USE_ACTION_CACHE) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Playables Cache -- Hits: ").append(playablesHit).append(" Misses: ").append(playablesMiss).append("\n"); sb.append("Playables Cache -- Hits: ").append(playablesHit).append(" Misses: ").append(playablesMiss).append('\n');
sb.append("Attacks Cache -- Hits: ").append(attacksHit).append(" Misses: ").append(attacksMiss).append("\n"); sb.append("Attacks Cache -- Hits: ").append(attacksHit).append(" Misses: ").append(attacksMiss).append('\n');
sb.append("Blocks Cache -- Hits: ").append(blocksHit).append(" Misses: ").append(blocksMiss).append("\n"); sb.append("Blocks Cache -- Hits: ").append(blocksHit).append(" Misses: ").append(blocksMiss).append('\n');
logger.info(sb.toString()); logger.info(sb.toString());
} }
} }

View file

@ -52,7 +52,7 @@ public class MCTSPlayer extends ComputerPlayer {
private NextAction nextAction; private NextAction nextAction;
public enum NextAction { public enum NextAction {
PRIORITY, SELECT_ATTACKERS, SELECT_BLOCKERS; PRIORITY, SELECT_ATTACKERS, SELECT_BLOCKERS
} }
public MCTSPlayer(UUID id) { public MCTSPlayer(UUID id) {
@ -83,7 +83,7 @@ public class MCTSPlayer extends ComputerPlayer {
for (Ability ability: playables) { for (Ability ability: playables) {
List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game); List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game);
if (options.isEmpty()) { if (options.isEmpty()) {
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(ability, all, game); simulateVariableCosts(ability, all, game);
} }
else { else {
@ -92,7 +92,7 @@ public class MCTSPlayer extends ComputerPlayer {
} }
else { else {
for (Ability option: options) { for (Ability option: options) {
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(option, all, game); simulateVariableCosts(option, all, game);
} }
else { else {
@ -131,7 +131,7 @@ public class MCTSPlayer extends ComputerPlayer {
binary.setLength(0); binary.setLength(0);
binary.append(Integer.toBinaryString(i)); binary.append(Integer.toBinaryString(i));
while (binary.length() < attackersList.size()) { while (binary.length() < attackersList.size()) {
binary.insert(0, "0"); binary.insert(0, '0');
} }
List<UUID> engagement = new ArrayList<UUID>(); List<UUID> engagement = new ArrayList<UUID>();
for (int j = 0; j < attackersList.size(); j++) { for (int j = 0; j < attackersList.size(); j++) {

View file

@ -124,7 +124,7 @@ public class SimulatedPlayerMCTS extends MCTSPlayer {
ability = options.get(RandomUtil.nextInt(options.size())); ability = options.get(RandomUtil.nextInt(options.size()));
} }
} }
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
int amount = getAvailableManaProducers(game).size() - ability.getManaCosts().convertedManaCost(); int amount = getAvailableManaProducers(game).size() - ability.getManaCosts().convertedManaCost();
if (amount > 0) { if (amount > 0) {
ability = ability.copy(); ability = ability.copy();
@ -195,7 +195,7 @@ public class SimulatedPlayerMCTS extends MCTSPlayer {
StringBuilder binary = new StringBuilder(); StringBuilder binary = new StringBuilder();
binary.append(Integer.toBinaryString(value)); binary.append(Integer.toBinaryString(value));
while (binary.length() < attackersList.size()) { while (binary.length() < attackersList.size()) {
binary.insert(0, "0"); //pad with zeros binary.insert(0, '0'); //pad with zeros
} }
for (int i = 0; i < attackersList.size(); i++) { for (int i = 0; i < attackersList.size(); i++) {
if (binary.charAt(i) == '1') { if (binary.charAt(i) == '1') {
@ -221,7 +221,7 @@ public class SimulatedPlayerMCTS extends MCTSPlayer {
int check = RandomUtil.nextInt(numGroups + 1); int check = RandomUtil.nextInt(numGroups + 1);
if (check < numGroups) { if (check < numGroups) {
CombatGroup group = game.getCombat().getGroups().get(check); CombatGroup group = game.getCombat().getGroups().get(check);
if (group.getAttackers().size() > 0) { if (!group.getAttackers().isEmpty()) {
this.declareBlocker(this.getId(), blocker.getId(), group.getAttackers().get(0), game); this.declareBlocker(this.getId(), blocker.getId(), group.getAttackers().get(0), game);
} }
} }

View file

@ -161,7 +161,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
else else
addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE); addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s"); logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s");
if (root.children.size() > 0) { if (!root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
actions = new LinkedList<Ability>(root.abilities); actions = new LinkedList<Ability>(root.abilities);
combat = root.combat; combat = root.combat;
@ -174,10 +174,10 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
} }
protected boolean getNextAction(Game game) { protected boolean getNextAction(Game game) {
if (root != null && root.children.size() > 0) { if (root != null && !root.children.isEmpty()) {
SimulationNode test = root; SimulationNode test = root;
root = root.children.get(0); root = root.children.get(0);
while (root.children.size() > 0 && !root.playerId.equals(playerId)) { while (!root.children.isEmpty() && !root.playerId.equals(playerId)) {
test = root; test = root;
root = root.children.get(0); root = root.children.get(0);
} }
@ -297,7 +297,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
task.get(maxThink, TimeUnit.SECONDS); task.get(maxThink, TimeUnit.SECONDS);
long endTime = System.nanoTime(); long endTime = System.nanoTime();
long duration = endTime - startTime; long duration = endTime - startTime;
logger.info("Calculated " + SimulationNode.nodeCount + " nodes in " + duration/1000000000.0 + "s"); logger.info("Calculated " + SimulationNode.nodeCount + " nodes in " + duration/1000000000.0 + 's');
nodeCount += SimulationNode.nodeCount; nodeCount += SimulationNode.nodeCount;
thinkTime += duration; thinkTime += duration;
} catch (TimeoutException e) { } catch (TimeoutException e) {
@ -311,7 +311,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
} }
long endTime = System.nanoTime(); long endTime = System.nanoTime();
long duration = endTime - startTime; long duration = endTime - startTime;
logger.info("Timeout - Calculated " + SimulationNode.nodeCount + " nodes in " + duration/1000000000.0 + "s"); logger.info("Timeout - Calculated " + SimulationNode.nodeCount + " nodes in " + duration/1000000000.0 + 's');
nodeCount += SimulationNode.nodeCount; nodeCount += SimulationNode.nodeCount;
thinkTime += duration; thinkTime += duration;
} catch (ExecutionException e) { } catch (ExecutionException e) {
@ -335,7 +335,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
logger.debug(indent(node.depth) + "simulating -- reached end state"); logger.debug(indent(node.depth) + "simulating -- reached end state");
val = GameStateEvaluator.evaluate(playerId, game); val = GameStateEvaluator.evaluate(playerId, game);
} }
else if (node.getChildren().size() > 0) { else if (!node.getChildren().isEmpty()) {
logger.debug(indent(node.depth) + "simulating -- somthing added children:" + node.getChildren().size()); logger.debug(indent(node.depth) + "simulating -- somthing added children:" + node.getChildren().size());
val = minimaxAB(node, alpha, beta); val = minimaxAB(node, alpha, beta);
} }
@ -361,7 +361,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
if (game.gameOver(null)) { if (game.gameOver(null)) {
val = GameStateEvaluator.evaluate(playerId, game); val = GameStateEvaluator.evaluate(playerId, game);
} }
else if (node.getChildren().size() > 0) { else if (!node.getChildren().isEmpty()) {
//declared attackers or blockers or triggered abilities //declared attackers or blockers or triggered abilities
logger.debug(indent(node.depth) + "simulating -- attack/block/trigger added children:" + node.getChildren().size()); logger.debug(indent(node.depth) + "simulating -- attack/block/trigger added children:" + node.getChildren().size());
val = minimaxAB(node, alpha, beta); val = minimaxAB(node, alpha, beta);
@ -430,9 +430,9 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
alpha = val; alpha = val;
bestNode = newNode; bestNode = newNode;
node.setCombat(newNode.getCombat()); node.setCombat(newNode.getCombat());
if (node.getTargets().size() > 0) if (!node.getTargets().isEmpty())
targets = node.getTargets(); targets = node.getTargets();
if (node.getChoices().size() > 0) if (!node.getChoices().isEmpty())
choices = node.getChoices(); choices = node.getChoices();
} }
if (val == GameStateEvaluator.WIN_SCORE) { if (val == GameStateEvaluator.WIN_SCORE) {
@ -673,7 +673,7 @@ public class ComputerPlayer2 extends ComputerPlayer implements Player {
@Override @Override
public void selectBlockers(Game game, UUID defendingPlayerId) { public void selectBlockers(Game game, UUID defendingPlayerId) {
logger.debug("selectBlockers"); logger.debug("selectBlockers");
if (combat != null && combat.getGroups().size() > 0) { if (combat != null && !combat.getGroups().isEmpty()) {
List<CombatGroup> groups = game.getCombat().getGroups(); List<CombatGroup> groups = game.getCombat().getGroups();
for (int i = 0; i < groups.size(); i++) { for (int i = 0; i < groups.size(); i++) {
if (i < combat.getGroups().size()) { if (i < combat.getGroups().size()) {

View file

@ -139,7 +139,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
else else
addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE); addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s"); logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s");
if (root.children.size() > 0) { if (!root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
actions = new LinkedList<Ability>(root.abilities); actions = new LinkedList<Ability>(root.abilities);
combat = root.combat; combat = root.combat;
@ -163,7 +163,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
else else
addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE); addActions(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s"); logger.info(name + " simulated " + nodeCount + " nodes in " + thinkTime/1000000000.0 + "s - average " + nodeCount/(thinkTime/1000000000.0) + " nodes/s");
if (root.children.size() > 0) { if (!root.children.isEmpty()) {
root = root.children.get(0); root = root.children.get(0);
actions = new LinkedList<Ability>(root.abilities); actions = new LinkedList<Ability>(root.abilities);
combat = root.combat; combat = root.combat;
@ -189,7 +189,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
logger.debug(indent(node.depth) + "simulating -- reached end state"); logger.debug(indent(node.depth) + "simulating -- reached end state");
val = GameStateEvaluator.evaluate(playerId, game); val = GameStateEvaluator.evaluate(playerId, game);
} }
else if (node.getChildren().size() > 0) { else if (!node.getChildren().isEmpty()) {
logger.debug(indent(node.depth) + "simulating -- somthing added children:" + node.getChildren().size()); logger.debug(indent(node.depth) + "simulating -- somthing added children:" + node.getChildren().size());
val = minimaxAB(node, alpha, beta); val = minimaxAB(node, alpha, beta);
} }
@ -238,7 +238,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
val = GameStateEvaluator.evaluate(playerId, game); val = GameStateEvaluator.evaluate(playerId, game);
} }
} }
else if (node.getChildren().size() > 0) { else if (!node.getChildren().isEmpty()) {
logger.debug(indent(node.depth) + "simulating -- trigger added children:" + node.getChildren().size()); logger.debug(indent(node.depth) + "simulating -- trigger added children:" + node.getChildren().size());
val = minimaxAB(node, alpha, beta); val = minimaxAB(node, alpha, beta);
} }
@ -388,7 +388,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
} }
Game sim = game.copy(); Game sim = game.copy();
for (CombatGroup group: engagement.getGroups()) { for (CombatGroup group: engagement.getGroups()) {
if (group.getAttackers().size() > 0) { if (!group.getAttackers().isEmpty()) {
UUID attackerId = group.getAttackers().get(0); UUID attackerId = group.getAttackers().get(0);
for (UUID blockerId: group.getBlockers()) { for (UUID blockerId: group.getBlockers()) {
sim.getPlayer(defenderId).declareBlocker(defenderId, blockerId, attackerId, sim); sim.getPlayer(defenderId).declareBlocker(defenderId, blockerId, attackerId, sim);

View file

@ -60,7 +60,7 @@ public class SimulatedAction {
} }
public boolean usesStack() { public boolean usesStack() {
if (abilities != null && abilities.size() > 0) { if (abilities != null && !abilities.isEmpty()) {
return abilities.get(abilities.size() -1).isUsesStack(); return abilities.get(abilities.size() -1).isUsesStack();
} }
return true; return true;

View file

@ -90,7 +90,7 @@ public class SimulatedPlayer extends ComputerPlayer {
for (Ability ability: playables) { for (Ability ability: playables) {
List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game); List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game);
if (options.isEmpty()) { if (options.isEmpty()) {
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(ability, game); simulateVariableCosts(ability, game);
} }
else { else {
@ -101,7 +101,7 @@ public class SimulatedPlayer extends ComputerPlayer {
else { else {
// ExecutorService simulationExecutor = Executors.newFixedThreadPool(4); // ExecutorService simulationExecutor = Executors.newFixedThreadPool(4);
for (Ability option: options) { for (Ability option: options) {
if (ability.getManaCosts().getVariableCosts().size() > 0) { if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(option, game); simulateVariableCosts(option, game);
} }
else { else {
@ -172,7 +172,7 @@ public class SimulatedPlayer extends ComputerPlayer {
binary.setLength(0); binary.setLength(0);
binary.append(Integer.toBinaryString(i)); binary.append(Integer.toBinaryString(i));
while (binary.length() < attackersList.size()) { while (binary.length() < attackersList.size()) {
binary.insert(0, "0"); binary.insert(0, '0');
} }
for (int j = 0; j < attackersList.size(); j++) { for (int j = 0; j < attackersList.size(); j++) {
if (binary.charAt(j) == '1') { if (binary.charAt(j) == '1') {

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