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 {
LOGGER.debug("connecting (auto): " + currentConnection.getProxyType().toString()
+ " " + currentConnection.getProxyHost() + " " + currentConnection.getProxyPort() + " " + currentConnection.getProxyUsername());
+ ' ' + currentConnection.getProxyHost() + ' ' + currentConnection.getProxyPort() + ' ' + currentConnection.getProxyUsername());
if (MageFrame.connect(currentConnection)) {
showGames(false);
return true;
@ -1334,7 +1334,7 @@ public class MageFrame extends javax.swing.JFrame implements MageClient {
hideTables();
SessionHandler.disconnect(false);
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.setButton2("Yes", PlayerAction.CLIENT_RECONNECT);
showUserRequestDialog(message);

View file

@ -141,7 +141,7 @@ public class BigCard extends JComponent {
try {
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) {
}

View file

@ -181,7 +181,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gImage.setColor(Color.BLACK);
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);
}
@ -192,12 +192,12 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
gImage.setFont(new Font("Arial", Font.PLAIN, NAME_FONT_MAX_SIZE));
gImage.drawString(card.getName()+"TEST", CONTENT_MAX_XOFFSET, NAME_MAX_YOFFSET);
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)) {
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);
}
@ -211,7 +211,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
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);
}
drawText();
@ -228,27 +228,27 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StringBuilder sb = new StringBuilder();
if (card instanceof StackAbilityView || card instanceof AbilityView) {
for (String rule : getRules()) {
sb.append("\n").append(rule);
sb.append('\n').append(rule);
}
} else {
sb.append(card.getName());
if (card.getManaCost().size() > 0) {
sb.append("\n").append(card.getManaCost());
if (!card.getManaCost().isEmpty()) {
sb.append('\n').append(card.getManaCost());
}
sb.append("\n").append(cardType);
sb.append('\n').append(cardType);
if (card.getColor().hasColor()) {
sb.append("\n").append(card.getColor().toString());
sb.append('\n').append(card.getColor().toString());
}
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)) {
sb.append("\n").append(card.getLoyalty());
sb.append('\n').append(card.getLoyalty());
}
for (String rule : getRules()) {
sb.append("\n").append(rule);
sb.append('\n').append(rule);
}
if (card.getExpansionSetCode() != null && card.getExpansionSetCode().length() > 0) {
sb.append("\n").append(card.getCardNumber()).append(" - ");
if (card.getExpansionSetCode() != null && !card.getExpansionSetCode().isEmpty()) {
sb.append('\n').append(card.getCardNumber()).append(" - ");
sb.append(Sets.getInstance().get(card.getExpansionSetCode()).getName()).append(" - ");
sb.append(card.getRarity().toString());
}
@ -277,7 +277,7 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
try {
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) {
}
@ -301,17 +301,17 @@ public class Card extends MagePermanent implements MouseMotionListener, MouseLis
StringBuilder sbType = new StringBuilder();
for (String superType : card.getSuperTypes()) {
sbType.append(superType).append(" ");
sbType.append(superType).append(' ');
}
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("- ");
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) {
int rowsOfCards = 20;
int columns = 1;
if (showCards != null && showCards.size() > 0) {
if (showCards != null && !showCards.isEmpty()) {
Rectangle rectangle = new Rectangle(cardDimension.width, cardDimension.height);
int count = 0;
for (CardView card : showCards.values()) {

View file

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

View file

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

View file

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

View file

@ -106,25 +106,25 @@ public class Permanent extends Card {
if (permanent.getOriginal() != null) {
sb.append("\n----- Originally -------\n");
sb.append(permanent.getOriginal().getName());
if (permanent.getOriginal().getManaCost().size() > 0) {
sb.append("\n").append(permanent.getOriginal().getManaCost());
if (!permanent.getOriginal().getManaCost().isEmpty()) {
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()) {
sb.append("\n").append(permanent.getOriginal().getColor().toString());
sb.append('\n').append(permanent.getOriginal().getColor().toString());
}
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)) {
sb.append("\n").append(permanent.getOriginal().getLoyalty());
sb.append('\n').append(permanent.getOriginal().getLoyalty());
}
for (String rule: getRules()) {
sb.append("\n").append(rule);
sb.append('\n').append(rule);
}
if (permanent.getOriginal().getExpansionSetCode().length() > 0) {
sb.append("\n").append(permanent.getCardNumber()).append(" - ");
sb.append("\n").append(Sets.getInstance().get(permanent.getOriginal().getExpansionSetCode()).getName()).append(" - ");
if (!permanent.getOriginal().getExpansionSetCode().isEmpty()) {
sb.append('\n').append(permanent.getCardNumber()).append(" - ");
sb.append('\n').append(Sets.getInstance().get(permanent.getOriginal().getExpansionSetCode()).getName()).append(" - ");
sb.append(permanent.getOriginal().getRarity().toString());
}
// 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>");
final String basicText = ManaSymbols.replaceSymbolsWithHTML(text, ManaSymbols.Type.DIALOG);
if (text.length() > 0) {
if (!text.isEmpty()) {
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 += "<br>";
if (text.length() > 0) {
if (!text.isEmpty()) {
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()
+ "[axis=" + axis
+ ",gap=" + gap
+ "]";
+ ']';
}
}

View file

@ -168,7 +168,7 @@ public class RatioAdjustingSliderPanel extends JPanel {
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 -> {
String value = String.valueOf(slider.getValue());
@ -178,7 +178,7 @@ public class RatioAdjustingSliderPanel extends JPanel {
labelBuilder.append(" ");
}
labelBuilder.append(value);
labelBuilder.append("%");
labelBuilder.append('%');
label.setText(labelBuilder.toString());
});
return label;

View file

@ -97,7 +97,7 @@ public class DeckArea extends javax.swing.JPanel {
@Override
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);
String text;
if (minute < 10) {
text = "0" + Integer.toString(minute) + ":";
text = '0' + Integer.toString(minute) + ':';
} else {
text = Integer.toString(minute) + ":";
text = Integer.toString(minute) + ':';
}
if (second < 10) {
text = text + "0" + Integer.toString(second);
text = text + '0' + Integer.toString(second);
} else {
text = text + Integer.toString(second);
}
@ -599,7 +599,7 @@ public class DeckEditorPanel extends javax.swing.JPanel {
}
if (timeToSubmit > 0) {
timeToSubmit--;
btnSubmitTimer.setText("Submit (" + timeToSubmit + ")");
btnSubmitTimer.setText("Submit (" + timeToSubmit + ')');
btnSubmitTimer.setToolTipText("Submit your deck in " + timeToSubmit + " seconds!");
}
}

View file

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

View file

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

View file

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

View file

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

View file

@ -398,7 +398,7 @@ public class ConnectDialog extends MageDialog {
// pref settings
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.execute();
} finally {

View file

@ -100,7 +100,7 @@ public class GameEndDialog extends MageDialog {
StringBuilder sb = new StringBuilder();
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());
@ -128,8 +128,8 @@ public class GameEndDialog extends MageDialog {
sdf.applyPattern( "yyyyMMdd_HHmmss" );
String fileName = new StringBuilder(dir).append(File.separator)
.append(sdf.format(gameEndView.getStartTime()))
.append("_").append(gameEndView.getMatchView().getGameType())
.append("_").append(gameEndView.getMatchView().getGames().size())
.append('_').append(gameEndView.getMatchView().getGameType())
.append('_').append(gameEndView.getMatchView().getGames().size())
.append(".txt").toString();
PrintWriter out = new PrintWriter(fileName);
out.print(gamePanel.getGameLog());

View file

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

View file

@ -826,7 +826,7 @@ public class NewTournamentDialog extends MageDialog {
txtRandomPacks.setEnabled(false);
txtRandomPacks.setLineWrap(true);
String randomPrefs = PreferencesDialog.getCachedValue(PreferencesDialog.KEY_NEW_TOURNAMENT_PACKS_RANDOM_DRAFT, "");
if (randomPrefs.length() > 0) {
if (!randomPrefs.isEmpty()) {
txtRandomPacks.setText(randomPrefs);
ArrayList<String> theList = new ArrayList<>();
theList.addAll(Arrays.asList(randomPrefs.split(";")));
@ -836,7 +836,7 @@ public class NewTournamentDialog extends MageDialog {
StringBuilder packList = new StringBuilder();
for (ExpansionInfo exp : allExpansions) {
packList.append(exp.getCode());
packList.append(";");
packList.append(';');
}
txtRandomPacks.setText(packList.toString());
}
@ -860,7 +860,7 @@ public class NewTournamentDialog extends MageDialog {
StringBuilder packList = new StringBuilder();
for (String str : randomPackSelector.getSelectedPacks()) {
packList.append(str);
packList.append(";");
packList.append(';');
}
this.txtRandomPacks.setText(packList.toString());
this.pack();
@ -1026,7 +1026,7 @@ public class NewTournamentDialog extends MageDialog {
}
private void loadBoosterPacks(String packString) {
if (packString.length()>0) {
if (!packString.isEmpty()) {
String[] packsArray = packString.substring(1, packString.length() - 1).split(",");
int packNumber = 0;
for (String pack : packsArray ){
@ -1088,7 +1088,7 @@ public class NewTournamentDialog extends MageDialog {
StringBuilder packlist = new StringBuilder();
for (String pack : this.randomPackSelector.getSelectedPacks()){
packlist.append(pack);
packlist.append(";");
packlist.append(';');
}
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
// the log.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
logFilename = "Draft_" + sdf.format(new Date()) + "_" + draftId + ".txt";
logFilename = "Draft_" + sdf.format(new Date()) + '_' + draftId + ".txt";
try {
Files.write(pathToDraftLog(), "".getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException ex) {
@ -366,12 +366,12 @@ public class DraftPanel extends javax.swing.JPanel {
int second = s - (minute * 60);
String text;
if (minute < 10) {
text = "0" + Integer.toString(minute) + ":";
text = '0' + Integer.toString(minute) + ':';
} else {
text = Integer.toString(minute) + ":";
text = Integer.toString(minute) + ':';
}
if (second < 10) {
text = text + "0" + Integer.toString(second);
text = text + '0' + Integer.toString(second);
} else {
text = text + Integer.toString(second);
}

View file

@ -406,7 +406,7 @@ public final class GamePanel extends javax.swing.JPanel {
private void saveDividerLocations() {
// save panel sizes and divider locations.
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_GAMEPANEL_DIVIDER_LOCATION_0, Integer.toString(this.jSplitPane0.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();
if (rec != 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
if (size != null && size.equals(sb)) {
@ -723,7 +723,7 @@ public final class GamePanel extends javax.swing.JPanel {
if (!handCards.containsKey(chosenHandKey)) {
chosenHandKey = YOUR_HAND;
}
} else if (chosenHandKey.isEmpty() && handCards.size() > 0) {
} else if (chosenHandKey.isEmpty() && !handCards.isEmpty()) {
chosenHandKey = handCards.keySet().iterator().next();
}
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")) {
this.txtSpellsCast.setVisible(true);
this.txtSpellsCast.setText(" " + Integer.toString(game.getSpellsCastCurrentTurn()) + " ");
this.txtSpellsCast.setText(' ' + Integer.toString(game.getSpellsCastCurrentTurn()) + ' ');
} else {
this.txtSpellsCast.setVisible(false);
}
@ -854,7 +854,7 @@ public final class GamePanel extends javax.swing.JPanel {
showRevealed(game);
showLookedAt(game);
if (game.getCombat().size() > 0) {
if (!game.getCombat().isEmpty()) {
CombatManager.getInstance().showCombat(game.getCombat(), gameId);
} else {
CombatManager.getInstance().hideCombat(gameId);
@ -1164,7 +1164,7 @@ public final class GamePanel extends javax.swing.JPanel {
updateGame(gameView);
Map<String, Serializable> options0 = options == null ? new HashMap<>() : options;
ShowCardsDialog dialog = null;
if (cardView != null && cardView.size() > 0) {
if (cardView != null && !cardView.isEmpty()) {
dialog = showCards(message, cardView, required, options0, popupMenuType);
options0.put("dialog", dialog);
}
@ -1279,7 +1279,7 @@ public final class GamePanel extends javax.swing.JPanel {
pickChoice.showDialog(choice, objectId, choiceWindowState);
if (choice.isKeyChoice()) {
if (pickChoice.isAutoSelect()) {
SessionHandler.sendPlayerString(gameId, "#" + choice.getChoiceKey());
SessionHandler.sendPlayerString(gameId, '#' + choice.getChoiceKey());
} else {
SessionHandler.sendPlayerString(gameId, choice.getChoiceKey());
}
@ -2130,7 +2130,7 @@ public final class GamePanel extends javax.swing.JPanel {
choices,
this.chosenHandKey);
if (newChosenHandKey != null && newChosenHandKey.length() > 0) {
if (newChosenHandKey != null && !newChosenHandKey.isEmpty()) {
this.chosenHandKey = newChosenHandKey;
CardsView cards = handCards.get(chosenHandKey);
handContainer.loadCards(cards, bigCard, gameId);

View file

@ -377,11 +377,11 @@ public class HelperPanel extends JPanel {
public void handleAutoAnswerPopupMenuEvent(ActionEvent e) {
switch (e.getActionCommand()) {
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);
break;
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);
break;
case CMD_AUTO_ANSWER_NAME_YES:

View file

@ -360,7 +360,7 @@ public class PlayerPanelExt extends javax.swing.JPanel {
int h = priorityTimeLeft / 3600;
int m = (priorityTimeLeft % 3600) / 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) {

View file

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

View file

@ -161,11 +161,11 @@ public class PlayersChatPanel extends javax.swing.JPanel {
JTableHeader th = jTablePlayers.getTableHeader();
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(
"Games " + roomUserInfo.getNumberActiveGames()
+ (roomUserInfo.getNumberActiveGames() != roomUserInfo.getNumberGameThreads() ? " (T:" + roomUserInfo.getNumberGameThreads() : " (")
+ " limit: " + roomUserInfo.getNumberMaxGames() + ")");
+ " limit: " + roomUserInfo.getNumberMaxGames() + ')');
th.repaint();
this.fireTableDataChanged();
}

View file

@ -187,7 +187,7 @@ public class TablesPanel extends javax.swing.JPanel {
String pwdColumn = (String) tableModel.getValueAt(modelRow, TableTableModel.COLUMN_PASSWORD);
switch (action) {
case "Join":
if (owner.equals(SessionHandler.getUserName()) || owner.startsWith(SessionHandler.getUserName() + ",")) {
if (owner.equals(SessionHandler.getUserName()) || owner.startsWith(SessionHandler.getUserName() + ',')) {
try {
JDesktopPane desktopPane = (JDesktopPane) MageFrame.getUI().getComponent(MageComponents.DESKTOP_PANE);
JInternalFrame[] windows = desktopPane.getAllFramesInLayer(javax.swing.JLayeredPane.DEFAULT_LAYER);
@ -259,7 +259,7 @@ public class TablesPanel extends javax.swing.JPanel {
switch (action) {
case "Replay":
List<UUID> gameList = matchesModel.getListofGames(modelRow);
if (gameList != null && gameList.size() > 0) {
if (gameList != null && !gameList.isEmpty()) {
if (gameList.size() == 1) {
SessionHandler.replayGame(gameList.get(0));
} else {
@ -350,7 +350,7 @@ public class TablesPanel extends javax.swing.JPanel {
private void saveDividerLocations() {
// save panel sizes and divider locations.
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_TABLES_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.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();
if (rec != 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
if (size != null && size.equals(sb)) {
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() {
// save panel sizes and divider locations.
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_TOURNAMENT_DIVIDER_LOCATION_1, Integer.toString(this.jSplitPane1.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();
if (rec != 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
if (size != null && size.equals(sb)) {
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();
}
if (c != null) {
((TournamentPane) c).setTitle("Tournament [" + tournament.getTournamentName() + "]");
((TournamentPane) c).setTitle("Tournament [" + tournament.getTournamentName() + ']');
}
txtName.setText(tournament.getTournamentName());
txtType.setText(tournament.getTournamentType());
@ -260,7 +260,7 @@ public class TournamentPanel extends javax.swing.JPanel {
if (tournament.getStepStartTime() != null) {
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;
case "Dueling":
case "Drafting":

View file

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

View file

@ -62,13 +62,13 @@ public class Format {
seconds = seconds % 3600;
long m = seconds / 60;
long s = seconds % 60;
sb.append(h).append(":");
sb.append(h).append(':');
if (m<10) {
sb.append("0");
sb.append('0');
}
sb.append(m).append(":");
sb.append(m).append(':');
if (s<10) {
sb.append("0");
sb.append('0');
}
sb.append(s);
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) {
if (costs.size() > 0) {
if (!costs.isEmpty()) {
int costLeft = xOffset;
for (int i = costs.size() - 1; i >= 0; i--) {
String symbol = costs.get(i);

View file

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

View file

@ -112,7 +112,7 @@ public class MusicPlayer {
volume = (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN);
sourceDataLine.start();
} 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)) {
Map<Type, List<Arrow>> innerMap = map.get(gameId);
java.util.List<Arrow> arrows = innerMap.get(type);
if (arrows != null && arrows.size() > 0) {
if (arrows != null && !arrows.isEmpty()) {
JPanel p = getArrowsPanel(gameId);
synchronized (map) {
for (Arrow arrow : arrows) {

View file

@ -222,7 +222,7 @@ public class GuiDisplayUtil {
buffer.append("<tr><td valign='top'><b>");
buffer.append(card.getDisplayName());
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(symbolCount * GUISizeHelper.cardTooltipFontSize);
@ -232,7 +232,7 @@ public class GuiDisplayUtil {
}
buffer.append("</td></tr></table>");
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()) {
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 = "";
if (CardUtil.isCreature(card)) {
pt = card.getPower() + "/" + card.getToughness();
pt = card.getPower() + '/' + card.getToughness();
} else if (CardUtil.isPlaneswalker(card)) {
pt = card.getLoyalty();
}
@ -291,7 +291,7 @@ public class GuiDisplayUtil {
buffer.append("<td align='right'>");
if (!card.isControlledByOwner()) {
if (card instanceof PermanentView) {
buffer.append("[").append(((PermanentView) card).getNameOwner()).append("] ");
buffer.append('[').append(((PermanentView) card).getNameOwner()).append("] ");
} else {
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) {
if (textLine != null && !textLine.replace(".", "").trim().isEmpty()) {
rule.append("<p style='margin: 2px'>").append(textLine).append("</p>");
@ -339,7 +339,7 @@ public class GuiDisplayUtil {
}
String legal = rule.toString();
if (legal.length() > 0) {
if (!legal.isEmpty()) {
legal = legal.replaceAll("\\{this\\}", card.getName().isEmpty() ? "this" : card.getName());
legal = legal.replaceAll("\\{source\\}", card.getName().isEmpty() ? "this" : card.getName());
buffer.append(ManaSymbols.replaceSymbolsWithHTML(legal, ManaSymbols.Type.TOOLTIP));
@ -361,16 +361,16 @@ public class GuiDisplayUtil {
private static String getTypes(CardView card) {
String types = "";
for (String superType : card.getSuperTypes()) {
types += superType + " ";
types += superType + ' ';
}
for (CardType cardType : card.getCardTypes()) {
types += cardType.toString() + " ";
types += cardType.toString() + ' ';
}
if (card.getSubTypes().size() > 0) {
if (!card.getSubTypes().isEmpty()) {
types += "- ";
}
for (String subType : card.getSubTypes()) {
types += subType + " ";
types += subType + ' ';
}
return types.trim();
}

View file

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

View file

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

View file

@ -53,7 +53,7 @@ public class SaveObjectUtil {
}
}
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()) {
f.createNewFile();
}

View file

@ -36,7 +36,7 @@ public class UpdateMemUsageTask extends SwingWorker<Void, Float> {
@Override
protected void process(List<Float> chunks) {
if (chunks != null && chunks.size() > 0) {
if (chunks != null && !chunks.isEmpty()) {
Float memUsage = chunks.get(chunks.size() - 1);
if (memUsage != null) {
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();
for (String superType : card.getSuperTypes()) {
sbType.append(superType).append(" ");
sbType.append(superType).append(' ');
}
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("- ");
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();
if (card instanceof StackAbilityView || card instanceof AbilityView) {
for (String rule : card.getRules()) {
sb.append("\n").append(rule);
sb.append('\n').append(rule);
}
} else {
sb.append(card.getName());
if (card.getManaCost().size() > 0) {
sb.append("\n").append(card.getManaCost());
if (!card.getManaCost().isEmpty()) {
sb.append('\n').append(card.getManaCost());
}
sb.append("\n").append(cardType);
sb.append('\n').append(cardType);
if (card.getColor().hasColor()) {
sb.append("\n").append(card.getColor().toString());
sb.append('\n').append(card.getColor().toString());
}
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)) {
sb.append("\n").append(card.getLoyalty());
sb.append('\n').append(card.getLoyalty());
}
if (card.getRules() == null) {
card.overrideRules(new ArrayList<>());
}
for (String rule : card.getRules()) {
sb.append("\n").append(rule);
sb.append('\n').append(rule);
}
if (card.getExpansionSetCode() != null && card.getExpansionSetCode().length() > 0) {
sb.append("\n").append(card.getCardNumber()).append(" - ");
if (card.getExpansionSetCode() != null && !card.getExpansionSetCode().isEmpty()) {
sb.append('\n').append(card.getCardNumber()).append(" - ");
sb.append(card.getExpansionSetCode()).append(" - ");
sb.append(card.getRarity().toString());
}

View file

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

View file

@ -380,15 +380,15 @@ public abstract class CardRenderer {
} else {
StringBuilder sbType = new StringBuilder();
for (String superType : cardView.getSuperTypes()) {
sbType.append(superType).append(" ");
sbType.append(superType).append(' ');
}
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("- ");
for (String subType : cardView.getSubTypes()) {
sbType.append(subType).append(" ");
sbType.append(subType).append(' ');
}
}
return sbType.toString();

View file

@ -89,7 +89,7 @@ public class ManaSymbols {
setImages.put(set, rarityImages);
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 {
Image image = UI.getImageIcon(file.getAbsolutePath()).getImage();
int width = image.getWidth(null);
@ -114,11 +114,11 @@ public class ManaSymbols {
}
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()) {
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();
try {
int width = image.getWidth(null);
@ -130,7 +130,7 @@ public class ManaSymbols {
}
Rectangle r = new Rectangle(15 + dx, (int) (height * (15.0f + dx) / width));
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);
}
} catch (Exception e) {
@ -171,7 +171,7 @@ public class ManaSymbols {
resourcePath = Constants.RESOURCE_PATH_MANA_MEDIUM;
}
for (String symbol : symbols) {
File file = new File(getSymbolsPath() + resourcePath + "/" + symbol + ".gif");
File file = new File(getSymbolsPath() + resourcePath + '/' + symbol + ".gif");
try {
if (size == 15 || size == 25) {
@ -315,7 +315,7 @@ public class ManaSymbols {
if (symbolFilesFound) {
replaced = REPLACE_SYMBOLS_PATTERN.matcher(value).replaceAll(
"<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("|this|", "{this}");
@ -328,7 +328,7 @@ public class ManaSymbols {
int factor = size / 15 + 1;
Integer width = setImagesExist.get(_set).width * 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 {
return set;
}

View file

@ -638,7 +638,7 @@ public class ModernCardRenderer extends CardRenderer {
}
g.setColor(textColor);
g.setFont(ptTextFont);
String ptText = cardView.getPower() + "/" + cardView.getToughness();
String ptText = cardView.getPower() + '/' + cardView.getToughness();
int ptTextWidth = g.getFontMetrics().stringWidth(ptText);
g.drawString(ptText,
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
// there are multiple attributes stacked (EG: bold + italic)
AttributedString attributedRule = new AttributedString(text);
if (text.length() != 0) {
if (!text.isEmpty()) {
attributedRule.addAttribute(TextAttribute.FONT, normal);
for (int i = regions.size() - 1; i >= 0; --i) {
regions.get(i).applyToAttributedString(attributedRule, normal, italic);

View file

@ -179,7 +179,7 @@ public class CardPluginImpl implements CardPlugin {
break;
}
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
insertIndex = i;
break;
@ -191,7 +191,7 @@ public class CardPluginImpl implements CardPlugin {
continue;
}
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
insertIndex = i + 1;
continue;

View file

@ -22,5 +22,5 @@ public class Constants {
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
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
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) {
File dst = new File(outDir, name + ".png");
String url = BASE_DOWNLOAD_URL + dirName + "/" + name + ".png";
return new DownloadJob("frames-" + dirName + "-" + name, fromURL(url), toFile(dst));
String url = BASE_DOWNLOAD_URL + dirName + '/' + name + ".png";
return new DownloadJob("frames-" + dirName + '-' + name, fromURL(url), toFile(dst));
}
private void useDefaultDir() {

View file

@ -163,12 +163,12 @@ public class GathererSets implements Iterable<DownloadJob> {
}
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)) {
set = symbolsReplacements.get(set);
}
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) {

View file

@ -54,6 +54,7 @@ public class GathererSymbols implements Iterable<DownloadJob> {
@Override
protected DownloadJob computeNext() {
while (true) {
String sym;
if (symIndex < symbols.length) {
sym = symbols[symIndex++];
@ -68,7 +69,7 @@ public class GathererSymbols implements Iterable<DownloadJob> {
symIndex = 0;
numeric = 0;
dir = new File(outDir, sizes[sizeIndex]);
return computeNext();
continue;
}
String symbol = sym.replaceAll("/", "");
File dst = new File(dir, symbol + ".gif");
@ -111,6 +112,7 @@ public class GathererSymbols implements Iterable<DownloadJob> {
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");
StringBuilder url = new StringBuilder("http://magiccards.info/scans/").append(preferedLanguage).append("/");
url.append(set.toLowerCase()).append("/").append(collectorId);
StringBuilder url = new StringBuilder("http://magiccards.info/scans/").append(preferedLanguage).append('/');
url.append(set.toLowerCase()).append('/').append(collectorId);
if (card.isTwoFacedCard()) {
url.append(card.isSecondSide() ? "b" : "a");
}
if (card.isSplitCard()) {
url.append("a");
url.append('a');
}
if (card.isFlipCard()) {
if (card.isFlippedSide()) { // download rotated by 180 degree image
url.append("b");
url.append('b');
} else {
url.append("a");
url.append('a');
}
}
url.append(".jpg");
@ -200,16 +200,16 @@ public class MagicCardsImageSource implements CardImageSource {
String name = card.getName();
// add type to name if it's not 0
if (card.getType() > 0) {
name = name + " " + card.getType();
name = name + ' ' + card.getType();
}
name = name.replaceAll(" ", "-").replace(",", "").toLowerCase();
String set = "not-supported-set";
if (setNameTokenReplacement.containsKey(card.getSet())) {
set = setNameTokenReplacement.get(card.getSet());
} 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

View file

@ -74,7 +74,7 @@ public class MagidexImageSource implements CardImageSource {
}
// 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();
}

View file

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

View file

@ -115,7 +115,7 @@ public class MythicspoilerComSource implements CardImageSource {
Connection.ProxyType proxyType = Connection.ProxyType.valueByText(prefs.get("proxyType", "None"));
for (String setName : setNames.split("\\^")) {
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);
setLinks.putAll(pageLinks);
@ -166,7 +166,7 @@ public class MythicspoilerComSource implements CardImageSource {
Elements cardsImages = doc.select("img[src^=cards/]"); // starts with cards/
if (!aliasesStart.isEmpty()) {
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);
}
if (cardName != null && !cardName.isEmpty()) {
if (cardNameAliases.containsKey(cardSet + "-" + cardName)) {
cardName = cardNameAliases.get(cardSet + "-" + cardName);
if (cardNameAliases.containsKey(cardSet + '-' + cardName)) {
cardName = cardNameAliases.get(cardSet + '-' + cardName);
} else if (cardName.endsWith("1") || cardName.endsWith("2") || cardName.endsWith("3") || cardName.endsWith("4") || cardName.endsWith("5")) {
if (!cardName.startsWith("forest")
&& !cardName.startsWith("swamp")

View file

@ -27,6 +27,9 @@
*/
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.IOException;
import java.io.InputStream;
@ -36,8 +39,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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;
if (type == 0) {
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);
} else {
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;
}
tokenData = matchedTokens.get(card.getType() - 1);
}
String url = "http://tokens.mtg.onl/tokens/" + tokenData.getExpansionSetCode().trim() + "_"
+ tokenData.getNumber().trim() + "-" + tokenData.getName().trim() + ".jpg";
String url = "http://tokens.mtg.onl/tokens/" + tokenData.getExpansionSetCode().trim() + '_'
+ tokenData.getNumber().trim() + '-' + tokenData.getName().trim() + ".jpg";
url = url.replace(' ', '-');
return url;
}
@ -184,30 +185,18 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData = new ArrayList<>();
// get tokens data from resource file
InputStream inputStream = null;
try {
inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv");
try(InputStream inputStream = this.getClass().getResourceAsStream("/tokens-mtg-onl-list.csv")) {
List<TokenData> fileTokensData = parseTokensData(inputStream);
tokensData.addAll(fileTokensData);
} catch (Exception 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
// try to add it
try {
URL url = new URL("http://tokens.mtg.onl/data/SetsWithTokens.csv");
inputStream = url.openStream();
try(InputStream inputStream = url.openStream()) {
List<TokenData> siteTokensData = parseTokensData(inputStream);
List<TokenData> newTokensData = new ArrayList<>();
for (TokenData siteData : siteTokensData) {
boolean isNew = true;
@ -227,14 +216,6 @@ public class TokensMtgImageSource implements CardImageSource {
tokensData.addAll(newTokensData);
} catch (Exception 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 {
List<TokenData> newTokensData = new ArrayList<>();
InputStreamReader inputReader = null;
BufferedReader reader = null;
try {
try(InputStreamReader inputReader = new InputStreamReader(inputStream, "Cp1252");
BufferedReader reader = new BufferedReader(inputReader)) {
// we have to specify encoding to read special comma
inputReader = new InputStreamReader(inputStream, "Cp1252");
reader = new BufferedReader(inputReader);
reader.readLine(); // skip header
String line = reader.readLine();
@ -282,21 +260,6 @@ public class TokensMtgImageSource implements CardImageSource {
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;

View file

@ -410,11 +410,11 @@ public class WizardCardsImageSource implements CardImageSource {
private String normalizeName(String name) {
//Split card
if(name.contains("//")) {
name = name.substring(0, name.indexOf("(") - 1);
name = name.substring(0, name.indexOf('(') - 1);
}
//Special timeshifted name
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", "'")
.replace("\u00C6", "AE").replace("\u00E6", "ae")
@ -456,7 +456,7 @@ public class WizardCardsImageSource implements CardImageSource {
} else {
link = setLinks.get(Integer.toString(number - 21));
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;
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.client.constants.Constants;
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.kernel.spec.FsSyncException;
import org.apache.log4j.Logger;
import org.mage.plugins.card.dl.sources.AltMtgOnlTokensImageSource;
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.dl.sources.*;
import org.mage.plugins.card.properties.SettingsManager;
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 {
private static final Logger logger = Logger.getLogger(DownloadPictures.class);
@ -356,12 +325,12 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
int tokenImages = 0;
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()) {
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 token images: " + tokenImages);
return new ArrayList<>(cardsToDownload);
@ -376,11 +345,9 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
return list;
}
BufferedReader reader = null;
InputStreamReader input = null;
try {
input = new InputStreamReader(in);
reader = new BufferedReader(input);
try(InputStreamReader input = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(input)) {
String line;
line = reader.readLine();
@ -425,22 +392,6 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} catch (Exception ex) {
logger.error(ex);
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;
}
@ -494,7 +445,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
CardDownloadData card = cardsToDownload.get(i);
logger.debug("Downloading card: " + card.getName() + " (" + card.getSet() + ")");
logger.debug("Downloading card: " + card.getName() + " (" + card.getSet() + ')');
String url;
if (ignoreUrls.contains(card.getSet()) || card.isToken()) {
@ -519,7 +470,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
} catch (Exception ex) {
}
} 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) {
update(cardIndex + 1, cardsToDownload.size());
}
@ -589,7 +540,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
try {
filePath.append(Constants.IO.imageBaseDir);
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());
}
String imagePath;
@ -699,7 +650,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
if (card != null && !useSpecifiedPaths) {
logger.warn("Image download for " + card.getName()
+ (!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
logger.debug("Returned HTML ERROR:\n" + convertStreamToString(((HttpURLConnection) httpConn).getErrorStream()));
@ -707,7 +658,7 @@ public class DownloadPictures extends DefaultBoundedRangeModel implements Runnab
}
} 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) {
logger.error(e, e);
} finally {

View file

@ -255,11 +255,11 @@ public class ImageCache {
* Returns the map key for a card, without any suffixes for the image size.
*/
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())
+ suffix
+ (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 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();
if (card.getUsesVariousArt()) {
imageName = name + "." + card.getCollectorId() + ".full.jpg";
imageName = name + '.' + card.getCollectorId() + ".full.jpg";
} else {
imageName = name + type + ".full.jpg";
}

View file

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

View file

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

View file

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

View file

@ -158,7 +158,7 @@ public class SessionImpl implements Session {
StringBuilder sb = new StringBuilder();
sb.append("Unable to connect to server.\n");
for (StackTraceElement element : t.getStackTrace()) {
sb.append(element.toString()).append("\n");
sb.append(element.toString()).append('\n');
}
client.showMessage(sb.toString());
}
@ -171,11 +171,11 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override
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(),
connection.getPassword(), connection.getEmail());
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;
}
@ -187,10 +187,10 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override
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());
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;
}
@ -202,10 +202,10 @@ public class SessionImpl implements Session {
return establishJBossRemotingConnection(connection) && handleRemotingTaskExceptions(new RemotingTask() {
@Override
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());
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;
}
@ -218,7 +218,7 @@ public class SessionImpl implements Session {
&& handleRemotingTaskExceptions(new RemotingTask() {
@Override
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;
if (connection.getAdminPassword() == null) {
// 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")) {
updateDatabase(connection.isForceDBComparison(), serverState);
}
logger.info("Logged-in as " + getUserName() + " to MAGE server at " + connection.getHost() + ":" + connection.getPort());
client.connected(getUserName() + "@" + 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() + ' ');
return true;
}
disconnect(false);
@ -260,7 +260,7 @@ public class SessionImpl implements Session {
boolean result = handleRemotingTaskExceptions(new RemotingTask() {
@Override
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("socksNonProxyHosts", "code.google.com");
@ -391,14 +391,14 @@ public class SessionImpl implements Session {
Set callbackConnectors = callbackClient.getCallbackConnectors(callbackHandler);
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);
sessionId = callbackClient.getSessionId();
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;
}
});
@ -451,7 +451,7 @@ public class SessionImpl implements Session {
break;
}
if (t.getCause() != null && logger.isDebugEnabled()) {
message = "\n" + t.getCause().getMessage() + message;
message = '\n' + t.getCause().getMessage() + message;
logger.debug(t.getCause().getMessage());
}
@ -1434,7 +1434,7 @@ public class SessionImpl implements Session {
@Override
public boolean endUserSession(String userSessionId) {
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) {
if (isConnected()) {
server.endUserSession(sessionId, userSessionId);
@ -1470,7 +1470,7 @@ public class SessionImpl implements Session {
@Override
public boolean setActivation(String userName, boolean active) {
try {
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to set active to " + active + " for user: " + userName + "?", "WARNING",
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to set active to " + active + " for user: " + userName + '?', "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (isConnected()) {
server.setActivation(sessionId, userName, active);
@ -1496,7 +1496,7 @@ public class SessionImpl implements Session {
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
return setActivation(userName, false);
}
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to toggle activation for user: " + userName + "?", "WARNING",
if (JOptionPane.showConfirmDialog(null, "Are you sure you mean to toggle activation for user: " + userName + '?', "WARNING",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
if (isConnected()) {
server.toggleActivation(sessionId, userName);
@ -1542,8 +1542,8 @@ public class SessionImpl implements Session {
}
private void handleInvalidDeckException(InvalidDeckException iex) {
logger.warn(iex.getMessage() + "\n" + iex.getInvalid());
client.showError(iex.getMessage() + "\n" + iex.getInvalid());
logger.warn(iex.getMessage() + '\n' + iex.getInvalid());
client.showError(iex.getMessage() + '\n' + iex.getInvalid());
}
private void handleGameException(GameException ex) {
@ -1588,7 +1588,7 @@ public class SessionImpl implements Session {
if (isConnected()) {
long startTime = System.nanoTime();
if (!server.ping(sessionId, pingInfo)) {
logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() + ":" + connection.getPort());
logger.error("Ping failed: " + this.getUserName() + " Session: " + sessionId + " to MAGE server at " + connection.getHost() + ':' + connection.getPort());
throw new MageException("Ping failed");
}
pingTime.add(System.nanoTime() - startTime);
@ -1602,7 +1602,7 @@ public class SessionImpl implements Session {
sum += time;
}
milliSeconds = TimeUnit.MILLISECONDS.convert(sum / pingTime.size(), TimeUnit.NANOSECONDS);
pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms" : "<1ms") + ")";
pingInfo = lastPing + " (Av: " + (milliSeconds > 0 ? milliSeconds + "ms" : "<1ms") + ')';
}
return true;
} catch (MageException ex) {

View file

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

View file

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

View file

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

View file

@ -45,15 +45,15 @@ public class ChatMessage implements Serializable {
private MessageType messageType;
public enum MessageColor {
BLACK, RED, GREEN, BLUE, ORANGE, YELLOW;
BLACK, RED, GREEN, BLUE, ORANGE, YELLOW
}
public enum MessageType {
USER_INFO, STATUS, GAME, TALK, WHISPER;
USER_INFO, STATUS, GAME, TALK, WHISPER
}
public enum SoundToPlay {
PlayerLeft, PlayerQuitTournament, PlayerSubmittedDeck, PlayerWhispered;
PlayerLeft, PlayerQuitTournament, PlayerSubmittedDeck, PlayerWhispered
}
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.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) {
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 {
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);

View file

@ -138,7 +138,7 @@ public class GameView implements Serializable {
if (designation != null) {
stack.put(stackObject.getId(), new CardView(designation, (StackAbility) stackObject));
} 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) {
@ -147,7 +147,7 @@ public class GameView implements Serializable {
stack.put(stackObject.getId(), new CardView(((StackAbility) stackObject)));
checkPaid(stackObject.getId(), ((StackAbility) stackObject));
} 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 {
// 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()
&& (createdForPlayerId.equals(priorityPlayer.getId()) // player controls the 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 {
this.special = false;

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -70,14 +70,14 @@ public class TournamentGameView implements Serializable {
if (game.hasEnded()) {
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.result = game.getWinner();
}
else {
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.result = "";

View file

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

View file

@ -67,7 +67,7 @@ public class TournamentView implements Serializable {
typeText.append(" / ").append(tournament.getOptions().getMatchOptions().getDeckType());
}
if (tournament.getNumberRounds() > 0) {
typeText.append(" ").append(tournament.getNumberRounds()).append(" rounds");
typeText.append(' ').append(tournament.getNumberRounds()).append(" rounds");
}
tournamentType = typeText.toString();
startTime = tournament.getStartTime();
@ -79,7 +79,7 @@ public class TournamentView implements Serializable {
tournamentState = tournament.getTournamentState();
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 {
runningInfo = "";
}

View file

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

View file

@ -575,14 +575,14 @@ class UpdateUsersTask extends SwingWorker<Void, List<UserView>> {
for (UserView u2 : usersToCheck) {
if (u1.getUserName().equals(u2.getUserName())) {
found = true;
String s = u1.getUserName() + "," + u1.getHost();
String s = u1.getUserName() + ',' + u1.getHost();
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");
}
s = u2.getUserName() + "," + u2.getHost();
s = u2.getUserName() + ',' + u2.getHost();
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");
}
break;

View file

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

View file

@ -189,11 +189,11 @@ public class TinyLeaders extends Constructed {
}
}
} else {
invalid.put("Commander", "Commander banned (" + commander.getName() + ")");
invalid.put("Commander", "Commander banned (" + commander.getName() + ')');
valid = false;
}
} else {
invalid.put("Commander", "Commander invalide (" + commander.getName() + ")");
invalid.put("Commander", "Commander invalide (" + commander.getName() + ')');
valid = false;
}
} else {
@ -221,22 +221,22 @@ public class TinyLeaders extends Constructed {
private boolean isCardFormatValid(Card card, Card commander, FilterMana color) {
if (!cardHasValideColor(color, card)) {
invalid.put(card.getName(), "Invalid color (" + commander.getName() + ")");
invalid.put(card.getName(), "Invalid color (" + commander.getName() + ')');
return false;
}
//905.5b - Converted mana cost must be 3 or less
if (card instanceof SplitCard) {
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;
}
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;
}
} 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 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());
StringBuilder sb = new StringBuilder("-> Hand: [");
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.append("-> Permanents: [");
for (Permanent permanent : game.getBattlefield().getAllPermanents()) {
@ -258,10 +258,10 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
if (permanent.isAttacking()) {
sb.append("(attacking)");
}
sb.append(";");
sb.append(';');
}
}
logger.info(sb.append("]").toString());
logger.info(sb.append(']').toString());
}
protected void act(Game game) {
@ -272,7 +272,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
while (actions.peek() != null) {
Ability ability = actions.poll();
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 (UUID id : target.getTargets()) {
target.updateTarget(id, game);
@ -318,7 +318,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
//int bestScore = addActionsTimed(new FilterAbility());
currentScore = GameStateEvaluator2.evaluate(playerId, game);
addActionsTimed();
if (root.children.size() > 0) {
if (!root.children.isEmpty()) {
root = root.children.get(0);
//GameStateEvaluator2.evaluate(playerId, root.getGame());
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");
//}
} 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) {
if (root != null && root.children.size() > 0) {
if (root != null && !root.children.isEmpty()) {
SimulationNode2 test = root;
root = root.children.get(0);
while (root.children.size() > 0 && !root.playerId.equals(playerId)) {
while (!root.children.isEmpty() && !root.playerId.equals(playerId)) {
test = root;
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) {
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();
SimulationNode2 bestChild = null;
for (SimulationNode2 child : node.getChildren()) {
@ -525,7 +525,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
UUID currentPlayerId = node.getGame().getPlayerList().get();
//logger.info("reached - " + val + ", playerId=" + playerId + ", node.pid="+currentPlayerId);
return val;
} else if (node.getChildren().size() > 0) {
} else if (!node.getChildren().isEmpty()) {
logger.trace("Add actions -- something added children:" + node.getChildren().size());
val = minimaxAB(node, depth - 1, alpha, beta);
return val;
@ -542,7 +542,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
if (game.gameOver(null)) {
val = GameStateEvaluator2.evaluate(playerId, game);
} else if (node.getChildren().size() > 0) {
} else if (!node.getChildren().isEmpty()) {
//declared attackers or blockers or triggered abilities
logger.debug("Add actions -- attack/block/trigger added children:" + node.getChildren().size());
val = minimaxAB(node, depth - 1, alpha, beta);
@ -568,8 +568,8 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
SimulationNode2 bestNode = null;
List<Ability> allActions = currentPlayer.simulatePriority(game);
optimize(game, allActions);
if (logger.isInfoEnabled() && allActions.size() > 0 && depth == maxDepth) {
logger.info("ADDED ACTIONS (" + allActions.size() + ") " + " " + allActions);
if (logger.isInfoEnabled() && !allActions.isEmpty() && depth == maxDepth) {
logger.info("ADDED ACTIONS (" + allActions.size() + ") " + ' ' + allActions);
}
int counter = 0;
int bestValSubNodes = Integer.MIN_VALUE;
@ -606,18 +606,18 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
} else {
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) {
StringBuilder sb = new StringBuilder("Sim Prio [").append(depth).append("] #").append(counter)
.append(" <").append(val).append("> (").append(action)
.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() : "");
SimulationNode2 logNode = newNode;
while (logNode.getChildren() != null && logNode.getChildren().size() > 0) {
while (logNode.getChildren() != null && !logNode.getChildren().isEmpty()) {
logNode = logNode.getChildren().get(0);
if (logNode.getAbilities() != null && logNode.getAbilities().size() > 0) {
sb.append(" -> [").append(logNode.getDepth()).append("]").append(logNode.getAbilities().toString()).append("<").append(logNode.getScore()).append(">");
if (logNode.getAbilities() != null && !logNode.getAbilities().isEmpty()) {
sb.append(" -> [").append(logNode.getDepth()).append(']').append(logNode.getAbilities().toString()).append('<').append(logNode.getScore()).append('>');
}
}
logger.info(sb);
@ -634,7 +634,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
alpha = val;
bestNode = newNode;
bestNode.setScore(val);
if (newNode.getChildren().size() > 0) {
if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat());
}
/*
@ -660,7 +660,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
beta = val;
bestNode = newNode;
bestNode.setScore(val);
if (newNode.getChildren().size() > 0) {
if (!newNode.getChildren().isEmpty()) {
bestNode.setCombat(newNode.getChildren().get(0).getCombat());
}
}
@ -1437,7 +1437,7 @@ public class ComputerPlayer6 extends ComputerPlayer /*implements Player*/ {
StringBuilder sb = new StringBuilder();
if (targets != null) {
for (Target target : targets) {
sb.append("[").append(target.getTargetedName(game)).append("]");
sb.append('[').append(target.getTargetedName(game)).append(']');
}
if (sb.length() > 0) {
sb.insert(0, " targeting ");

View file

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

View file

@ -64,7 +64,7 @@ public class GameStateEvaluator2 {
int onePermScore = evaluatePermanent(permanent, game);
playerScore += onePermScore;
if (logger.isDebugEnabled()) {
sbPlayer.append(permanent.getName()).append("[").append(onePermScore).append("] ");
sbPlayer.append(permanent.getName()).append('[').append(onePermScore).append("] ");
}
}
if (logger.isDebugEnabled()) {
@ -78,7 +78,7 @@ public class GameStateEvaluator2 {
int onePermScore = evaluatePermanent(permanent, game);
opponentScore += onePermScore;
if (logger.isDebugEnabled()) {
sbOpponent.append(permanent.getName()).append("[").append(onePermScore).append("] ");
sbOpponent.append(permanent.getName()).append('[').append(onePermScore).append("] ");
}
}
if (logger.isDebugEnabled()) {
@ -97,7 +97,7 @@ public class GameStateEvaluator2 {
handScore *= 5;
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;
}

View file

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

View file

@ -103,7 +103,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
if (logger.isTraceEnabled()) {
for (Ability a : allActions) {
logger.info("ability==" + a);
if (a.getTargets().size() > 0) {
if (!a.getTargets().isEmpty()) {
MageObject mageObject = game.getObject(a.getFirstTarget());
if (mageObject != null) {
logger.info(" target=" + mageObject.getName());
@ -170,14 +170,14 @@ public class SimulatedPlayer2 extends ComputerPlayer {
}
}
// 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);
if (varCost != null) {
varCost.setPaid();
}
card.adjustTargets(newAbility, game);
// 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);
}
}
@ -240,7 +240,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
}
List<Ability> filtered = new ArrayList<>();
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());
for (String s : suggested) {
String[] groups = s.split(";");
@ -338,7 +338,7 @@ public class SimulatedPlayer2 extends ComputerPlayer {
binary.setLength(0);
binary.append(Integer.toBinaryString(i));
while (binary.length() < attackersList.size()) {
binary.insert(0, "0");
binary.insert(0, '0');
}
for (int j = 0; j < attackersList.size(); j++) {
if (binary.charAt(j) == '1') {

View file

@ -161,7 +161,7 @@ public class CombatUtil {
UUID attackerId = game.getCombat().getAttackerId();
UUID defenderId = game.getCombat().getDefenders().iterator().next();
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();
}
@ -298,7 +298,7 @@ public class CombatUtil {
UUID attackerId = game.getCombat().getAttackerId();
UUID defenderId = game.getCombat().getDefenders().iterator().next();
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();
}

View file

@ -199,7 +199,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override
public boolean choose(Outcome outcome, Target target, UUID sourceId, Game game, Map<String, Serializable> options) {
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
UUID abilityControllerId = playerId;
@ -212,7 +212,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
if (target.getOriginalTarget() instanceof TargetDiscard) {
findPlayables(game);
if (unplayable.size() > 0) {
if (!unplayable.isEmpty()) {
for (int i = unplayable.size() - 1; i >= 0; i--) {
if (target.canTarget(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++) {
if (target.canTarget(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
public boolean chooseTarget(Outcome outcome, Target target, Ability source, Game game) {
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
UUID abilityControllerId = playerId;
@ -467,7 +467,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
Cards cards = new CardsImpl(target.possibleTargets(source.getSourceId(), getId(), game));
ArrayList<Card> cardsInHand = new ArrayList<>(cards.getCards(game));
while (!target.isChosen()
&& target.possibleTargets(source.getSourceId(), getId(), game).size() > 0
&& !target.possibleTargets(source.getSourceId(), getId(), game).isEmpty()
&& target.getMaxNumberOfTargets() > target.getTargets().size()) {
Card card = pickBestCard(cardsInHand, null, target, source, game);
if (card != null) {
@ -482,7 +482,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
} else {
findPlayables(game);
if (unplayable.size() > 0) {
if (!unplayable.isEmpty()) {
for (int i = unplayable.size() - 1; i >= 0; i--) {
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);
@ -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++) {
if (target.canTarget(getId(), 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();
}
if (target.getOriginalTarget() instanceof TargetSpell) {
if (game.getStack().size() > 0) {
if (!game.getStack().isEmpty()) {
Iterator<StackObject> it = game.getStack().iterator();
while (it.hasNext()) {
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();
while (it.hasNext()) {
StackObject stackObject = it.next();
@ -817,7 +817,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override
public boolean chooseTargetAmount(Outcome outcome, TargetAmount target, Ability source, Game game) {
if (log.isDebugEnabled()) {
log.debug("chooseTarget: " + outcome.toString() + ":" + target.toString());
log.debug("chooseTarget: " + outcome.toString() + ':' + target.toString());
}
UUID opponentId = game.getOpponents(playerId).iterator().next();
if (target.getOriginalTarget() instanceof TargetCreatureOrPlayerAmount) {
@ -878,7 +878,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
break;
case PRECOMBAT_MAIN:
findPlayables(game);
if (playableAbilities.size() > 0) {
if (!playableAbilities.isEmpty()) {
for (ActivatedAbility ability : playableAbilities) {
if (ability.canActivate(playerId, game)) {
if (ability.getEffects().hasOutcome(Outcome.PutLandInPlay)) {
@ -909,7 +909,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
case POSTCOMBAT_MAIN:
findPlayables(game);
if (game.getStack().isEmpty()) {
if (playableNonInstant.size() > 0) {
if (!playableNonInstant.isEmpty()) {
for (Card card : playableNonInstant) {
if (card.getSpellAbility().canActivate(playerId, 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) {
if (ability.canActivate(playerId, game)) {
if (!(ability.getEffects().get(0) instanceof BecomesCreatureSourceEffect)) {
@ -975,7 +975,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
}
lands.add(landCard);
}
while (lands.size() > 0 && this.canPlayLand()) {
while (!lands.isEmpty() && this.canPlayLand()) {
if (lands.size() == 1) {
this.playLand(lands.iterator().next(), game, false);
} else {
@ -1030,7 +1030,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (Card card : nonLands) {
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
for (Mana option : options) {
option.add(Mana.GenericMana(3));
@ -1062,7 +1062,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
continue;
}
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
for (Mana option : abilityOptions) {
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)) {
if (game.getOpponents(this.getId()).contains(permanent.getControllerId())
&& permanent.getCardType().contains(CardType.CREATURE)
&& permanent.getSubtype(game).size() > 0) {
&& !permanent.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(permanent.getSubtype(game).get(0))) {
choice.setChoice(permanent.getSubtype(game).get(0));
break;
@ -1398,7 +1398,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (UUID opponentId : game.getOpponents(this.getId())) {
Player opponent = game.getPlayer(opponentId);
for (Card card : opponent.getGraveyard().getCards(game)) {
if (card != null && card.getCardType().contains(CardType.CREATURE) && card.getSubtype(game).size() > 0) {
if (card != null && card.getCardType().contains(CardType.CREATURE) && !card.getSubtype(game).isEmpty()) {
if (choice.getChoices().contains(card.getSubtype(game).get(0))) {
choice.setChoice(card.getSubtype(game).get(0));
break;
@ -1414,7 +1414,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
// choose a creature type of hand or library
for (UUID cardId : this.getHand()) {
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))) {
choice.setChoice(card.getSubtype(game).get(0));
break;
@ -1424,7 +1424,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
if (!choice.isChosen()) {
for (UUID cardId : this.getLibrary().getCardList()) {
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))) {
choice.setChoice(card.getSubtype(game).get(0));
break;
@ -1545,7 +1545,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
MageObject object = game.getObject(ability.getSourceId());
if (object != null) {
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()));
// TODO: Improve this
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) {
log.debug("chooseTriggeredAbility: " + abilities.toString());
//TODO: improve this
if (abilities.size() > 0) {
if (!abilities.isEmpty()) {
return abilities.get(0);
}
return null;
@ -1729,7 +1729,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
@Override
public void construct(Tournament tournament, Deck deck) {
if (deck != null && deck.getCards().size() < 40 && deck.getSideboard().size() > 0) {
if (deck != null && deck.getCards().size() < 40 && !deck.getSideboard().isEmpty()) {
//pick the top 23 cards
if (chosenColors == null) {
for (Card card : deck.getSideboard()) {
@ -1999,7 +1999,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
for (int i = 1; i < powerElements; i++) {
String binary = Integer.toBinaryString(i);
while (binary.length() < attackersList.size()) {
binary = "0" + binary;
binary = '0' + binary;
}
List<Permanent> trialAttackers = new ArrayList<>();
for (int j = 0; j < attackersList.size(); j++) {
@ -2119,7 +2119,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
StringBuilder sb = new StringBuilder();
sb.append(message).append(": ");
for (MageObject object : list) {
sb.append(object.getName()).append(",");
sb.append(object.getName()).append(',');
}
log.info(sb.toString());
}
@ -2128,7 +2128,7 @@ public class ComputerPlayer extends PlayerImpl implements Player {
StringBuilder sb = new StringBuilder();
sb.append(message).append(": ");
for (Ability ability : list) {
sb.append(ability.getRule()).append(",");
sb.append(ability.getRule()).append(',');
}
log.debug(sb.toString());
}

View file

@ -215,7 +215,7 @@ public class ComputerPlayerMCTS extends ComputerPlayer implements Player {
UUID opponentId = game.getCombat().getDefenders().iterator().next();
for (UUID attackerId: combat.getAttackers()) {
this.declareAttacker(attackerId, opponentId, game, false);
sb.append(game.getPermanent(attackerId).getName()).append(",");
sb.append(game.getPermanent(attackerId).getName()).append(',');
}
logger.info(sb.toString());
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: ");
for (UUID blockerId: combat.getGroups().get(i).getBlockers()) {
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());
@ -448,7 +448,7 @@ public class ComputerPlayerMCTS extends ComputerPlayer implements Player {
StringBuilder sb = new StringBuilder();
sb.append(game.getTurn().getValue(game.getTurnNum()));
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());
}

View file

@ -567,9 +567,9 @@ public class MCTSNode {
public static void logHitMiss() {
if (USE_ACTION_CACHE) {
StringBuilder sb = new StringBuilder();
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("Blocks Cache -- Hits: ").append(blocksHit).append(" Misses: ").append(blocksMiss).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("Blocks Cache -- Hits: ").append(blocksHit).append(" Misses: ").append(blocksMiss).append('\n');
logger.info(sb.toString());
}
}

View file

@ -52,7 +52,7 @@ public class MCTSPlayer extends ComputerPlayer {
private NextAction nextAction;
public enum NextAction {
PRIORITY, SELECT_ATTACKERS, SELECT_BLOCKERS;
PRIORITY, SELECT_ATTACKERS, SELECT_BLOCKERS
}
public MCTSPlayer(UUID id) {
@ -83,7 +83,7 @@ public class MCTSPlayer extends ComputerPlayer {
for (Ability ability: playables) {
List<Ability> options = game.getPlayer(playerId).getPlayableOptions(ability, game);
if (options.isEmpty()) {
if (ability.getManaCosts().getVariableCosts().size() > 0) {
if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(ability, all, game);
}
else {
@ -92,7 +92,7 @@ public class MCTSPlayer extends ComputerPlayer {
}
else {
for (Ability option: options) {
if (ability.getManaCosts().getVariableCosts().size() > 0) {
if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
simulateVariableCosts(option, all, game);
}
else {
@ -131,7 +131,7 @@ public class MCTSPlayer extends ComputerPlayer {
binary.setLength(0);
binary.append(Integer.toBinaryString(i));
while (binary.length() < attackersList.size()) {
binary.insert(0, "0");
binary.insert(0, '0');
}
List<UUID> engagement = new ArrayList<UUID>();
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()));
}
}
if (ability.getManaCosts().getVariableCosts().size() > 0) {
if (!ability.getManaCosts().getVariableCosts().isEmpty()) {
int amount = getAvailableManaProducers(game).size() - ability.getManaCosts().convertedManaCost();
if (amount > 0) {
ability = ability.copy();
@ -195,7 +195,7 @@ public class SimulatedPlayerMCTS extends MCTSPlayer {
StringBuilder binary = new StringBuilder();
binary.append(Integer.toBinaryString(value));
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++) {
if (binary.charAt(i) == '1') {
@ -221,7 +221,7 @@ public class SimulatedPlayerMCTS extends MCTSPlayer {
int check = RandomUtil.nextInt(numGroups + 1);
if (check < numGroups) {
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);
}
}

View file

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

View file

@ -139,7 +139,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
else
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");
if (root.children.size() > 0) {
if (!root.children.isEmpty()) {
root = root.children.get(0);
actions = new LinkedList<Ability>(root.abilities);
combat = root.combat;
@ -163,7 +163,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
else
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");
if (root.children.size() > 0) {
if (!root.children.isEmpty()) {
root = root.children.get(0);
actions = new LinkedList<Ability>(root.abilities);
combat = root.combat;
@ -189,7 +189,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
logger.debug(indent(node.depth) + "simulating -- reached end state");
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());
val = minimaxAB(node, alpha, beta);
}
@ -238,7 +238,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
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());
val = minimaxAB(node, alpha, beta);
}
@ -388,7 +388,7 @@ public class ComputerPlayer3 extends ComputerPlayer2 implements Player {
}
Game sim = game.copy();
for (CombatGroup group: engagement.getGroups()) {
if (group.getAttackers().size() > 0) {
if (!group.getAttackers().isEmpty()) {
UUID attackerId = group.getAttackers().get(0);
for (UUID blockerId: group.getBlockers()) {
sim.getPlayer(defenderId).declareBlocker(defenderId, blockerId, attackerId, sim);

View file

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

View file

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

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