Cleanup: use Lists rather than arrays whenever applicable (removes some methods)

This commit is contained in:
elcnesh
2015-05-11 14:22:08 +00:00
parent 77c479832c
commit 49dc0e2e59
43 changed files with 450 additions and 391 deletions

View File

@@ -242,7 +242,7 @@ public class PlayerControllerAi extends PlayerController {
} }
@Override @Override
public void reveal(Collection<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix) { public void reveal(List<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix) {
// We don't know how to reveal cards to AI // We don't know how to reveal cards to AI
} }
@@ -583,7 +583,7 @@ public class PlayerControllerAi extends PlayerController {
} }
@Override @Override
public CounterType chooseCounterType(Collection<CounterType> options, SpellAbility sa, String prompt) { public CounterType chooseCounterType(List<CounterType> options, SpellAbility sa, String prompt) {
// may write a smarter AI if you need to (with calls to AI-clas for given API ability) // may write a smarter AI if you need to (with calls to AI-clas for given API ability)
// TODO: ArsenalNut (06 Feb 12)computer needs // TODO: ArsenalNut (06 Feb 12)computer needs

View File

@@ -7,6 +7,14 @@ public final class EnumUtil {
private EnumUtil() { private EnumUtil() {
} }
/**
* Get the names of the values of an enum type.
*
* @param enumType
* an {@link Enum} type.
* @return an {@link ImmutableList} of strings representing the names of the
* enum's values.
*/
public static ImmutableList<String> getNames(final Class<? extends Enum<?>> enumType) { public static ImmutableList<String> getNames(final Class<? extends Enum<?>> enumType) {
final ImmutableList.Builder<String> builder = ImmutableList.builder(); final ImmutableList.Builder<String> builder = ImmutableList.builder();
for (final Enum<?> type : enumType.getEnumConstants()) { for (final Enum<?> type : enumType.getEnumConstants()) {

View File

@@ -5,6 +5,8 @@ import forge.game.trigger.TriggerType;
import java.util.HashMap; import java.util.HashMap;
import com.google.common.collect.ImmutableList;
/** /**
* Represents the planar dice for Planechase games. * Represents the planar dice for Planechase games.
* *
@@ -59,4 +61,6 @@ public enum PlanarDice {
throw new RuntimeException("Element " + value + " not found in PlanarDice enum"); throw new RuntimeException("Element " + value + " not found in PlanarDice enum");
} }
public static final ImmutableList<PlanarDice> values = ImmutableList.copyOf(values());
} }

View File

@@ -12,8 +12,11 @@ import forge.game.zone.Zone;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.ImmutableList;
public class CountersRemoveEffect extends SpellAbilityEffect { public class CountersRemoveEffect extends SpellAbilityEffect {
@Override @Override
protected String getStackDescription(SpellAbility sa) { protected String getStackDescription(SpellAbility sa) {
@@ -93,7 +96,7 @@ public class CountersRemoveEffect extends SpellAbilityEffect {
while (cntToRemove > 0 && tgtCard.hasCounters()) { while (cntToRemove > 0 && tgtCard.hasCounters()) {
final Map<CounterType, Integer> tgtCounters = tgtCard.getCounters(); final Map<CounterType, Integer> tgtCounters = tgtCard.getCounters();
CounterType chosenType = pc.chooseCounterType(tgtCounters.keySet(), sa, "Select type of counters to remove"); CounterType chosenType = pc.chooseCounterType(ImmutableList.copyOf(tgtCounters.keySet()), sa, "Select type of counters to remove");
String prompt = "Select the number of " + chosenType.getName() + " counters to remove"; String prompt = "Select the number of " + chosenType.getName() + " counters to remove";
int chosenAmount = pc.chooseNumber(sa, prompt, 1, Math.min(cntToRemove, tgtCounters.get(chosenType))); int chosenAmount = pc.chooseNumber(sa, prompt, 1, Math.min(cntToRemove, tgtCounters.get(chosenType)));

View File

@@ -18,6 +18,8 @@
package forge.game.card; package forge.game.card;
import com.google.common.collect.ImmutableList;
/** /**
* The class Counters. * The class Counters.
* *
@@ -311,4 +313,6 @@ public enum CounterType {
final String replacedName = name.replace("/", "").replaceAll("\\+", "p").replaceAll("\\-", "m").toUpperCase(); final String replacedName = name.replace("/", "").replaceAll("\\+", "p").replaceAll("\\-", "m").toUpperCase();
return Enum.valueOf(CounterType.class, replacedName); return Enum.valueOf(CounterType.class, replacedName);
} }
public static final ImmutableList<CounterType> values = ImmutableList.copyOf(values());
} }

View File

@@ -1,11 +1,11 @@
package forge.game.player; package forge.game.player;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection;
import forge.game.card.Card; import forge.game.card.Card;
import forge.game.card.CardView; import forge.game.card.CardView;
import forge.game.zone.ZoneType; import forge.game.zone.ZoneType;
import forge.trackable.TrackableCollection;
/** /**
* Stores information to reveal cards after a delay unless those cards can be * Stores information to reveal cards after a delay unless those cards can be
@@ -14,22 +14,22 @@ import forge.game.zone.ZoneType;
public class DelayedReveal implements Serializable { public class DelayedReveal implements Serializable {
private static final long serialVersionUID = 5516713460440436615L; private static final long serialVersionUID = 5516713460440436615L;
private final Collection<CardView> cards; private final TrackableCollection<CardView> cards;
private final ZoneType zone; private final ZoneType zone;
private final PlayerView owner; private final PlayerView owner;
private final String messagePrefix; private final String messagePrefix;
public DelayedReveal(Iterable<Card> cards0, ZoneType zone0, PlayerView owner0) { public DelayedReveal(final Iterable<Card> cards0, final ZoneType zone0, final PlayerView owner0) {
this(cards0, zone0, owner0, null); this(cards0, zone0, owner0, null);
} }
public DelayedReveal(Iterable<Card> cards0, ZoneType zone0, PlayerView owner0, String messagePrefix0) { public DelayedReveal(final Iterable<Card> cards0, final ZoneType zone0, final PlayerView owner0, final String messagePrefix0) {
cards = CardView.getCollection(cards0); cards = CardView.getCollection(cards0);
zone = zone0; zone = zone0;
owner = owner0; owner = owner0;
messagePrefix = messagePrefix0; messagePrefix = messagePrefix0;
} }
public Collection<CardView> getCards() { public TrackableCollection<CardView> getCards() {
return cards; return cards;
} }
@@ -45,7 +45,7 @@ public class DelayedReveal implements Serializable {
return messagePrefix; return messagePrefix;
} }
public void remove(CardView card) { public void remove(final CardView card) {
cards.remove(card); cards.remove(card);
} }

View File

@@ -141,7 +141,7 @@ public abstract class PlayerController {
reveal(cards, zone, owner, null); reveal(cards, zone, owner, null);
} }
public abstract void reveal(CardCollectionView cards, ZoneType zone, Player owner, String messagePrefix); public abstract void reveal(CardCollectionView cards, ZoneType zone, Player owner, String messagePrefix);
public abstract void reveal(Collection<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix); public abstract void reveal(List<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix);
/** Shows message to player to reveal chosen cardName, creatureType, number etc. AI must analyze API to understand what that is */ /** Shows message to player to reveal chosen cardName, creatureType, number etc. AI must analyze API to understand what that is */
public abstract void notifyOfValue(SpellAbility saSource, GameObject realtedTarget, String value); public abstract void notifyOfValue(SpellAbility saSource, GameObject realtedTarget, String value);
@@ -192,7 +192,7 @@ public abstract class PlayerController {
public abstract PaperCard chooseSinglePaperCard(SpellAbility sa, String message, Predicate<PaperCard> cpp, String name); public abstract PaperCard chooseSinglePaperCard(SpellAbility sa, String message, Predicate<PaperCard> cpp, String name);
public abstract List<String> chooseColors(String message, SpellAbility sa, int min, int max, List<String> options); public abstract List<String> chooseColors(String message, SpellAbility sa, int min, int max, List<String> options);
public abstract CounterType chooseCounterType(Collection<CounterType> options, SpellAbility sa, String prompt); public abstract CounterType chooseCounterType(List<CounterType> options, SpellAbility sa, String prompt);
public abstract boolean confirmPayment(CostPart costPart, String string); public abstract boolean confirmPayment(CostPart costPart, String string);
public abstract ReplacementEffect chooseSingleReplacementEffect(String prompt, List<ReplacementEffect> possibleReplacers, HashMap<String, Object> runParams); public abstract ReplacementEffect chooseSingleReplacementEffect(String prompt, List<ReplacementEffect> possibleReplacers, HashMap<String, Object> runParams);

View File

@@ -132,12 +132,12 @@ public class GuiDesktop implements IGuiBase {
} }
@Override @Override
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return FOptionPane.showOptionDialog(message, title, icon == null ? null : FSkin.getImage(icon), options, defaultOption); return FOptionPane.showOptionDialog(message, title, icon == null ? null : FSkin.getImage(icon), options, defaultOption);
} }
@Override @Override
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return FOptionPane.showInputDialog(message, title, icon == null ? null : FSkin.getImage(icon), initialInput, inputOptions); return FOptionPane.showInputDialog(message, title, icon == null ? null : FSkin.getImage(icon), initialInput, inputOptions);
} }

View File

@@ -126,7 +126,7 @@ public enum FControl implements KeyEventDispatcher {
public void windowClosing(final WindowEvent e) { public void windowClosing(final WindowEvent e) {
switch (closeAction) { switch (closeAction) {
case NONE: //prompt user for close action if not previously specified case NONE: //prompt user for close action if not previously specified
final String[] options = {"Close Screen", "Exit Forge", "Cancel"}; final List<String> options = ImmutableList.of("Close Screen", "Exit Forge", "Cancel");
final int reply = FOptionPane.showOptionDialog( final int reply = FOptionPane.showOptionDialog(
"Forge now supports navigation tabs which allow closing and switching between different screens with ease. " "Forge now supports navigation tabs which allow closing and switching between different screens with ease. "
+ "As a result, you no longer need to use the X button in the upper right to close the current screen and go back." + "As a result, you no longer need to use the X button in the upper right to close the current screen and go back."

View File

@@ -1,5 +1,19 @@
package forge.deckchooser; package forge.deckchooser;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.UiCommand; import forge.UiCommand;
import forge.deck.ColorDeckGenerator; import forge.deck.ColorDeckGenerator;
@@ -24,16 +38,6 @@ import forge.quest.QuestUtil;
import forge.screens.match.controllers.CDetailPicture; import forge.screens.match.controllers.CDetailPicture;
import forge.toolbox.FLabel; import forge.toolbox.FLabel;
import forge.toolbox.FOptionPane; import forge.toolbox.FOptionPane;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import javax.swing.*;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class FDeckChooser extends JPanel implements IDecksComboBoxListener { public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
@@ -58,9 +62,9 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
final FDeckChooser chooser = new FDeckChooser(cDetailPicture, forAi); final FDeckChooser chooser = new FDeckChooser(cDetailPicture, forAi);
chooser.initialize(defaultDeckType); chooser.initialize(defaultDeckType);
chooser.populate(); chooser.populate();
Dimension parentSize = JOptionPane.getRootFrame().getSize(); final Dimension parentSize = JOptionPane.getRootFrame().getSize();
chooser.setMinimumSize(new Dimension((int)(parentSize.getWidth() / 2), (int)parentSize.getHeight() - 200)); chooser.setMinimumSize(new Dimension((int)(parentSize.getWidth() / 2), (int)parentSize.getHeight() - 200));
final FOptionPane optionPane = new FOptionPane(null, title, null, chooser, new String[] { "OK", "Cancel" }, 0); final FOptionPane optionPane = new FOptionPane(null, title, null, chooser, ImmutableList.of("OK", "Cancel"), 0);
optionPane.setDefaultFocus(chooser); optionPane.setDefaultFocus(chooser);
chooser.lstDecks.setItemActivateCommand(new UiCommand() { chooser.lstDecks.setItemActivateCommand(new UiCommand() {
@Override @Override
@@ -69,7 +73,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
} }
}); });
optionPane.setVisible(true); optionPane.setVisible(true);
int dialogResult = optionPane.getResult(); final int dialogResult = optionPane.getResult();
optionPane.dispose(); optionPane.dispose();
if (dialogResult == 0) { if (dialogResult == 0) {
return chooser.getDeck(); return chooser.getDeck();
@@ -81,9 +85,8 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
lstDecks = new DeckManager(GameType.Constructed, cDetailPicture); lstDecks = new DeckManager(GameType.Constructed, cDetailPicture);
setOpaque(false); setOpaque(false);
isAi = forAi; isAi = forAi;
UiCommand cmdViewDeck = new UiCommand() { final UiCommand cmdViewDeck = new UiCommand() {
@Override @Override public void run() {
public void run() {
if (selectedDeckType != DeckType.COLOR_DECK && selectedDeckType != DeckType.THEME_DECK) { if (selectedDeckType != DeckType.COLOR_DECK && selectedDeckType != DeckType.THEME_DECK) {
FDeckViewer.show(getDeck()); FDeckViewer.show(getDeck());
} }
@@ -96,16 +99,16 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
public void initialize() { public void initialize() {
initialize(DeckType.COLOR_DECK); initialize(DeckType.COLOR_DECK);
} }
public void initialize(DeckType defaultDeckType) { public void initialize(final DeckType defaultDeckType) {
initialize(null, defaultDeckType); initialize(null, defaultDeckType);
} }
public void initialize(FPref savedStateSetting, DeckType defaultDeckType) { public void initialize(final FPref savedStateSetting, final DeckType defaultDeckType) {
stateSetting = savedStateSetting; stateSetting = savedStateSetting;
selectedDeckType = defaultDeckType; selectedDeckType = defaultDeckType;
} }
public DeckType getSelectedDeckType() { return selectedDeckType; } public DeckType getSelectedDeckType() { return selectedDeckType; }
public void setSelectedDeckType(DeckType selectedDeckType0) { public void setSelectedDeckType(final DeckType selectedDeckType0) {
refreshDecksList(selectedDeckType0, false, null); refreshDecksList(selectedDeckType0, false, null);
} }
@@ -247,8 +250,8 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
// Special branch for quest events // Special branch for quest events
if (selectedDeckType == DeckType.QUEST_OPPONENT_DECK) { if (selectedDeckType == DeckType.QUEST_OPPONENT_DECK) {
QuestEvent event = DeckgenUtil.getQuestEvent(lstDecks.getSelectedItem().getName()); final QuestEvent event = DeckgenUtil.getQuestEvent(lstDecks.getSelectedItem().getName());
RegisteredPlayer result = new RegisteredPlayer(event.getEventDeck()); final RegisteredPlayer result = new RegisteredPlayer(event.getEventDeck());
if (event instanceof QuestEventChallenge) { if (event instanceof QuestEventChallenge) {
result.setStartingLife(((QuestEventChallenge) event).getAiLife()); result.setStartingLife(((QuestEventChallenge) event).getAiLife());
} }
@@ -283,7 +286,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
return isAi; return isAi;
} }
public void setIsAi(boolean isAiDeck) { public void setIsAi(final boolean isAiDeck) {
isAi = isAiDeck; isAi = isAiDeck;
} }
@@ -317,7 +320,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
refreshDecksList(ev.getDeckType(), false, ev); refreshDecksList(ev.getDeckType(), false, ev);
} }
private void refreshDecksList(DeckType deckType, boolean forceRefresh, DecksComboBoxEvent ev) { private void refreshDecksList(final DeckType deckType, final boolean forceRefresh, final DecksComboBoxEvent ev) {
if (decksComboBox == null) { return; } // Not yet populated if (decksComboBox == null) { return; } // Not yet populated
if (selectedDeckType == deckType && !forceRefresh) { return; } if (selectedDeckType == deckType && !forceRefresh) { return; }
selectedDeckType = deckType; selectedDeckType = deckType;
@@ -330,29 +333,29 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
lstDecks.setCaption(deckType.toString()); lstDecks.setCaption(deckType.toString());
switch (deckType) { switch (deckType) {
case CUSTOM_DECK: case CUSTOM_DECK:
updateCustom(); updateCustom();
break; break;
case COLOR_DECK: case COLOR_DECK:
updateColors(); updateColors();
break; break;
case THEME_DECK: case THEME_DECK:
updateThemes(); updateThemes();
break; break;
case QUEST_OPPONENT_DECK: case QUEST_OPPONENT_DECK:
updateQuestEvents(); updateQuestEvents();
break; break;
case PRECONSTRUCTED_DECK: case PRECONSTRUCTED_DECK:
updatePrecons(); updatePrecons();
break; break;
case RANDOM_DECK: case RANDOM_DECK:
updateRandom(); updateRandom();
break; break;
case NET_DECK: case NET_DECK:
updateNetDecks(); updateNetDecks();
break; break;
default: default:
break; //other deck types not currently supported here break; //other deck types not currently supported here
} }
} }
@@ -367,7 +370,7 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
} }
private String getState() { private String getState() {
StringBuilder state = new StringBuilder(); final StringBuilder state = new StringBuilder();
if (decksComboBox.getDeckType() == null || decksComboBox.getDeckType() == DeckType.NET_DECK) { if (decksComboBox.getDeckType() == null || decksComboBox.getDeckType() == DeckType.NET_DECK) {
//handle special case of net decks //handle special case of net decks
if (netDeckCategory == null) { return ""; } if (netDeckCategory == null) { return ""; }
@@ -381,15 +384,14 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
return state.toString(); return state.toString();
} }
private void joinSelectedDecks(StringBuilder state, String delimiter) { private void joinSelectedDecks(final StringBuilder state, final String delimiter) {
Iterable<DeckProxy> selectedDecks = lstDecks.getSelectedItems(); final Iterable<DeckProxy> selectedDecks = lstDecks.getSelectedItems();
boolean isFirst = true; boolean isFirst = true;
if (selectedDecks != null) { if (selectedDecks != null) {
for (DeckProxy deck : selectedDecks) { for (final DeckProxy deck : selectedDecks) {
if (isFirst) { if (isFirst) {
isFirst = false; isFirst = false;
} } else {
else {
state.append(delimiter); state.append(delimiter);
} }
state.append(deck.toString()); state.append(deck.toString());
@@ -398,14 +400,14 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
} }
public void restoreSavedState() { public void restoreSavedState() {
DeckType oldDeckType = selectedDeckType; final DeckType oldDeckType = selectedDeckType;
if (stateSetting == null) { if (stateSetting == null) {
//if can't restore saved state, just refresh deck list //if can't restore saved state, just refresh deck list
refreshDecksList(oldDeckType, true, null); refreshDecksList(oldDeckType, true, null);
return; return;
} }
String savedState = prefs.getPref(stateSetting); final String savedState = prefs.getPref(stateSetting);
refreshDecksList(getDeckTypeFromSavedState(savedState), true, null); refreshDecksList(getDeckTypeFromSavedState(savedState), true, null);
if (!lstDecks.setSelectedStrings(getSelectedDecksFromSavedState(savedState))) { if (!lstDecks.setSelectedStrings(getSelectedDecksFromSavedState(savedState))) {
//if can't select old decks, just refresh deck list //if can't select old decks, just refresh deck list
@@ -413,36 +415,32 @@ public class FDeckChooser extends JPanel implements IDecksComboBoxListener {
} }
} }
private DeckType getDeckTypeFromSavedState(String savedState) { private DeckType getDeckTypeFromSavedState(final String savedState) {
try { try {
if (StringUtils.isBlank(savedState)) { if (StringUtils.isBlank(savedState)) {
return selectedDeckType; return selectedDeckType;
} } else {
else { final String deckType = savedState.split(";")[0];
String deckType = savedState.split(";")[0];
if (deckType.startsWith(NetDeckCategory.PREFIX)) { if (deckType.startsWith(NetDeckCategory.PREFIX)) {
netDeckCategory = NetDeckCategory.selectAndLoad(lstDecks.getGameType(), deckType.substring(NetDeckCategory.PREFIX.length())); netDeckCategory = NetDeckCategory.selectAndLoad(lstDecks.getGameType(), deckType.substring(NetDeckCategory.PREFIX.length()));
return DeckType.NET_DECK; return DeckType.NET_DECK;
} }
return DeckType.valueOf(deckType); return DeckType.valueOf(deckType);
} }
} } catch (final IllegalArgumentException ex) {
catch (IllegalArgumentException ex) {
System.err.println(ex.getMessage() + ". Using default : " + selectedDeckType); System.err.println(ex.getMessage() + ". Using default : " + selectedDeckType);
return selectedDeckType; return selectedDeckType;
} }
} }
private List<String> getSelectedDecksFromSavedState(String savedState) { private List<String> getSelectedDecksFromSavedState(final String savedState) {
try { try {
if (StringUtils.isBlank(savedState)) { if (StringUtils.isBlank(savedState)) {
return new ArrayList<String>(); return new ArrayList<String>();
} } else {
else {
return Arrays.asList(savedState.split(";")[1].split(SELECTED_DECK_DELIMITER)); return Arrays.asList(savedState.split(";")[1].split(SELECTED_DECK_DELIMITER));
} }
} } catch (final Exception ex) {
catch (Exception ex) {
System.err.println(ex + " [savedState=" + savedState + "]"); System.err.println(ex + " [savedState=" + savedState + "]");
return new ArrayList<String>(); return new ArrayList<String>();
} }

View File

@@ -1,11 +1,14 @@
package forge.gui; package forge.gui;
import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; import java.util.concurrent.FutureTask;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.game.card.CardView; import forge.game.card.CardView;
import forge.screens.match.CMatchUI; import forge.screens.match.CMatchUI;
@@ -16,9 +19,9 @@ import forge.toolbox.FOptionPane;
* *
*/ */
public class GuiDialog { public class GuiDialog {
private static final String[] defaultConfirmOptions = { "Yes", "No" }; private static final ImmutableList<String> defaultConfirmOptions = ImmutableList.of("Yes", "No");
public static boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options, final CMatchUI matchUI) { public static boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final List<String> options, final CMatchUI matchUI) {
final Callable<Boolean> confirmTask = new Callable<Boolean>() { final Callable<Boolean> confirmTask = new Callable<Boolean>() {
@Override public final Boolean call() { @Override public final Boolean call() {
if (matchUI != null && c != null) { if (matchUI != null && c != null) {
@@ -27,7 +30,7 @@ public class GuiDialog {
final String title = c == null ? "Question" : c + " - Ability"; final String title = c == null ? "Question" : c + " - Ability";
final String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question; final String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question;
final String[] opts = options == null ? defaultConfirmOptions : options; final List<String> opts = options == null ? defaultConfirmOptions : options;
final int answer = FOptionPane.showOptionDialog(questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1); final int answer = FOptionPane.showOptionDialog(questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1);
return Boolean.valueOf(answer == 0); return Boolean.valueOf(answer == 0);
}}; }};

View File

@@ -55,6 +55,8 @@ import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Pair;
import com.google.common.collect.ImmutableList;
import forge.UiCommand; import forge.UiCommand;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.error.BugReporter; import forge.error.BugReporter;
@@ -91,6 +93,8 @@ public class ImportDialog {
// volatile since it is checked from multiple threads // volatile since it is checked from multiple threads
private volatile boolean _cancel; private volatile boolean _cancel;
private static final ImmutableList<String> fixOrContinue = ImmutableList.of("Whoops, let me fix that!", "Continue with the import, I know what I'm doing.");
@SuppressWarnings("serial") @SuppressWarnings("serial")
public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) { public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) {
this.forcedSrcDir = forcedSrcDir; this.forcedSrcDir = forcedSrcDir;
@@ -636,8 +640,7 @@ public class ImportDialog {
sb.append("will come up again the next time you start Forge in order to migrate the remaining files<br>"); sb.append("will come up again the next time you start Forge in order to migrate the remaining files<br>");
sb.append("unless you move or delete them manually.</html>"); sb.append("unless you move or delete them manually.</html>");
final String[] options = { "Whoops, let me fix that!", "Continue with the import, I know what I'm doing." }; final int chosen = FOptionPane.showOptionDialog(sb.toString(), "Migration warning", FOptionPane.WARNING_ICON, fixOrContinue);
final int chosen = FOptionPane.showOptionDialog(sb.toString(), "Migration warning", FOptionPane.WARNING_ICON, options);
if (chosen != 1) { if (chosen != 1) {
// i.e. option 0 was chosen or the dialog was otherwise closed // i.e. option 0 was chosen or the dialog was otherwise closed

View File

@@ -37,6 +37,7 @@ import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener; import javax.swing.event.ListSelectionListener;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import forge.FThreads; import forge.FThreads;
@@ -88,12 +89,11 @@ public class ListChooser<T> {
this.list = list.getClass().isInstance(List.class) ? (List<T>)list : Lists.newArrayList(list); this.list = list.getClass().isInstance(List.class) ? (List<T>)list : Lists.newArrayList(list);
this.lstChoices = new FList<T>(new ChooserListModel()); this.lstChoices = new FList<T>(new ChooserListModel());
String[] options; final ImmutableList<String> options;
if (minChoices == 0) { if (minChoices == 0) {
options = new String[] {"OK","Cancel"}; options = ImmutableList.of("OK","Cancel");
} } else {
else { options = ImmutableList.of("OK");
options = new String[] {"OK"};
} }
if (maxChoices == 1 || minChoices == -1) { if (maxChoices == 1 || minChoices == -1) {

View File

@@ -12,6 +12,8 @@ import forge.toolbox.FOptionPane;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ImmutableList;
/** /**
* Handles editor preferences saving and loading. * Handles editor preferences saving and loading.
* *
@@ -69,6 +71,7 @@ public class SEditorIO {
return true; return true;
} }
private final static ImmutableList<String> confirmSaveOptions = ImmutableList.of("Save", "Don't Save", "Cancel");
/** /**
* Prompts to save changes if necessary. * Prompts to save changes if necessary.
* *
@@ -82,7 +85,7 @@ public class SEditorIO {
} }
final int choice = FOptionPane.showOptionDialog("Save changes to current deck?", "Save Changes?", final int choice = FOptionPane.showOptionDialog("Save changes to current deck?", "Save Changes?",
FOptionPane.QUESTION_ICON, new String[] {"Save", "Don't Save", "Cancel"}); FOptionPane.QUESTION_ICON, confirmSaveOptions);
if (choice == -1 || choice == 2) { return false; } if (choice == -1 || choice == 2) { return false; }

View File

@@ -19,6 +19,8 @@ package forge.screens.deckeditor.controllers;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.google.common.collect.ImmutableList;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.card.MagicColor; import forge.card.MagicColor;
import forge.deck.Deck; import forge.deck.Deck;
@@ -71,6 +73,8 @@ public class CEditorQuestDraftingProcess extends ACEditorBase<PaperCard, DeckGro
private DragCell deckGenParent = null; private DragCell deckGenParent = null;
private boolean saved = false; private boolean saved = false;
private static final ImmutableList<String> leaveOrCancel = ImmutableList.of("Leave", "Cancel");
//========== Constructor //========== Constructor
/** /**
@@ -290,7 +294,7 @@ public class CEditorQuestDraftingProcess extends ACEditorBase<PaperCard, DeckGro
String userPrompt = String userPrompt =
"This will end the current draft and you will not be able to join this tournament again.\nYour credits will be refunded and the draft will be removed.\n\n" + "This will end the current draft and you will not be able to join this tournament again.\nYour credits will be refunded and the draft will be removed.\n\n" +
"Leave anyway?"; "Leave anyway?";
boolean leave = FOptionPane.showOptionDialog(userPrompt, "Leave Draft?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), new String[] {"Leave", "Cancel"}, 1) == 0; boolean leave = FOptionPane.showOptionDialog(userPrompt, "Leave Draft?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), leaveOrCancel, 1) == 0;
if (leave) { if (leave) {
QuestEventDraft draft = quest.getAchievements().getCurrentDraft(); QuestEventDraft draft = quest.getAchievements().getCurrentDraft();
quest.getAssets().addCredits(draft.getEntryFee()); quest.getAssets().addCredits(draft.getEntryFee());

View File

@@ -707,12 +707,13 @@ public class VLobby implements IUpdateable {
return usedAvatars; return usedAvatars;
} }
private static final ImmutableList<String> genderOptions = ImmutableList.of("Male", "Female", "Any"),
typeOptions = ImmutableList.of("Fantasy", "Generic", "Any");
final String getNewName() { final String getNewName() {
final String title = "Get new random name"; final String title = "Get new random name";
final String message = "What type of name do you want to generate?"; final String message = "What type of name do you want to generate?";
final SkinImage icon = FOptionPane.QUESTION_ICON; final SkinImage icon = FOptionPane.QUESTION_ICON;
final String[] genderOptions = new String[]{ "Male", "Female", "Any" };
final String[] typeOptions = new String[]{ "Fantasy", "Generic", "Any" };
final int genderIndex = FOptionPane.showOptionDialog(message, title, icon, genderOptions, 2); final int genderIndex = FOptionPane.showOptionDialog(message, title, icon, genderOptions, 2);
if (genderIndex < 0) { if (genderIndex < 0) {
@@ -723,8 +724,8 @@ public class VLobby implements IUpdateable {
return null; return null;
} }
final String gender = genderOptions[genderIndex]; final String gender = genderOptions.get(genderIndex);
final String type = typeOptions[typeIndex]; final String type = typeOptions.get(typeIndex);
String confirmMsg, newName; String confirmMsg, newName;
final List<String> usedNames = getPlayerNames(); final List<String> usedNames = getPlayerNames();

View File

@@ -13,6 +13,8 @@ import java.util.List;
import javax.swing.JRadioButton; import javax.swing.JRadioButton;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import com.google.common.collect.ImmutableList;
import forge.GuiBase; import forge.GuiBase;
import forge.Singletons; import forge.Singletons;
import forge.UiCommand; import forge.UiCommand;
@@ -139,7 +141,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
final boolean shouldQuit = FOptionPane.showOptionDialog("If you leave now, this tournament will be forever gone." final boolean shouldQuit = FOptionPane.showOptionDialog("If you leave now, this tournament will be forever gone."
+ "\nYou will keep the cards you drafted, but will receive no other prizes." + "\nYou will keep the cards you drafted, but will receive no other prizes."
+ "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), new String[] { "Yes", "No" }, 1) == 0; + "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), ImmutableList.of("Yes", "No"), 1) == 0;
if (!shouldQuit) { if (!shouldQuit) {
return; return;
} }
@@ -149,7 +151,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
if (draft.playerHasMatchesLeft()) { if (draft.playerHasMatchesLeft()) {
final boolean shouldQuit = FOptionPane.showOptionDialog("You have matches left to play!\nLeaving the tournament early will forfeit your potential future winnings." final boolean shouldQuit = FOptionPane.showOptionDialog("You have matches left to play!\nLeaving the tournament early will forfeit your potential future winnings."
+ "\nYou will still receive winnings as if you conceded your next match and you will keep the cards you drafted." + "\nYou will still receive winnings as if you conceded your next match and you will keep the cards you drafted."
+ "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), new String[] { "Yes", "No" }, 1) == 0; + "\n\nWould you still like to quit the tournament?", "Really Quit?", FSkin.getImage(FSkinProp.ICO_WARNING).scale(2.0), ImmutableList.of("Yes", "No"), 1) == 0;
if (!shouldQuit) { if (!shouldQuit) {
return; return;
} }
@@ -242,7 +244,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
} }
final boolean saveDraft = FOptionPane.showOptionDialog("Would you like to save this draft to the regular draft mode?", "Save Draft?", FSkin.getImage(FSkinProp.ICO_QUESTION).scale(2.0), new String[] { "Yes", "No" }, 0) == 0; final boolean saveDraft = FOptionPane.showOptionDialog("Would you like to save this draft to the regular draft mode?", "Save Draft?", FSkin.getImage(FSkinProp.ICO_QUESTION).scale(2.0), ImmutableList.of("Yes", "No"), 0) == 0;
if (saveDraft) { if (saveDraft) {
draft.saveToRegularDraft(); draft.saveToRegularDraft();
@@ -525,7 +527,7 @@ public enum CSubmenuQuestDraft implements ICDoc {
return; return;
} }
final boolean okayToEnter = FOptionPane.showOptionDialog("This tournament costs " + draftEvent.getEntryFee() + " credits to enter.\nAre you sure you wish to enter?", "Enter Draft Tournament?", FSkin.getImage(FSkinProp.ICO_QUEST_GOLD), new String[] { "Yes", "No" }, 1) == 0; final boolean okayToEnter = FOptionPane.showOptionDialog("This tournament costs " + draftEvent.getEntryFee() + " credits to enter.\nAre you sure you wish to enter?", "Enter Draft Tournament?", FSkin.getImage(FSkinProp.ICO_QUEST_GOLD), ImmutableList.of("Yes", "No"), 1) == 0;
if (!okayToEnter) { if (!okayToEnter) {
return; return;

View File

@@ -326,8 +326,11 @@ public final class CMatchUI
} }
public void setCard(final CardView c, final boolean isInAltState) { public void setCard(final CardView c, final boolean isInAltState) {
FThreads.assertExecutedByEdt(true); FThreads.invokeInEdtNowOrLater(new Runnable() {
cDetailPicture.showCard(c, isInAltState); @Override public void run() {
cDetailPicture.showCard(c, isInAltState);
}
});
} }
public void setCard(final InventoryItem item) { public void setCard(final InventoryItem item) {
@@ -819,17 +822,17 @@ public final class CMatchUI
} }
@Override @Override
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return FOptionPane.showOptionDialog(message, title, icon == null ? null : FSkin.getImage(icon), options, defaultOption); return FOptionPane.showOptionDialog(message, title, icon == null ? null : FSkin.getImage(icon), options, defaultOption);
} }
@Override @Override
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return FOptionPane.showInputDialog(message, title, icon == null ? null : FSkin.getImage(icon), initialInput, inputOptions); return FOptionPane.showInputDialog(message, title, icon == null ? null : FSkin.getImage(icon), initialInput, inputOptions);
} }
@Override @Override
public <T> List<T> getChoices(final String message, final int min, final int max, final Collection<T> choices, final T selected, final Function<T, String> display) { public <T> List<T> getChoices(final String message, final int min, final int max, final List<T> choices, final T selected, final Function<T, String> display) {
/*if ((choices != null && !choices.isEmpty() && choices.iterator().next() instanceof GameObject) || selected instanceof GameObject) { /*if ((choices != null && !choices.isEmpty() && choices.iterator().next() instanceof GameObject) || selected instanceof GameObject) {
System.err.println("Warning: GameObject passed to GUI! Printing stack trace."); System.err.println("Warning: GameObject passed to GUI! Printing stack trace.");
Thread.dumpStack(); Thread.dumpStack();
@@ -854,7 +857,7 @@ public final class CMatchUI
} }
@Override @Override
public GameEntityView chooseSingleEntityForEffect(final String title, final Collection<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) { public GameEntityView chooseSingleEntityForEffect(final String title, final List<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) {
if (delayedReveal != null) { if (delayedReveal != null) {
reveal(delayedReveal.getMessagePrefix(), delayedReveal.getCards()); //TODO: Merge this into search dialog reveal(delayedReveal.getMessagePrefix(), delayedReveal.getCards()); //TODO: Merge this into search dialog
} }
@@ -984,13 +987,13 @@ public final class CMatchUI
} }
@Override @Override
public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options) { public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final List<String> options) {
return GuiDialog.confirm(c, question, defaultIsYes, options, this); return GuiDialog.confirm(c, question, defaultIsYes, options, this);
} }
@Override @Override
public boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) { public boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) {
final String[] options = {yesButtonText, noButtonText}; final List<String> options = ImmutableList.of(yesButtonText, noButtonText);
final int reply = SOptionPane.showOptionDialog(message, title, SOptionPane.QUESTION_ICON, options, defaultYes ? 0 : 1); final int reply = SOptionPane.showOptionDialog(message, title, SOptionPane.QUESTION_ICON, options, defaultYes ? 0 : 1);
return reply == 0; return reply == 0;
} }

View File

@@ -19,6 +19,8 @@ package forge.screens.match;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import com.google.common.collect.ImmutableList;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.game.GameView; import forge.game.GameView;
import forge.match.NextGameDecision; import forge.match.NextGameDecision;
@@ -104,7 +106,7 @@ public class QuestDraftWinLose extends ControlWinLose {
@Override @Override
public void actionPerformed(final ActionEvent e) { public void actionPerformed(final ActionEvent e) {
if (warningString == null || if (warningString == null ||
FOptionPane.showOptionDialog(warningString, warningCaption, FSkin.getImage(FSkinProp.ICO_WARNING).scale(2), new String[] { "Yes", "No" }, 1) == 0) { FOptionPane.showOptionDialog(warningString, warningCaption, FSkin.getImage(FSkinProp.ICO_WARNING).scale(2), ImmutableList.of("Yes", "No"), 1) == 0) {
matchUI.getGameController().nextGameDecision(NextGameDecision.QUIT); matchUI.getGameController().nextGameDecision(NextGameDecision.QUIT);
QuestDraftUtils.matchInProgress = false; QuestDraftUtils.matchInProgress = false;
QuestDraftUtils.continueMatches(matchUI); QuestDraftUtils.continueMatches(matchUI);

View File

@@ -11,6 +11,8 @@ import javax.swing.event.DocumentListener;
import javax.swing.text.Style; import javax.swing.text.Style;
import javax.swing.text.StyledDocument; import javax.swing.text.StyledDocument;
import com.google.common.collect.ImmutableList;
import forge.Singletons; import forge.Singletons;
import forge.card.CardDb; import forge.card.CardDb;
import forge.card.CardRules; import forge.card.CardRules;
@@ -117,6 +119,7 @@ public enum CCardScript implements ICDoc {
return (currentScriptInfo != null && isTextDirty); return (currentScriptInfo != null && isTextDirty);
} }
private static final ImmutableList<String> switchAwayOptions = ImmutableList.of("Save", "Don't Save", "Cancel");
public boolean canSwitchAway(final boolean isCardChanging) { public boolean canSwitchAway(final boolean isCardChanging) {
if (switchInProgress) { return false; } if (switchInProgress) { return false; }
if (!hasChanges()) { return true; } if (!hasChanges()) { return true; }
@@ -124,10 +127,10 @@ public enum CCardScript implements ICDoc {
switchInProgress = true; switchInProgress = true;
Singletons.getControl().ensureScreenActive(FScreen.WORKSHOP_SCREEN); //ensure Workshop is active before showing dialog Singletons.getControl().ensureScreenActive(FScreen.WORKSHOP_SCREEN); //ensure Workshop is active before showing dialog
final int choice = FOptionPane.showOptionDialog( final int choice = FOptionPane.showOptionDialog(
"Save changes to " + currentCard + "?", String.format("Save changes to %s?", currentCard),
"Save Changes?", "Save Changes?",
FOptionPane.QUESTION_ICON, FOptionPane.QUESTION_ICON,
new String[] {"Save", "Don't Save", "Cancel"}); switchAwayOptions);
switchInProgress = false; switchInProgress = false;
if (choice == -1 || choice == 2) { return false; } if (choice == -1 || choice == 2) { return false; }

View File

@@ -5,6 +5,7 @@ import java.awt.FontMetrics;
import java.awt.Graphics; import java.awt.Graphics;
import java.awt.Graphics2D; import java.awt.Graphics2D;
import java.awt.LayoutManager; import java.awt.LayoutManager;
import java.util.List;
import java.util.Vector; import java.util.Vector;
import javax.swing.ComboBoxModel; import javax.swing.ComboBoxModel;
@@ -51,6 +52,9 @@ public class FComboBox<E> extends SkinnedComboBox<E> implements IComboBox<E> {
super(items); super(items);
initialize(); initialize();
} }
public FComboBox(final List<E> items) {
this(new Vector<>(items));
}
public FComboBox(final Vector<E> items) { public FComboBox(final Vector<E> items) {
super(items); super(items);
initialize(); initialize();

View File

@@ -7,6 +7,7 @@ import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter; import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.util.List;
import javax.swing.JComponent; import javax.swing.JComponent;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
@@ -14,6 +15,8 @@ import javax.swing.SwingConstants;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import javax.swing.text.StyleConstants; import javax.swing.text.StyleConstants;
import com.google.common.collect.ImmutableList;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
import forge.toolbox.FSkin.SkinImage; import forge.toolbox.FSkin.SkinImage;
import forge.view.FDialog; import forge.view.FDialog;
@@ -46,7 +49,7 @@ public class FOptionPane extends FDialog {
} }
public static void showMessageDialog(final String message, final String title, final SkinImage icon) { public static void showMessageDialog(final String message, final String title, final SkinImage icon) {
showOptionDialog(message, title, icon, new String[] {"OK"}, 0); showOptionDialog(message, title, icon, ImmutableList.of("OK"), 0);
} }
public static boolean showConfirmDialog(final String message) { public static boolean showConfirmDialog(final String message) {
@@ -66,16 +69,16 @@ public class FOptionPane extends FDialog {
} }
public static boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) { public static boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) {
final String[] options = {yesButtonText, noButtonText}; final List<String> options = ImmutableList.of(yesButtonText, noButtonText);
final int reply = FOptionPane.showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1); final int reply = FOptionPane.showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1);
return (reply == 0); return (reply == 0);
} }
public static int showOptionDialog(final String message, final String title, final SkinImage icon, final String[] options) { public static int showOptionDialog(final String message, final String title, final SkinImage icon, final List<String> options) {
return showOptionDialog(message, title, icon, options, 0); return showOptionDialog(message, title, icon, options, 0);
} }
public static int showOptionDialog(final String message, final String title, final SkinImage icon, final String[] options, final int defaultOption) { public static int showOptionDialog(final String message, final String title, final SkinImage icon, final List<String> options, final int defaultOption) {
final FOptionPane optionPane = new FOptionPane(message, title, icon, null, options, defaultOption); final FOptionPane optionPane = new FOptionPane(message, title, icon, null, options, defaultOption);
optionPane.setVisible(true); optionPane.setVisible(true);
final int dialogResult = optionPane.result; final int dialogResult = optionPane.result;
@@ -96,21 +99,20 @@ public class FOptionPane extends FDialog {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T showInputDialog(final String message, final String title, final SkinImage icon, final T initialInput, final T[] inputOptions) { public static <T> T showInputDialog(final String message, final String title, final SkinImage icon, final String initialInput, final List<T> inputOptions) {
final JComponent inputField; final JComponent inputField;
FTextField txtInput = null; FTextField txtInput = null;
FComboBox<T> cbInput = null; FComboBox<T> cbInput = null;
if (inputOptions == null) { if (inputOptions == null) {
txtInput = new FTextField.Builder().text(initialInput.toString()).build(); txtInput = new FTextField.Builder().text(initialInput.toString()).build();
inputField = txtInput; inputField = txtInput;
} } else {
else {
cbInput = new FComboBox<T>(inputOptions); cbInput = new FComboBox<T>(inputOptions);
cbInput.setSelectedItem(initialInput); cbInput.setSelectedItem(initialInput);
inputField = cbInput; inputField = cbInput;
} }
final FOptionPane optionPane = new FOptionPane(message, title, icon, inputField, new String[] {"OK", "Cancel"}, -1); final FOptionPane optionPane = new FOptionPane(message, title, icon, inputField, ImmutableList.of("OK", "Cancel"), -1);
optionPane.setDefaultFocus(inputField); optionPane.setDefaultFocus(inputField);
inputField.addKeyListener(new KeyAdapter() { //hook so pressing Enter on field accepts dialog inputField.addKeyListener(new KeyAdapter() { //hook so pressing Enter on field accepts dialog
@Override @Override
@@ -136,7 +138,7 @@ public class FOptionPane extends FDialog {
private int result = -1; //default result to -1, indicating dialog closed without choosing option private int result = -1; //default result to -1, indicating dialog closed without choosing option
private final FButton[] buttons; private final FButton[] buttons;
public FOptionPane(final String message, final String title, final SkinImage icon, final Component comp, final String[] options, final int defaultOption) { public FOptionPane(final String message, final String title, final SkinImage icon, final Component comp, final List<String> options, final int defaultOption) {
this.setTitle(title); this.setTitle(title);
final int padding = 10; final int padding = 10;
@@ -184,18 +186,19 @@ public class FOptionPane extends FDialog {
} }
//determine size of buttons //determine size of buttons
final int optionCount = options.length; final int optionCount = options.size();
final FButton btnMeasure = new FButton(); //use blank button to aid in measurement final FButton btnMeasure = new FButton(); //use blank button to aid in measurement
final FontMetrics metrics = JOptionPane.getRootFrame().getGraphics().getFontMetrics(btnMeasure.getFont()); final FontMetrics metrics = JOptionPane.getRootFrame().getGraphics().getFontMetrics(btnMeasure.getFont());
int maxTextWidth = 0; int maxTextWidth = 0;
buttons = new FButton[optionCount]; buttons = new FButton[optionCount];
for (int i = 0; i < optionCount; i++) { for (int i = 0; i < optionCount; i++) {
final int textWidth = metrics.stringWidth(options[i]); final String option = options.get(i);
final int textWidth = metrics.stringWidth(option);
if (textWidth > maxTextWidth) { if (textWidth > maxTextWidth) {
maxTextWidth = textWidth; maxTextWidth = textWidth;
} }
buttons[i] = new FButton(options[i]); buttons[i] = new FButton(option);
} }
this.pack(); //resize dialog to fit component and title to help determine button layout this.pack(); //resize dialog to fit component and title to help determine button layout

View File

@@ -238,7 +238,7 @@ public class PlayerControllerForTests extends PlayerController {
} }
@Override @Override
public void reveal(Collection<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix) { public void reveal(List<CardView> cards, ZoneType zone, PlayerView owner, String messagePrefix) {
//nothing needs to be done here //nothing needs to be done here
} }
@@ -499,7 +499,7 @@ public class PlayerControllerForTests extends PlayerController {
} }
@Override @Override
public CounterType chooseCounterType(Collection<CounterType> options, SpellAbility sa, String prompt) { public CounterType chooseCounterType(List<CounterType> options, SpellAbility sa, String prompt) {
return Iterables.getFirst(options, CounterType.P1P1); return Iterables.getFirst(options, CounterType.P1P1);
} }

View File

@@ -141,7 +141,7 @@ public class GuiMobile implements IGuiBase {
} }
@Override @Override
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return new WaitCallback<Integer>() { return new WaitCallback<Integer>() {
@Override @Override
public void run() { public void run() {
@@ -151,7 +151,7 @@ public class GuiMobile implements IGuiBase {
} }
@Override @Override
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return new WaitCallback<String>() { return new WaitCallback<String>() {
@Override @Override
public void run() { public void run() {

View File

@@ -3,11 +3,13 @@ package forge.assets;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Gdx;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.Forge; import forge.Forge;
@@ -20,6 +22,9 @@ import forge.util.gui.SOptionPane;
public class AssetsDownloader { public class AssetsDownloader {
public static final boolean SHARE_DESKTOP_ASSETS = true; //change to false to test downloading separate assets for desktop version public static final boolean SHARE_DESKTOP_ASSETS = true; //change to false to test downloading separate assets for desktop version
private final static ImmutableList<String> downloadIgnoreExit = ImmutableList.of("Download", "Ignore", "Exit");
private final static ImmutableList<String> downloadExit = ImmutableList.of("Download", "Exit");
//if not sharing desktop assets, check whether assets are up to date //if not sharing desktop assets, check whether assets are up to date
public static void checkForUpdates(final SplashScreen splashScreen) { public static void checkForUpdates(final SplashScreen splashScreen) {
if (Gdx.app.getType() == ApplicationType.Desktop && SHARE_DESKTOP_ASSETS) { return; } if (Gdx.app.getType() == ApplicationType.Desktop && SHARE_DESKTOP_ASSETS) { return; }
@@ -105,16 +110,16 @@ public class AssetsDownloader {
else { else {
message += "so it's highly recommended that you connect to wifi first."; message += "so it's highly recommended that you connect to wifi first.";
} }
String[] options; final List<String> options;
message += "\n\n"; message += "\n\n";
if (canIgnoreDownload) { if (canIgnoreDownload) {
message += "If you choose to ignore this download, you may miss out on card fixes or experience other problems."; message += "If you choose to ignore this download, you may miss out on card fixes or experience other problems.";
options = new String[] { "Download", "Ignore", "Exit" }; options = downloadIgnoreExit;
} } else {
else {
message += "This download is mandatory to start the app since you haven't previously downloaded these files."; message += "This download is mandatory to start the app since you haven't previously downloaded these files.";
options = new String[] { "Download", "Exit" }; options = downloadExit;
} }
switch (SOptionPane.showOptionDialog(message, "", null, options)) { switch (SOptionPane.showOptionDialog(message, "", null, options)) {
case 1: case 1:
if (!canIgnoreDownload) { if (!canIgnoreDownload) {

View File

@@ -4,6 +4,8 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import com.google.common.collect.ImmutableList;
import forge.Graphics; import forge.Graphics;
import forge.assets.FImage; import forge.assets.FImage;
import forge.assets.FSkinFont; import forge.assets.FSkinFont;
@@ -30,7 +32,7 @@ public class GameEntityPicker extends TabPageScreen<GameEntityPicker> {
setHeight(FOptionPane.getMaxDisplayObjHeight()); setHeight(FOptionPane.getMaxDisplayObjHeight());
optionPane = new FOptionPane(null, title, null, this, optionPane = new FOptionPane(null, title, null, this,
isOptional ? new String[] { "OK", "Cancel" } : new String[] { "OK" }, 0, new Callback<Integer>() { isOptional ? ImmutableList.of("OK", "Cancel") : ImmutableList.of("OK"), 0, new Callback<Integer>() {
@Override @Override
public void run(Integer result) { public void run(Integer result) {
if (result == 0) { if (result == 0) {

View File

@@ -43,6 +43,7 @@ import forge.util.storage.IStorage;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@@ -97,7 +98,7 @@ public class FDeckChooser extends FScreen {
container.add(deckChooser.lstDecks); container.add(deckChooser.lstDecks);
container.setHeight(FOptionPane.getMaxDisplayObjHeight()); container.setHeight(FOptionPane.getMaxDisplayObjHeight());
deckChooser.optionPane = new FOptionPane(null, title, null, container, new String[] { "OK", "Cancel" }, 0, new Callback<Integer>() { deckChooser.optionPane = new FOptionPane(null, title, null, container, ImmutableList.of("OK", "Cancel"), 0, new Callback<Integer>() {
@Override @Override
public void run(Integer result) { public void run(Integer result) {
if (result == 0) { if (result == 0) {

View File

@@ -12,6 +12,7 @@ import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector2;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.base.Supplier; import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import forge.Forge; import forge.Forge;
import forge.Graphics; import forge.Graphics;
@@ -479,6 +480,8 @@ public class FDeckEditor extends TabPageScreen<FDeckEditor> {
} }
} }
private final static ImmutableList<String> onCloseOptions = ImmutableList.of("Save", "Don't Save", "Cancel");
@Override @Override
public void onClose(final Callback<Boolean> canCloseCallback) { public void onClose(final Callback<Boolean> canCloseCallback) {
if (editorType.getController().isSaved() || canCloseCallback == null) { if (editorType.getController().isSaved() || canCloseCallback == null) {
@@ -486,7 +489,7 @@ public class FDeckEditor extends TabPageScreen<FDeckEditor> {
return; return;
} }
FOptionPane.showOptionDialog("Save changes to current deck?", "", FOptionPane.showOptionDialog("Save changes to current deck?", "",
FOptionPane.QUESTION_ICON, new String[] {"Save", "Don't Save", "Cancel"}, new Callback<Integer>() { FOptionPane.QUESTION_ICON, onCloseOptions, new Callback<Integer>() {
@Override @Override
public void run(Integer result) { public void run(Integer result) {
if (result == 0) { if (result == 0) {

View File

@@ -19,6 +19,8 @@ package forge.deck;
import java.util.List; import java.util.List;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.Forge; import forge.Forge;
import forge.Graphics; import forge.Graphics;
@@ -48,6 +50,8 @@ public class FDeckImportDialog extends FDialog {
private final boolean showOptions; private final boolean showOptions;
private final DeckImportController controller; private final DeckImportController controller;
private final static ImmutableList<String> importOrCancel = ImmutableList.of("Import", "Cancel");
public FDeckImportDialog(final boolean replacingDeck, final Callback<Deck> callback0) { public FDeckImportDialog(final boolean replacingDeck, final Callback<Deck> callback0) {
super("Import from Clipboard", 2); super("Import from Clipboard", 2);
@@ -74,7 +78,7 @@ public class FDeckImportDialog extends FDialog {
} }
} }
if (sb.length() > 0) { if (sb.length() > 0) {
if (SOptionPane.showOptionDialog("The following cards cannot be imported due to misspelling, set restrictions, or not being in Forge yet:\n\n" + sb.toString(), "Import remaining cards?", SOptionPane.INFORMATION_ICON, new String[] { "Import", "Cancel" }) == 1) { if (SOptionPane.showOptionDialog("The following cards cannot be imported due to misspelling, set restrictions, or not being in Forge yet:\n\n" + sb.toString(), "Import remaining cards?", SOptionPane.INFORMATION_ICON, importOrCancel) == 1) {
return; return;
} }
} }

View File

@@ -5,6 +5,7 @@ import java.util.*;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.Forge; import forge.Forge;
@@ -859,12 +860,12 @@ public class ConstructedScreen extends LaunchScreen {
return usedAvatars; return usedAvatars;
} }
private static final ImmutableList<String> genderOptions = ImmutableList.of("Male", "Female", "Any");
private static final ImmutableList<String> typeOptions = ImmutableList.of("Fantasy", "Generic", "Any");
private final void getNewName(final Callback<String> callback) { private final void getNewName(final Callback<String> callback) {
final String title = "Get new random name"; final String title = "Get new random name";
final String message = "What type of name do you want to generate?"; final String message = "What type of name do you want to generate?";
final FSkinImage icon = FOptionPane.QUESTION_ICON; final FSkinImage icon = FOptionPane.QUESTION_ICON;
final String[] genderOptions = new String[]{ "Male", "Female", "Any" };
final String[] typeOptions = new String[]{ "Fantasy", "Generic", "Any" };
FOptionPane.showOptionDialog(message, title, icon, genderOptions, 2, new Callback<Integer>() { FOptionPane.showOptionDialog(message, title, icon, genderOptions, 2, new Callback<Integer>() {
@Override @Override
@@ -882,7 +883,7 @@ public class ConstructedScreen extends LaunchScreen {
return; return;
} }
generateRandomName(genderOptions[genderIndex], typeOptions[typeIndex], getPlayerNames(), title, callback); generateRandomName(genderOptions.get(genderIndex), typeOptions.get(typeIndex), getPlayerNames(), title, callback);
} }
}); });
} }

View File

@@ -10,6 +10,7 @@ import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import forge.Forge; import forge.Forge;
@@ -82,7 +83,7 @@ public class MatchController extends AbstractGuiGame {
} }
public static FImage getPlayerAvatar(final PlayerView p) { public static FImage getPlayerAvatar(final PlayerView p) {
String lp = p.getLobbyPlayerName(); final String lp = p.getLobbyPlayerName();
FImage avatar = avatarImages.get(lp); FImage avatar = avatarImages.get(lp);
if (avatar == null) { if (avatar == null) {
if (StringUtils.isEmpty(p.getAvatarCardImageKey())) { if (StringUtils.isEmpty(p.getAvatarCardImageKey())) {
@@ -96,9 +97,9 @@ public class MatchController extends AbstractGuiGame {
} }
@Override @Override
public void refreshCardDetails(Iterable<CardView> cards) { public void refreshCardDetails(final Iterable<CardView> cards) {
//ensure cards appear in the correct row of the field //ensure cards appear in the correct row of the field
for (VPlayerPanel pnl : view.getPlayerPanels().values()) { for (final VPlayerPanel pnl : view.getPlayerPanels().values()) {
pnl.getField().update(); pnl.getField().update();
} }
} }
@@ -123,12 +124,12 @@ public class MatchController extends AbstractGuiGame {
//add special object that pauses game if screen touched //add special object that pauses game if screen touched
view.add(new FDisplayObject() { view.add(new FDisplayObject() {
@Override @Override
public void draw(Graphics g) { public void draw(final Graphics g) {
//don't draw anything //don't draw anything
} }
@Override @Override
public void buildTouchListeners(float screenX, float screenY, ArrayList<FDisplayObject> listeners) { public void buildTouchListeners(final float screenX, final float screenY, final ArrayList<FDisplayObject> listeners) {
if (screenY < view.getHeight() - VPrompt.HEIGHT) { if (screenY < view.getHeight() - VPrompt.HEIGHT) {
hostedMatch.pause(); hostedMatch.pause();
} }
@@ -146,6 +147,7 @@ public class MatchController extends AbstractGuiGame {
view.getPrompt(player).setMessage(message); view.getPrompt(player).setMessage(message);
} }
@Override
public void updateButtons(final PlayerView owner, final String label1, final String label2, final boolean enable1, final boolean enable2, final boolean focus1) { public void updateButtons(final PlayerView owner, final String label1, final String label2, final boolean enable1, final boolean enable2, final boolean focus1) {
final VPrompt prompt = view.getPrompt(owner); final VPrompt prompt = view.getPrompt(owner);
final FButton btn1 = prompt.getBtnOk(), btn2 = prompt.getBtnCancel(); final FButton btn1 = prompt.getBtnOk(), btn2 = prompt.getBtnCancel();
@@ -194,7 +196,7 @@ public class MatchController extends AbstractGuiGame {
@Override @Override
public void disableOverlay() { public void disableOverlay() {
} }
@Override @Override
public void enableOverlay() { public void enableOverlay() {
} }
@@ -233,15 +235,15 @@ public class MatchController extends AbstractGuiGame {
@Override @Override
public Object showManaPool(final PlayerView player) { public Object showManaPool(final PlayerView player) {
VPlayerPanel playerPanel = view.getPlayerPanel(player); final VPlayerPanel playerPanel = view.getPlayerPanel(player);
InfoTab oldSelectedTab = playerPanel.getSelectedTab(); final InfoTab oldSelectedTab = playerPanel.getSelectedTab();
playerPanel.setSelectedTab(playerPanel.getManaPoolTab()); playerPanel.setSelectedTab(playerPanel.getManaPoolTab());
return oldSelectedTab; return oldSelectedTab;
} }
@Override @Override
public void hideManaPool(final PlayerView player, final Object zoneToRestore) { public void hideManaPool(final PlayerView player, final Object zoneToRestore) {
VPlayerPanel playerPanel = view.getPlayerPanel(player); final VPlayerPanel playerPanel = view.getPlayerPanel(player);
if (zoneToRestore == playerPanel.getManaPoolTab()) { if (zoneToRestore == playerPanel.getManaPoolTab()) {
return; //if mana pool was selected previously, we don't need to switch back to anything return; //if mana pool was selected previously, we don't need to switch back to anything
} }
@@ -252,38 +254,37 @@ public class MatchController extends AbstractGuiGame {
} }
@Override @Override
public boolean openZones(Collection<ZoneType> zones, Map<PlayerView, Object> players) { public boolean openZones(final Collection<ZoneType> zones, final Map<PlayerView, Object> players) {
if (zones.size() == 1) { if (zones.size() == 1) {
ZoneType zoneType = zones.iterator().next(); final ZoneType zoneType = zones.iterator().next();
switch (zoneType) { switch (zoneType) {
case Battlefield: case Battlefield:
case Command: case Command:
players.clear(); //clear since no zones need to be restored players.clear(); //clear since no zones need to be restored
return true; //Battlefield is always open return true; //Battlefield is always open
default: default:
//open zone tab for given zone if needed //open zone tab for given zone if needed
boolean result = true; boolean result = true;
for (PlayerView player : players.keySet()) { for (final PlayerView player : players.keySet()) {
VPlayerPanel playerPanel = view.getPlayerPanel(player); final VPlayerPanel playerPanel = view.getPlayerPanel(player);
players.put(player, playerPanel.getSelectedTab()); //backup selected tab before changing it players.put(player, playerPanel.getSelectedTab()); //backup selected tab before changing it
InfoTab zoneTab = playerPanel.getZoneTab(zoneType); final InfoTab zoneTab = playerPanel.getZoneTab(zoneType);
if (zoneTab == null) { if (zoneTab == null) {
result = false; result = false;
} else {
playerPanel.setSelectedTab(zoneTab);
}
} }
else { return result;
playerPanel.setSelectedTab(zoneTab);
}
}
return result;
} }
} }
return false; return false;
} }
@Override @Override
public void restoreOldZones(Map<PlayerView, Object> playersToRestoreZonesFor) { public void restoreOldZones(final Map<PlayerView, Object> playersToRestoreZonesFor) {
for (Entry<PlayerView, Object> player : playersToRestoreZonesFor.entrySet()) { for (final Entry<PlayerView, Object> player : playersToRestoreZonesFor.entrySet()) {
VPlayerPanel playerPanel = view.getPlayerPanel(player.getKey()); final VPlayerPanel playerPanel = view.getPlayerPanel(player.getKey());
playerPanel.setSelectedTab((InfoTab)player.getValue()); playerPanel.setSelectedTab((InfoTab)player.getValue());
} }
} }
@@ -293,33 +294,33 @@ public class MatchController extends AbstractGuiGame {
return new WaitCallback<Map<CardView, Integer>>() { return new WaitCallback<Map<CardView, Integer>>() {
@Override @Override
public void run() { public void run() {
VAssignDamage v = new VAssignDamage(attacker, blockers, damage, defender, overrideOrder, this); final VAssignDamage v = new VAssignDamage(attacker, blockers, damage, defender, overrideOrder, this);
v.show(); v.show();
} }
}.invokeAndWait(); }.invokeAndWait();
} }
@Override @Override
public void updateManaPool(Iterable<PlayerView> manaPoolUpdate) { public void updateManaPool(final Iterable<PlayerView> manaPoolUpdate) {
for (PlayerView p : manaPoolUpdate) { for (final PlayerView p : manaPoolUpdate) {
view.getPlayerPanel(p).updateManaPool(); view.getPlayerPanel(p).updateManaPool();
} }
} }
@Override @Override
public void updateLives(Iterable<PlayerView> livesUpdate) { public void updateLives(final Iterable<PlayerView> livesUpdate) {
for (PlayerView p : livesUpdate) { for (final PlayerView p : livesUpdate) {
view.getPlayerPanel(p).updateLife(); view.getPlayerPanel(p).updateLife();
} }
} }
@Override @Override
public void updateZones(Iterable<PlayerZoneUpdate> zonesToUpdate) { public void updateZones(final Iterable<PlayerZoneUpdate> zonesToUpdate) {
view.updateZones(zonesToUpdate); view.updateZones(zonesToUpdate);
} }
@Override @Override
public void updateCards(Iterable<CardView> cards) { public void updateCards(final Iterable<CardView> cards) {
for (final CardView card : cards) { for (final CardView card : cards) {
view.updateSingleCard(card); view.updateSingleCard(card);
} }
@@ -332,9 +333,9 @@ public class MatchController extends AbstractGuiGame {
} }
private static void actuateMatchPreferences() { private static void actuateMatchPreferences() {
ForgePreferences prefs = FModel.getPreferences(); final ForgePreferences prefs = FModel.getPreferences();
VPhaseIndicator fvAi = view.getTopPlayerPanel().getPhaseIndicator(); final VPhaseIndicator fvAi = view.getTopPlayerPanel().getPhaseIndicator();
fvAi.getLabel(PhaseType.UPKEEP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_UPKEEP)); fvAi.getLabel(PhaseType.UPKEEP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_UPKEEP));
fvAi.getLabel(PhaseType.DRAW).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_DRAW)); fvAi.getLabel(PhaseType.DRAW).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_DRAW));
fvAi.getLabel(PhaseType.MAIN1).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_MAIN1)); fvAi.getLabel(PhaseType.MAIN1).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_MAIN1));
@@ -348,7 +349,7 @@ public class MatchController extends AbstractGuiGame {
fvAi.getLabel(PhaseType.END_OF_TURN).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_EOT)); fvAi.getLabel(PhaseType.END_OF_TURN).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_EOT));
fvAi.getLabel(PhaseType.CLEANUP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_CLEANUP)); fvAi.getLabel(PhaseType.CLEANUP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_AI_CLEANUP));
VPhaseIndicator fvHuman = view.getBottomPlayerPanel().getPhaseIndicator(); final VPhaseIndicator fvHuman = view.getBottomPlayerPanel().getPhaseIndicator();
fvHuman.getLabel(PhaseType.UPKEEP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_UPKEEP)); fvHuman.getLabel(PhaseType.UPKEEP).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_UPKEEP));
fvHuman.getLabel(PhaseType.DRAW).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_DRAW)); fvHuman.getLabel(PhaseType.DRAW).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_DRAW));
fvHuman.getLabel(PhaseType.MAIN1).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_MAIN1)); fvHuman.getLabel(PhaseType.MAIN1).setStopAtPhase(prefs.getPrefBoolean(FPref.PHASE_HUMAN_MAIN1));
@@ -364,9 +365,9 @@ public class MatchController extends AbstractGuiGame {
} }
public static void writeMatchPreferences() { public static void writeMatchPreferences() {
ForgePreferences prefs = FModel.getPreferences(); final ForgePreferences prefs = FModel.getPreferences();
VPhaseIndicator fvAi = view.getTopPlayerPanel().getPhaseIndicator(); final VPhaseIndicator fvAi = view.getTopPlayerPanel().getPhaseIndicator();
prefs.setPref(FPref.PHASE_AI_UPKEEP, String.valueOf(fvAi.getLabel(PhaseType.UPKEEP).getStopAtPhase())); prefs.setPref(FPref.PHASE_AI_UPKEEP, String.valueOf(fvAi.getLabel(PhaseType.UPKEEP).getStopAtPhase()));
prefs.setPref(FPref.PHASE_AI_DRAW, String.valueOf(fvAi.getLabel(PhaseType.DRAW).getStopAtPhase())); prefs.setPref(FPref.PHASE_AI_DRAW, String.valueOf(fvAi.getLabel(PhaseType.DRAW).getStopAtPhase()));
prefs.setPref(FPref.PHASE_AI_MAIN1, String.valueOf(fvAi.getLabel(PhaseType.MAIN1).getStopAtPhase())); prefs.setPref(FPref.PHASE_AI_MAIN1, String.valueOf(fvAi.getLabel(PhaseType.MAIN1).getStopAtPhase()));
@@ -380,7 +381,7 @@ public class MatchController extends AbstractGuiGame {
prefs.setPref(FPref.PHASE_AI_EOT, String.valueOf(fvAi.getLabel(PhaseType.END_OF_TURN).getStopAtPhase())); prefs.setPref(FPref.PHASE_AI_EOT, String.valueOf(fvAi.getLabel(PhaseType.END_OF_TURN).getStopAtPhase()));
prefs.setPref(FPref.PHASE_AI_CLEANUP, String.valueOf(fvAi.getLabel(PhaseType.CLEANUP).getStopAtPhase())); prefs.setPref(FPref.PHASE_AI_CLEANUP, String.valueOf(fvAi.getLabel(PhaseType.CLEANUP).getStopAtPhase()));
VPhaseIndicator fvHuman = view.getBottomPlayerPanel().getPhaseIndicator(); final VPhaseIndicator fvHuman = view.getBottomPlayerPanel().getPhaseIndicator();
prefs.setPref(FPref.PHASE_HUMAN_UPKEEP, String.valueOf(fvHuman.getLabel(PhaseType.UPKEEP).getStopAtPhase())); prefs.setPref(FPref.PHASE_HUMAN_UPKEEP, String.valueOf(fvHuman.getLabel(PhaseType.UPKEEP).getStopAtPhase()));
prefs.setPref(FPref.PHASE_HUMAN_DRAW, String.valueOf(fvHuman.getLabel(PhaseType.DRAW).getStopAtPhase())); prefs.setPref(FPref.PHASE_HUMAN_DRAW, String.valueOf(fvHuman.getLabel(PhaseType.DRAW).getStopAtPhase()));
prefs.setPref(FPref.PHASE_HUMAN_MAIN1, String.valueOf(fvHuman.getLabel(PhaseType.MAIN1).getStopAtPhase())); prefs.setPref(FPref.PHASE_HUMAN_MAIN1, String.valueOf(fvHuman.getLabel(PhaseType.MAIN1).getStopAtPhase()));
@@ -413,25 +414,28 @@ public class MatchController extends AbstractGuiGame {
} }
@Override @Override
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return SOptionPane.showOptionDialog(message, title, icon, options, defaultOption); return SOptionPane.showOptionDialog(message, title, icon, options, defaultOption);
} }
@Override @Override
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return SOptionPane.showInputDialog(message, title, icon, initialInput, inputOptions); return SOptionPane.showInputDialog(message, title, icon, initialInput, inputOptions);
} }
@Override @Override
public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, String[] options) { public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final List<String> options) {
final List<String> optionsToUse;
if (options == null) { if (options == null) {
options = new String[] { "Yes", "No" }; optionsToUse = ImmutableList.of("Yes", "No");
} else {
optionsToUse = options;
} }
return FOptionPane.showCardOptionDialog(c, question, "", SOptionPane.INFORMATION_ICON, options, defaultIsYes ? 0 : 1) == 0; return FOptionPane.showCardOptionDialog(c, question, "", SOptionPane.INFORMATION_ICON, optionsToUse, defaultIsYes ? 0 : 1) == 0;
} }
@Override @Override
public <T> List<T> getChoices(final String message, final int min, final int max, final Collection<T> choices, final T selected, final Function<T, String> display) { public <T> List<T> getChoices(final String message, final int min, final int max, final List<T> choices, final T selected, final Function<T, String> display) {
return GuiBase.getInterface().getChoices(message, min, max, choices, selected, display); return GuiBase.getInterface().getChoices(message, min, max, choices, selected, display);
} }
@@ -445,14 +449,14 @@ public class MatchController extends AbstractGuiGame {
return new WaitCallback<List<PaperCard>>() { return new WaitCallback<List<PaperCard>>() {
@Override @Override
public void run() { public void run() {
FSideboardDialog sideboardDialog = new FSideboardDialog(sideboard, main, this); final FSideboardDialog sideboardDialog = new FSideboardDialog(sideboard, main, this);
sideboardDialog.show(); sideboardDialog.show();
} }
}.invokeAndWait(); }.invokeAndWait();
} }
@Override @Override
public GameEntityView chooseSingleEntityForEffect(final String title, final Collection<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) { public GameEntityView chooseSingleEntityForEffect(final String title, final List<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) {
if (delayedReveal == null || Iterables.isEmpty(delayedReveal.getCards())) { if (delayedReveal == null || Iterables.isEmpty(delayedReveal.getCards())) {
if (isOptional) { if (isOptional) {
return SGuiChoose.oneOrNone(title, optionList); return SGuiChoose.oneOrNone(title, optionList);
@@ -464,11 +468,11 @@ public class MatchController extends AbstractGuiGame {
final String revealListCaption = StringUtils.capitalize(MessageUtil.formatMessage("{player's} " + delayedReveal.getZone().name(), delayedReveal.getOwner(), delayedReveal.getOwner())); final String revealListCaption = StringUtils.capitalize(MessageUtil.formatMessage("{player's} " + delayedReveal.getZone().name(), delayedReveal.getOwner(), delayedReveal.getOwner()));
final FImage revealListImage = MatchController.getView().getPlayerPanels().values().iterator().next().getZoneTab(delayedReveal.getZone()).getIcon(); final FImage revealListImage = MatchController.getView().getPlayerPanels().values().iterator().next().getZoneTab(delayedReveal.getZone()).getIcon();
//use special dialog for choosing card and offering ability to see all revealed cards at the same time //use special dialog for choosing card and offering ability to see all revealed cards at the same time
return new WaitCallback<GameEntityView>() { return new WaitCallback<GameEntityView>() {
@Override @Override
public void run() { public void run() {
GameEntityPicker picker = new GameEntityPicker(title, optionList, revealList, revealListCaption, revealListImage, isOptional, this); final GameEntityPicker picker = new GameEntityPicker(title, optionList, revealList, revealListCaption, revealListImage, isOptional, this);
picker.show(); picker.show();
} }
}.invokeAndWait(); }.invokeAndWait();

View File

@@ -1,10 +1,13 @@
package forge.toolbox; package forge.toolbox;
import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment; import com.badlogic.gdx.graphics.g2d.BitmapFont.HAlignment;
import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector2;
import com.google.common.collect.ImmutableList;
import forge.Forge; import forge.Forge;
import forge.Graphics; import forge.Graphics;
@@ -52,11 +55,11 @@ public class FOptionPane extends FDialog {
} }
public static void showMessageDialog(final String message, final String title, final FImage icon) { public static void showMessageDialog(final String message, final String title, final FImage icon) {
showOptionDialog(message, title, icon, new String[] {"OK"}, 0, null); showOptionDialog(message, title, icon, ImmutableList.of("OK"), 0, null);
} }
public static void showMessageDialog(final String message, final String title, final FImage icon, final Callback<Integer> callback) { public static void showMessageDialog(final String message, final String title, final FImage icon, final Callback<Integer> callback) {
showOptionDialog(message, title, icon, new String[] {"OK"}, 0, callback); showOptionDialog(message, title, icon, ImmutableList.of("OK"), 0, callback);
} }
public static void showConfirmDialog(final String message, final Callback<Boolean> callback) { public static void showConfirmDialog(final String message, final Callback<Boolean> callback) {
@@ -76,7 +79,7 @@ public class FOptionPane extends FDialog {
} }
public static void showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes, final Callback<Boolean> callback) { public static void showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes, final Callback<Boolean> callback) {
final String[] options = {yesButtonText, noButtonText}; final List<String> options = ImmutableList.of(yesButtonText, noButtonText);
showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1, new Callback<Integer>() { showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1, new Callback<Integer>() {
@Override @Override
public void run(final Integer result) { public void run(final Integer result) {
@@ -85,16 +88,16 @@ public class FOptionPane extends FDialog {
}); });
} }
public static void showOptionDialog(final String message, final String title, final FImage icon, final String[] options, final Callback<Integer> callback) { public static void showOptionDialog(final String message, final String title, final FImage icon, final List<String> options, final Callback<Integer> callback) {
showOptionDialog(message, title, icon, options, 0, callback); showOptionDialog(message, title, icon, options, 0, callback);
} }
public static void showOptionDialog(final String message, final String title, final FImage icon, final String[] options, final int defaultOption, final Callback<Integer> callback) { public static void showOptionDialog(final String message, final String title, final FImage icon, final List<String> options, final int defaultOption, final Callback<Integer> callback) {
final FOptionPane optionPane = new FOptionPane(message, title, icon, null, options, defaultOption, callback); final FOptionPane optionPane = new FOptionPane(message, title, icon, null, options, defaultOption, callback);
optionPane.show(); optionPane.show();
} }
public static int showCardOptionDialog(final CardView card, final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public static int showCardOptionDialog(final CardView card, final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return new WaitCallback<Integer>() { return new WaitCallback<Integer>() {
@Override @Override
public void run() { public void run() {
@@ -103,7 +106,7 @@ public class FOptionPane extends FDialog {
}.invokeAndWait(); }.invokeAndWait();
} }
public static void showCardOptionDialog(final CardView card, String message, String title, FImage icon, final String[] options, final int defaultOption, final Callback<Integer> callback) { public static void showCardOptionDialog(final CardView card, String message, String title, FImage icon, final List<String> options, final int defaultOption, final Callback<Integer> callback) {
final FDisplayObject cardDisplay; final FDisplayObject cardDisplay;
if (card != null) { if (card != null) {
cardDisplay = new FDisplayObject() { cardDisplay = new FDisplayObject() {
@@ -150,7 +153,7 @@ public class FOptionPane extends FDialog {
public static <T> void showInputDialog(final String title, final T initialInput, final Callback<T> callback) { public static <T> void showInputDialog(final String title, final T initialInput, final Callback<T> callback) {
showInputDialog(null, title, initialInput, null, callback); showInputDialog(null, title, initialInput, null, callback);
} }
public static <T> void showInputDialog(final String message, final String title, final T initialInput, final T[] inputOptions, final Callback<T> callback) { public static <T> void showInputDialog(final String message, final String title, final T initialInput, final List<T> inputOptions, final Callback<T> callback) {
final FDisplayObject inputField; final FDisplayObject inputField;
final FTextField txtInput; final FTextField txtInput;
final FComboBox<T> cbInput; final FComboBox<T> cbInput;
@@ -178,7 +181,7 @@ public class FOptionPane extends FDialog {
container.add(inputField); container.add(inputField);
container.setHeight(inputField.getHeight() + padTop + PADDING); container.setHeight(inputField.getHeight() + padTop + PADDING);
final FOptionPane optionPane = new FOptionPane(message, title, null, container, new String[] {"OK", "Cancel"}, 0, new Callback<Integer>() { final FOptionPane optionPane = new FOptionPane(message, title, null, container, ImmutableList.of("OK", "Cancel"), 0, new Callback<Integer>() {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public void run(final Integer result) { public void run(final Integer result) {
@@ -221,8 +224,8 @@ public class FOptionPane extends FDialog {
private final int defaultOption; private final int defaultOption;
private final boolean centerIcon; private final boolean centerIcon;
public FOptionPane(final String message, final String title, final FImage icon, final FDisplayObject displayObj0, final String[] options, final int defaultOption0, final Callback<Integer> callback0) { public FOptionPane(final String message, final String title, final FImage icon, final FDisplayObject displayObj0, final List<String> options, final int defaultOption0, final Callback<Integer> callback0) {
super(title, options.length); super(title, options.size());
if (icon != null) { if (icon != null) {
centerIcon = icon.getWidth() >= 100; //for large icon, center in dialog centerIcon = icon.getWidth() >= 100; //for large icon, center in dialog
@@ -254,9 +257,10 @@ public class FOptionPane extends FDialog {
callback = callback0; callback = callback0;
for (int i = 0; i < options.length; i++) { final int optionsSize = options.size();
for (int i = 0; i < optionsSize; i++) {
final int option = i; final int option = i;
initButton(i, options[i], new FEventHandler() { initButton(i, options.get(i), new FEventHandler() {
@Override @Override
public void handleEvent(final FEvent e) { public void handleEvent(final FEvent e) {
setResult(option); setResult(option);

View File

@@ -1,15 +1,19 @@
package forge.toolbox; package forge.toolbox;
import java.util.List;
import forge.game.card.CardView; import forge.game.card.CardView;
import forge.util.Callback; import forge.util.Callback;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ImmutableList;
/** /**
* Holds player interactions using standard windows * Holds player interactions using standard windows
*/ */
public class GuiDialog { public class GuiDialog {
private static final String[] defaultConfirmOptions = { "Yes", "No" }; private static final ImmutableList<String> defaultConfirmOptions = ImmutableList.of("Yes", "No");
public static void confirm(final CardView c, final String question, final Callback<Boolean> callback) { public static void confirm(final CardView c, final String question, final Callback<Boolean> callback) {
GuiDialog.confirm(c, question, true, null, callback); GuiDialog.confirm(c, question, true, null, callback);
@@ -17,18 +21,17 @@ public class GuiDialog {
public static void confirm(final CardView c, final String question, final boolean defaultChoice, final Callback<Boolean> callback) { public static void confirm(final CardView c, final String question, final boolean defaultChoice, final Callback<Boolean> callback) {
GuiDialog.confirm(c, question, defaultChoice, null, callback); GuiDialog.confirm(c, question, defaultChoice, null, callback);
} }
public static void confirm(final CardView c, final String question, String[] options, final Callback<Boolean> callback) { public static void confirm(final CardView c, final String question, final List<String> options, final Callback<Boolean> callback) {
GuiDialog.confirm(c, question, true, options, callback); GuiDialog.confirm(c, question, true, options, callback);
} }
public static void confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options, final Callback<Boolean> callback) { public static void confirm(final CardView c, final String question, final boolean defaultIsYes, final List<String> options, final Callback<Boolean> callback) {
final String title = c == null ? "Question" : c + " - Ability"; final String title = c == null ? "Question" : c + " - Ability";
String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question; String questionToUse = StringUtils.isBlank(question) ? "Activate card's ability?" : question;
String[] opts = options == null ? defaultConfirmOptions : options; final List<String> opts = options == null ? defaultConfirmOptions : options;
FOptionPane.showCardOptionDialog(c, questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1, new Callback<Integer>() { FOptionPane.showCardOptionDialog(c, questionToUse, title, FOptionPane.QUESTION_ICON, opts, defaultIsYes ? 0 : 1, new Callback<Integer>() {
@Override @Override public void run(final Integer result) {
public void run(Integer result) { callback.run(result.intValue() == 0);
callback.run(result == 0);
} }
}); });
} }

View File

@@ -19,6 +19,7 @@
package forge.toolbox; package forge.toolbox;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.Graphics; import forge.Graphics;
@@ -108,12 +109,11 @@ public class ListChooser<T> extends FContainer {
}); });
} }
String[] options; final List<String> options;
if (minChoices == 0) { if (minChoices == 0) {
options = new String[] {"OK", "Cancel"}; options = ImmutableList.of("OK", "Cancel");
} } else {
else { options = ImmutableList.of("OK");
options = new String[] {"OK"};
} }
updateHeight(); updateHeight();

View File

@@ -30,8 +30,8 @@ public interface IGuiBase {
ISkinImage createLayeredImage(FSkinProp background, String overlayFilename, float opacity); ISkinImage createLayeredImage(FSkinProp background, String overlayFilename, float opacity);
void showBugReportDialog(String title, String text, boolean showExitAppBtn); void showBugReportDialog(String title, String text, boolean showExitAppBtn);
void showImageDialog(ISkinImage image, String message, String title); void showImageDialog(ISkinImage image, String message, String title);
int showOptionDialog(String message, String title, FSkinProp icon, String[] options, int defaultOption); int showOptionDialog(String message, String title, FSkinProp icon, List<String> options, int defaultOption);
String showInputDialog(String message, String title, FSkinProp icon, String initialInput, String[] inputOptions); String showInputDialog(String message, String title, FSkinProp icon, String initialInput, List<String> inputOptions);
<T> List<T> getChoices(String message, int min, int max, Collection<T> choices, T selected, Function<T, String> display); <T> List<T> getChoices(String message, int min, int max, Collection<T> choices, T selected, Function<T, String> display);
<T> List<T> order(String title, String top, int remainingObjectsMin, int remainingObjectsMax, List<T> sourceChoices, List<T> destChoices); <T> List<T> order(String title, String top, int remainingObjectsMin, int remainingObjectsMax, List<T> sourceChoices, List<T> destChoices);
String showFileDialog(String title, String defaultDir); String showFileDialog(String title, String defaultDir);

View File

@@ -63,21 +63,19 @@ public interface IGuiGame {
boolean showConfirmDialog(String message, String title, String yesButtonText, String noButtonText); boolean showConfirmDialog(String message, String title, String yesButtonText, String noButtonText);
boolean showConfirmDialog(String message, String title, String yesButtonText, String noButtonText, boolean defaultYes); boolean showConfirmDialog(String message, String title, String yesButtonText, String noButtonText, boolean defaultYes);
int showOptionDialog(String message, String title, FSkinProp icon, int showOptionDialog(String message, String title, FSkinProp icon, List<String> options, int defaultOption);
String[] options, int defaultOption);
String showInputDialog(String message, String title); String showInputDialog(String message, String title);
String showInputDialog(String message, String title, FSkinProp icon); String showInputDialog(String message, String title, FSkinProp icon);
String showInputDialog(String message, String title, FSkinProp icon, String initialInput); String showInputDialog(String message, String title, FSkinProp icon, String initialInput);
String showInputDialog(String message, String title, FSkinProp icon, String initialInput, String[] inputOptions); String showInputDialog(String message, String title, FSkinProp icon, String initialInput, List<String> inputOptions);
boolean confirm(CardView c, String question); boolean confirm(CardView c, String question);
boolean confirm(CardView c, String question, String[] options); boolean confirm(CardView c, String question, List<String> options);
boolean confirm(CardView c, String question, boolean defaultIsYes, String[] options); boolean confirm(CardView c, String question, boolean defaultIsYes, List<String> options);
<T> List<T> getChoices(String message, int min, int max, T[] choices); <T> List<T> getChoices(String message, int min, int max, List<T> choices);
<T> List<T> getChoices(String message, int min, int max, Collection<T> choices); <T> List<T> getChoices(String message, int min, int max, List<T> choices, T selected, Function<T, String> display);
<T> List<T> getChoices(String message, int min, int max, Collection<T> choices, T selected, Function<T, String> display);
// Get Integer in range // Get Integer in range
Integer getInteger(String message, int min); Integer getInteger(String message, int min);
@@ -99,8 +97,7 @@ public interface IGuiGame {
* getChoices. * getChoices.
* @see #getChoices(String, int, int, Object...) * @see #getChoices(String, int, int, Object...)
*/ */
<T> T oneOrNone(String message, T[] choices); <T> T oneOrNone(String message, List<T> choices);
<T> T oneOrNone(String message, Collection<T> choices);
/** /**
* <p> * <p>
@@ -115,10 +112,9 @@ public interface IGuiGame {
* a T object. * a T object.
* @return One of {@code choices}. Can only be {@code null} if {@code choices} is empty. * @return One of {@code choices}. Can only be {@code null} if {@code choices} is empty.
*/ */
<T> T one(String message, T[] choices); <T> T one(String message, List<T> choices);
<T> T one(String message, Collection<T> choices);
<T> void reveal(String message, Collection<T> items); <T> void reveal(String message, List<T> items);
<T> List<T> many(String title, String topCaption, int cnt, List<T> sourceChoices, CardView c); <T> List<T> many(String title, String topCaption, int cnt, List<T> sourceChoices, CardView c);
<T> List<T> many(String title, String topCaption, int min, int max, List<T> sourceChoices, CardView c); <T> List<T> many(String title, String topCaption, int min, int max, List<T> sourceChoices, CardView c);
@@ -142,7 +138,7 @@ public interface IGuiGame {
<T> List<T> insertInList(String title, T newItem, List<T> oldItems); <T> List<T> insertInList(String title, T newItem, List<T> oldItems);
List<PaperCard> sideboard(CardPool sideboard, CardPool main); List<PaperCard> sideboard(CardPool sideboard, CardPool main);
GameEntityView chooseSingleEntityForEffect(String title, Collection<? extends GameEntityView> optionList, DelayedReveal delayedReveal, boolean isOptional); void setCard(CardView card); GameEntityView chooseSingleEntityForEffect(String title, List<? extends GameEntityView> optionList, DelayedReveal delayedReveal, boolean isOptional); void setCard(CardView card);
void setPlayerAvatar(LobbyPlayer player, IHasIcon ihi); void setPlayerAvatar(LobbyPlayer player, IHasIcon ihi);
boolean openZones(Collection<ZoneType> zones, Map<PlayerView, Object> players); boolean openZones(Collection<ZoneType> zones, Map<PlayerView, Object> players);
void restoreOldZones(Map<PlayerView, Object> playersToRestoreZonesFor); void restoreOldZones(Map<PlayerView, Object> playersToRestoreZonesFor);

View File

@@ -1,7 +1,6 @@
package forge.match; package forge.match;
import java.util.ArrayList; import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -12,6 +11,7 @@ import java.util.TimerTask;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@@ -114,17 +114,17 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
if (altState == null) { return false; } if (altState == null) { return false; }
switch (altState.getState()) { switch (altState.getState()) {
case Original: case Original:
final CardStateView currentState = cv.getCurrentState(); final CardStateView currentState = cv.getCurrentState();
if (currentState.getState() == CardStateName.FaceDown) { if (currentState.getState() == CardStateName.FaceDown) {
return getCurrentPlayer() == null || cv.canFaceDownBeShownToAny(getLocalPlayers()); return getCurrentPlayer() == null || cv.canFaceDownBeShownToAny(getLocalPlayers());
} }
return true; //original can always be shown if not a face down that can't be shown return true; //original can always be shown if not a face down that can't be shown
case Flipped: case Flipped:
case Transformed: case Transformed:
return true; return true;
default: default:
return false; return false;
} }
} }
@@ -339,17 +339,8 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
* @see #getChoices(String, int, int, Object...) * @see #getChoices(String, int, int, Object...)
*/ */
@Override @Override
public <T> T oneOrNone(final String message, final T[] choices) { public <T> T oneOrNone(final String message, final List<T> choices) {
if ((choices == null) || (choices.length == 0)) { if (choices == null || choices.isEmpty()) {
return null;
}
final List<T> choice = getChoices(message, 0, 1, choices);
return choice.isEmpty() ? null : choice.get(0);
}
@Override
public <T> T oneOrNone(final String message, final Collection<T> choices) {
if ((choices == null) || choices.isEmpty()) {
return null; return null;
} }
final List<T> choice = getChoices(message, 0, 1, choices); final List<T> choice = getChoices(message, 0, 1, choices);
@@ -371,14 +362,7 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
* @return a T object. * @return a T object.
*/ */
@Override @Override
public <T> T one(final String message, final T[] choices) { public <T> T one(final String message, final List<T> choices) {
final List<T> choice = getChoices(message, 1, 1, choices);
assert choice.size() == 1;
return choice.get(0);
}
@Override
public <T> T one(final String message, final Collection<T> choices) {
if (choices == null || choices.isEmpty()) { if (choices == null || choices.isEmpty()) {
return null; return null;
} }
@@ -393,7 +377,7 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
// Nothing to choose here. Code uses this to just reveal one or more items // Nothing to choose here. Code uses this to just reveal one or more items
@Override @Override
public <T> void reveal(final String message, final Collection<T> items) { public <T> void reveal(final String message, final List<T> items) {
getChoices(message, -1, -1, items); getChoices(message, -1, -1, items);
} }
@@ -424,14 +408,14 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
choices[count - i - 1] = Integer.valueOf(i + min); choices[count - i - 1] = Integer.valueOf(i + min);
} }
} } else {
else {
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
choices[i] = Integer.valueOf(i + min); choices[i] = Integer.valueOf(i + min);
} }
} }
return oneOrNone(message, choices); return oneOrNone(message, ImmutableList.copyOf(choices));
} }
@Override @Override
public Integer getInteger(final String message, final int min, final int max, final int cutoff) { public Integer getInteger(final String message, final int min, final int max, final int cutoff) {
if (max <= min || cutoff < min) { if (max <= min || cutoff < min) {
@@ -442,15 +426,15 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
return getInteger(message, min, max); return getInteger(message, min, max);
} }
final List<Object> choices = new ArrayList<Object>(); final ImmutableList.Builder<Serializable> choices = ImmutableList.builder();
for (int i = min; i <= cutoff; i++) { for (int i = min; i <= cutoff; i++) {
choices.add(Integer.valueOf(i)); choices.add(Integer.valueOf(i));
} }
choices.add("..."); choices.add("...");
final Object choice = oneOrNone(message, choices); final Object choice = oneOrNone(message, choices.build());
if (choice instanceof Integer || choice == null) { if (choice instanceof Integer || choice == null) {
return (Integer)choice; return (Integer) choice;
} }
//if Other option picked, prompt for number input //if Other option picked, prompt for number input
@@ -481,12 +465,7 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
// returned Object will never be null // returned Object will never be null
@Override @Override
public <T> List<T> getChoices(final String message, final int min, final int max, final T[] choices) { public <T> List<T> getChoices(final String message, final int min, final int max, final List<T> choices) {
return getChoices(message, min, max, Arrays.asList(choices), null, null);
}
@Override
public <T> List<T> getChoices(final String message, final int min, final int max, final Collection<T> choices) {
return getChoices(message, min, max, choices, null, null); return getChoices(message, min, max, choices, null, null);
} }
@@ -546,8 +525,9 @@ public abstract class AbstractGuiGame implements IGuiGame, IMayViewCards {
public boolean confirm(final CardView c, final String question) { public boolean confirm(final CardView c, final String question) {
return confirm(c, question, true, null); return confirm(c, question, true, null);
} }
@Override @Override
public boolean confirm(final CardView c, final String question, final String[] options) { public boolean confirm(final CardView c, final String question, final List<String> options) {
return confirm(c, question, true, options); return confirm(c, question, true, options);
} }

View File

@@ -6,6 +6,8 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import com.google.common.collect.ImmutableList;
import forge.game.GameEntity; import forge.game.GameEntity;
import forge.game.GameObject; import forge.game.GameObject;
import forge.game.ability.ApiType; import forge.game.ability.ApiType;
@@ -46,20 +48,22 @@ public final class InputSelectTargets extends InputSyncronizedBase {
sb.append("Targeted:\n"); sb.append("Targeted:\n");
for (final Entry<GameEntity, Integer> o : targetDepth.entrySet()) { for (final Entry<GameEntity, Integer> o : targetDepth.entrySet()) {
sb.append(o.getKey()); sb.append(o.getKey());
if( o.getValue() > 1 ) if (o.getValue() > 1) {
sb.append(" (").append(o.getValue()).append(" times)"); sb.append(String.format(" (%d times)", o.getValue()));
sb.append("\n"); }
sb.append("\n");
} }
if (!sa.getUniqueTargets().isEmpty()) { if (!sa.getUniqueTargets().isEmpty()) {
sb.append("Parent Targeted:"); sb.append("Parent Targeted:");
sb.append(sa.getUniqueTargets()).append("\n"); sb.append(sa.getUniqueTargets()).append("\n");
} }
sb.append(sa.getHostCard() + " - " + tgt.getVTSelection()); sb.append(sa.getHostCard() + " - " + tgt.getVTSelection());
int maxTargets = tgt.getMaxTargets(sa.getHostCard(), sa); final int maxTargets = tgt.getMaxTargets(sa.getHostCard(), sa);
int targeted = sa.getTargets().getNumTargeted(); final int targeted = sa.getTargets().getNumTargeted();
if(maxTargets > 1) if(maxTargets > 1) {
sb.append("\n(").append(maxTargets - targeted).append(" more can be targeted)"); sb.append(String.format("\n(%d more can be targeted)", Integer.valueOf(maxTargets - targeted)));
}
showMessage(sb.toString()); showMessage(sb.toString());
@@ -122,9 +126,9 @@ public final class InputSelectTargets extends InputSyncronizedBase {
// If all cards must have different controllers // If all cards must have different controllers
if (tgt.isDifferentControllers()) { if (tgt.isDifferentControllers()) {
final List<Player> targetedControllers = new ArrayList<Player>(); final List<Player> targetedControllers = new ArrayList<Player>();
for (GameObject o : targetDepth.keySet()) { for (final GameObject o : targetDepth.keySet()) {
if (o instanceof Card) { if (o instanceof Card) {
Player p = ((Card) o).getController(); final Player p = ((Card) o).getController();
targetedControllers.add(p); targetedControllers.add(p);
} }
} }
@@ -150,9 +154,9 @@ public final class InputSelectTargets extends InputSyncronizedBase {
// allow allocation only if the max targets isn't reached and there are more candidates // allow allocation only if the max targets isn't reached and there are more candidates
if ((sa.getTargets().getNumTargeted() + 1 < tgt.getMaxTargets(sa.getHostCard(), sa)) if ((sa.getTargets().getNumTargeted() + 1 < tgt.getMaxTargets(sa.getHostCard(), sa))
&& (tgt.getNumCandidates(sa, true) - 1 > 0) && stillToDivide > 1) { && (tgt.getNumCandidates(sa, true) - 1 > 0) && stillToDivide > 1) {
final Integer[] choices = new Integer[stillToDivide]; final ImmutableList.Builder<Integer> choices = ImmutableList.builder();
for (int i = 1; i <= stillToDivide; i++) { for (int i = 1; i <= stillToDivide; i++) {
choices[i - 1] = i; choices.add(Integer.valueOf(i));
} }
String apiBasedMessage = "Distribute how much to "; String apiBasedMessage = "Distribute how much to ";
if (sa.getApi() == ApiType.DealDamage) { if (sa.getApi() == ApiType.DealDamage) {
@@ -167,7 +171,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(apiBasedMessage); sb.append(apiBasedMessage);
sb.append(card.toString()); sb.append(card.toString());
final Integer chosen = getController().getGui().oneOrNone(sb.toString(), choices); final Integer chosen = getController().getGui().oneOrNone(sb.toString(), choices.build());
if (chosen == null) { if (chosen == null) {
return true; //still return true since there was a valid choice return true; //still return true since there was a valid choice
} }
@@ -184,7 +188,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
} }
@Override @Override
public String getActivateAction(Card card) { public String getActivateAction(final Card card) {
if (!tgt.isUniqueTargets() && targetDepth.containsKey(card)) { if (!tgt.isUniqueTargets() && targetDepth.containsKey(card)) {
return null; return null;
} }
@@ -195,7 +199,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
} }
@Override @Override
protected final void onPlayerSelected(Player player, final ITriggerEvent triggerEvent) { protected final void onPlayerSelected(final Player player, final ITriggerEvent triggerEvent) {
if (!tgt.isUniqueTargets() && targetDepth.containsKey(player)) { if (!tgt.isUniqueTargets() && targetDepth.containsKey(player)) {
return; return;
} }
@@ -204,15 +208,15 @@ public final class InputSelectTargets extends InputSyncronizedBase {
showMessage(sa.getHostCard() + " - Cannot target this player (Hexproof? Protection? Restrictions?)."); showMessage(sa.getHostCard() + " - Cannot target this player (Hexproof? Protection? Restrictions?).");
return; return;
} }
if (tgt.isDividedAsYouChoose()) { if (tgt.isDividedAsYouChoose()) {
final int stillToDivide = tgt.getStillToDivide(); final int stillToDivide = tgt.getStillToDivide();
int allocatedPortion = 0; int allocatedPortion = 0;
// allow allocation only if the max targets isn't reached and there are more candidates // allow allocation only if the max targets isn't reached and there are more candidates
if ((sa.getTargets().getNumTargeted() + 1 < tgt.getMaxTargets(sa.getHostCard(), sa)) && (tgt.getNumCandidates(sa, true) - 1 > 0) && stillToDivide > 1) { if ((sa.getTargets().getNumTargeted() + 1 < tgt.getMaxTargets(sa.getHostCard(), sa)) && (tgt.getNumCandidates(sa, true) - 1 > 0) && stillToDivide > 1) {
final Integer[] choices = new Integer[stillToDivide]; final ImmutableList.Builder<Integer> choices = ImmutableList.builder();
for (int i = 1; i <= stillToDivide; i++) { for (int i = 1; i <= stillToDivide; i++) {
choices[i - 1] = i; choices.add(Integer.valueOf(i));
} }
String apiBasedMessage = "Distribute how much to "; String apiBasedMessage = "Distribute how much to ";
if (sa.getApi() == ApiType.DealDamage) { if (sa.getApi() == ApiType.DealDamage) {
@@ -223,7 +227,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
sb.append(apiBasedMessage); sb.append(apiBasedMessage);
sb.append(player.getName()); sb.append(player.getName());
final Integer chosen = getController().getGui().oneOrNone(sb.toString(), choices); final Integer chosen = getController().getGui().oneOrNone(sb.toString(), choices.build());
if (null == chosen) { if (null == chosen) {
return; return;
} }
@@ -245,15 +249,15 @@ public final class InputSelectTargets extends InputSyncronizedBase {
} }
final Integer val = targetDepth.get(ge); final Integer val = targetDepth.get(ge);
targetDepth.put(ge, val == null ? Integer.valueOf(1) : Integer.valueOf(val.intValue() + 1) ); targetDepth.put(ge, val == null ? Integer.valueOf(1) : Integer.valueOf(val.intValue() + 1) );
if(hasAllTargets()) { if (hasAllTargets()) {
bOk = true; bOk = true;
this.done(); this.done();
} } else {
else
this.showMessage(); this.showMessage();
}
} }
private void done() { private void done() {
for (final GameEntity c : targetDepth.keySet()) { for (final GameEntity c : targetDepth.keySet()) {
if (c instanceof Card) { if (c instanceof Card) {
@@ -263,7 +267,7 @@ public final class InputSelectTargets extends InputSyncronizedBase {
this.stop(); this.stop();
} }
private boolean hasAllTargets() { private boolean hasAllTargets() {
return tgt.isMaxTargetsChosen(sa.getHostCard(), sa) || ( tgt.getStillToDivide() == 0 && tgt.isDividedAsYouChoose()); return tgt.isMaxTargetsChosen(sa.getHostCard(), sa) || ( tgt.getStillToDivide() == 0 && tgt.isDividedAsYouChoose());
} }

View File

@@ -1,6 +1,5 @@
package forge.net; package forge.net;
import java.lang.reflect.Array;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -55,13 +54,13 @@ public enum ProtocolMethod {
message (Mode.SERVER, Void.TYPE, String.class, String.class), message (Mode.SERVER, Void.TYPE, String.class, String.class),
showErrorDialog (Mode.SERVER, Void.TYPE, String.class, String.class), showErrorDialog (Mode.SERVER, Void.TYPE, String.class, String.class),
showConfirmDialog (Mode.SERVER, Boolean.TYPE, String.class, String.class, String.class, String.class, Boolean.TYPE), showConfirmDialog (Mode.SERVER, Boolean.TYPE, String.class, String.class, String.class, String.class, Boolean.TYPE),
showOptionDialog (Mode.SERVER, Integer.TYPE, String.class, String.class, FSkinProp.class, Array/*String*/.class, Integer.TYPE), showOptionDialog (Mode.SERVER, Integer.TYPE, String.class, String.class, FSkinProp.class, List/*String*/.class, Integer.TYPE),
showInputDialog (Mode.SERVER, String.class, String.class, String.class, FSkinProp.class, String.class, Array/*String*/.class), showInputDialog (Mode.SERVER, String.class, String.class, String.class, FSkinProp.class, String.class, List/*String*/.class),
confirm (Mode.SERVER, Boolean.TYPE, CardView.class, String.class, Boolean.TYPE, Array/*String*/.class), confirm (Mode.SERVER, Boolean.TYPE, CardView.class, String.class, Boolean.TYPE, List/*String*/.class),
getChoices (Mode.SERVER, List.class, String.class, Integer.TYPE, Integer.TYPE, Collection.class, Object.class, Function.class), getChoices (Mode.SERVER, List.class, String.class, Integer.TYPE, Integer.TYPE, List.class, Object.class, Function.class),
order (Mode.SERVER, List.class, String.class, String.class, Integer.TYPE, Integer.TYPE, List.class, List.class, CardView.class, Boolean.TYPE), order (Mode.SERVER, List.class, String.class, String.class, Integer.TYPE, Integer.TYPE, List.class, List.class, CardView.class, Boolean.TYPE),
sideboard (Mode.SERVER, List.class, CardPool.class, CardPool.class), sideboard (Mode.SERVER, List.class, CardPool.class, CardPool.class),
chooseSingleEntityForEffect(Mode.SERVER, GameEntityView.class, String.class, TrackableCollection.class, DelayedReveal.class, Boolean.TYPE), chooseSingleEntityForEffect(Mode.SERVER, GameEntityView.class, String.class, List.class, DelayedReveal.class, Boolean.TYPE),
setCard (Mode.SERVER, Void.TYPE, CardView.class), setCard (Mode.SERVER, Void.TYPE, CardView.class),
// TODO case "setPlayerAvatar": // TODO case "setPlayerAvatar":
openZones (Mode.SERVER, Boolean.TYPE, Collection/*ZoneType*/.class, Map/*PlayerView,Object*/.class), openZones (Mode.SERVER, Boolean.TYPE, Collection/*ZoneType*/.class, Map/*PlayerView,Object*/.class),

View File

@@ -189,22 +189,22 @@ public class NetGuiGame extends AbstractGuiGame {
} }
@Override @Override
public int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return sendAndWait(ProtocolMethod.showOptionDialog, message, title, icon, options, defaultOption); return sendAndWait(ProtocolMethod.showOptionDialog, message, title, icon, options, defaultOption);
} }
@Override @Override
public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return sendAndWait(ProtocolMethod.showInputDialog, message, title, icon, initialInput, inputOptions); return sendAndWait(ProtocolMethod.showInputDialog, message, title, icon, initialInput, inputOptions);
} }
@Override @Override
public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final String[] options) { public boolean confirm(final CardView c, final String question, final boolean defaultIsYes, final List<String> options) {
return sendAndWait(ProtocolMethod.confirm, c, question, defaultIsYes, options); return sendAndWait(ProtocolMethod.confirm, c, question, defaultIsYes, options);
} }
@Override @Override
public <T> List<T> getChoices(final String message, final int min, final int max, final Collection<T> choices, final T selected, final Function<T, String> display) { public <T> List<T> getChoices(final String message, final int min, final int max, final List<T> choices, final T selected, final Function<T, String> display) {
return sendAndWait(ProtocolMethod.getChoices, message, min, max, choices, selected, display); return sendAndWait(ProtocolMethod.getChoices, message, min, max, choices, selected, display);
} }
@@ -219,7 +219,7 @@ public class NetGuiGame extends AbstractGuiGame {
} }
@Override @Override
public GameEntityView chooseSingleEntityForEffect(final String title, final Collection<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) { public GameEntityView chooseSingleEntityForEffect(final String title, final List<? extends GameEntityView> optionList, final DelayedReveal delayedReveal, final boolean isOptional) {
return sendAndWait(ProtocolMethod.chooseSingleEntityForEffect, title, optionList, delayedReveal, isOptional); return sendAndWait(ProtocolMethod.chooseSingleEntityForEffect, title, optionList, delayedReveal, isOptional);
} }

View File

@@ -25,6 +25,7 @@ import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import forge.FThreads; import forge.FThreads;
import forge.GuiBase; import forge.GuiBase;
@@ -291,7 +292,7 @@ public class ConquestController {
public void run() { public void run() {
awardWinStreakBonus(view); awardWinStreakBonus(view);
String[] options = {"Booster", "Card"}; final List<String> options = ImmutableList.of("Booster", "Card");
if (SOptionPane.showOptionDialog("Choose one \u2014\n\n" + if (SOptionPane.showOptionDialog("Choose one \u2014\n\n" +
"\u2022 Open a random booster pack\n" + "\u2022 Open a random booster pack\n" +
"\u2022 Choose a card from your opponent's deck", "\u2022 Choose a card from your opponent's deck",

View File

@@ -24,6 +24,7 @@ import com.google.common.base.Function;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
@@ -447,11 +448,11 @@ implements IGameController {
if (min >= max) { if (min >= max) {
return min; return min;
} }
final Integer[] choices = new Integer[max + 1 - min]; final ImmutableList.Builder<Integer> choices = ImmutableList.builder();
for (int i = 0; i <= max - min; i++) { for (int i = 0; i <= max - min; i++) {
choices[i] = Integer.valueOf(i + min); choices.add(Integer.valueOf(i + min));
} }
return getGui().one(title, choices).intValue(); return getGui().one(title, choices.build()).intValue();
} }
@Override @Override
@@ -460,11 +461,14 @@ implements IGameController {
} }
@Override @Override
public SpellAbility chooseSingleSpellForEffect(final java.util.List<SpellAbility> spells, final SpellAbility sa, final String title) { public SpellAbility chooseSingleSpellForEffect(final List<SpellAbility> spells, final SpellAbility sa, final String title) {
if (spells.size() < 2) { if (spells.size() < 2) {
return spells.get(0); return Iterables.getFirst(spells, null);
} }
// Show the card that asked for this choice
getGui().setCard(CardView.get(sa.getHostCard()));
// Human is supposed to read the message and understand from it what to choose // Human is supposed to read the message and understand from it what to choose
return getGui().one(title, spells); return getGui().one(title, spells);
} }
@@ -573,7 +577,7 @@ implements IGameController {
} }
@Override @Override
public void reveal(final Collection<CardView> cards, final ZoneType zone, final PlayerView owner, String message) { public void reveal(final List<CardView> cards, final ZoneType zone, final PlayerView owner, String message) {
if (StringUtils.isBlank(message)) { if (StringUtils.isBlank(message)) {
message = "Looking at cards in {player's} " + zone.name().toLowerCase(); message = "Looking at cards in {player's} " + zone.name().toLowerCase();
} else { } else {
@@ -626,7 +630,7 @@ implements IGameController {
final CardView view = CardView.get(c); final CardView view = CardView.get(c);
tempShowCard(c); tempShowCard(c);
final boolean result = getGui().confirm(view, "Put " + view + " on the top or bottom of your library?", new String[]{"Top", "Bottom"}); final boolean result = getGui().confirm(view, String.format("Put %s on the top or bottom of your library?", view), ImmutableList.of("Top", "Bottom"));
endTempShowCards(); endTempShowCards();
return result; return result;
@@ -637,28 +641,28 @@ implements IGameController {
List<CardView> choices; List<CardView> choices;
tempShowCards(cards); tempShowCards(cards);
switch (destinationZone) { switch (destinationZone) {
case Library: case Library:
choices = getGui().order("Choose order of cards to put into the library", "Closest to top", CardView.getCollection(cards), null); choices = getGui().order("Choose order of cards to put into the library", "Closest to top", CardView.getCollection(cards), null);
break; break;
case Battlefield: case Battlefield:
choices = getGui().order("Choose order of cards to put onto the battlefield", "Put first", CardView.getCollection(cards), null); choices = getGui().order("Choose order of cards to put onto the battlefield", "Put first", CardView.getCollection(cards), null);
break; break;
case Graveyard: case Graveyard:
choices = getGui().order("Choose order of cards to put into the graveyard", "Closest to bottom", CardView.getCollection(cards), null); choices = getGui().order("Choose order of cards to put into the graveyard", "Closest to bottom", CardView.getCollection(cards), null);
break; break;
case PlanarDeck: case PlanarDeck:
choices = getGui().order("Choose order of cards to put into the planar deck", "Closest to top", CardView.getCollection(cards), null); choices = getGui().order("Choose order of cards to put into the planar deck", "Closest to top", CardView.getCollection(cards), null);
break; break;
case SchemeDeck: case SchemeDeck:
choices = getGui().order("Choose order of cards to put into the scheme deck", "Closest to top", CardView.getCollection(cards), null); choices = getGui().order("Choose order of cards to put into the scheme deck", "Closest to top", CardView.getCollection(cards), null);
break; break;
case Stack: case Stack:
choices = getGui().order("Choose order of copies to cast", "Put first", CardView.getCollection(cards), null); choices = getGui().order("Choose order of copies to cast", "Put first", CardView.getCollection(cards), null);
break; break;
default: default:
System.out.println("ZoneType " + destinationZone + " - Not Ordered"); System.out.println("ZoneType " + destinationZone + " - Not Ordered");
endTempShowCards(); endTempShowCards();
return cards; return cards;
} }
endTempShowCards(); endTempShowCards();
return game.getCardList(choices); return game.getCardList(choices);
@@ -694,13 +698,13 @@ implements IGameController {
if (cardsInGrave == 0) { if (cardsInGrave == 0) {
return CardCollection.EMPTY; return CardCollection.EMPTY;
} }
final CardCollection toExile = new CardCollection();
final Integer[] cntChoice = new Integer[cardsInGrave + 1];
for (int i = 0; i <= cardsInGrave; i++) {
cntChoice[i] = Integer.valueOf(i);
}
final Integer chosenAmount = getGui().one("Delve how many cards?", cntChoice); final CardCollection toExile = new CardCollection();
final ImmutableList.Builder<Integer> cntChoice = ImmutableList.builder();
for (int i = 0; i <= cardsInGrave; i++) {
cntChoice.add(Integer.valueOf(i));
}
final int chosenAmount = getGui().one("Delve how many cards?", cntChoice.build()).intValue();
for (int i = 0; i < chosenAmount; i++) { for (int i = 0; i < chosenAmount; i++) {
final CardView nowChosen = getGui().oneOrNone("Exile which card?", CardView.getCollection(grave)); final CardView nowChosen = getGui().oneOrNone("Exile which card?", CardView.getCollection(grave));
@@ -949,15 +953,15 @@ implements IGameController {
@Override @Override
public boolean chooseBinary(final SpellAbility sa, final String question, final BinaryChoiceType kindOfChoice, final Boolean defaultVal) { public boolean chooseBinary(final SpellAbility sa, final String question, final BinaryChoiceType kindOfChoice, final Boolean defaultVal) {
final String[] labels; final List<String> labels;
switch (kindOfChoice) { switch (kindOfChoice) {
case HeadsOrTails: labels = new String[]{"Heads", "Tails"}; break; case HeadsOrTails: labels = ImmutableList.of("Heads", "Tails"); break;
case TapOrUntap: labels = new String[]{"Tap", "Untap"}; break; case TapOrUntap: labels = ImmutableList.of("Tap", "Untap"); break;
case OddsOrEvens: labels = new String[]{"Odds", "Evens"}; break; case OddsOrEvens: labels = ImmutableList.of("Odds", "Evens"); break;
case UntapOrLeaveTapped: labels = new String[]{"Untap", "Leave tapped"}; break; case UntapOrLeaveTapped: labels = ImmutableList.of("Untap", "Leave tapped"); break;
case UntapTimeVault: labels = new String[]{"Untap (and skip this turn)", "Leave tapped"}; break; case UntapTimeVault: labels = ImmutableList.of("Untap (and skip this turn)", "Leave tapped"); break;
case PlayOrDraw: labels = new String[]{"Play", "Draw"}; break; case PlayOrDraw: labels = ImmutableList.of("Play", "Draw"); break;
default: labels = kindOfChoice.toString().split("Or"); default: labels = ImmutableList.copyOf(kindOfChoice.toString().split("Or"));
} }
return getGui().confirm(CardView.get(sa.getHostCard()), question, defaultVal == null || defaultVal.booleanValue(), labels); return getGui().confirm(CardView.get(sa.getHostCard()), question, defaultVal == null || defaultVal.booleanValue(), labels);
} }
@@ -965,11 +969,11 @@ implements IGameController {
@Override @Override
public boolean chooseFlipResult(final SpellAbility sa, final Player flipper, final boolean[] results, final boolean call) { public boolean chooseFlipResult(final SpellAbility sa, final Player flipper, final boolean[] results, final boolean call) {
final String[] labelsSrc = call ? new String[]{"heads", "tails"} : new String[]{"win the flip", "lose the flip"}; final String[] labelsSrc = call ? new String[]{"heads", "tails"} : new String[]{"win the flip", "lose the flip"};
final String[] strResults = new String[results.length]; final ImmutableList.Builder<String> strResults = ImmutableList.<String>builder();
for (int i = 0; i < results.length; i++) { for (int i = 0; i < results.length; i++) {
strResults[i] = labelsSrc[results[i] ? 0 : 1]; strResults.add(labelsSrc[results[i] ? 0 : 1]);
} }
return getGui().one(sa.getHostCard().getName() + " - Choose a result", strResults).equals(labelsSrc[0]); return getGui().one(sa.getHostCard().getName() + " - Choose a result", strResults.build()).equals(labelsSrc[0]);
} }
@Override @Override
@@ -986,12 +990,12 @@ implements IGameController {
} }
final String counterChoiceTitle = "Choose a counter type on " + cardWithCounter; final String counterChoiceTitle = "Choose a counter type on " + cardWithCounter;
final CounterType chosen = getGui().one(counterChoiceTitle, cardWithCounter.getCounters().keySet()); final CounterType chosen = getGui().one(counterChoiceTitle, ImmutableList.copyOf(cardWithCounter.getCounters().keySet()));
final String putOrRemoveTitle = "What to do with that '" + chosen.getName() + "' counter "; final String putOrRemoveTitle = "What to do with that '" + chosen.getName() + "' counter ";
final String putString = "Put another " + chosen.getName() + " counter on " + cardWithCounter; final String putString = "Put another " + chosen.getName() + " counter on " + cardWithCounter;
final String removeString = "Remove a " + chosen.getName() + " counter from " + cardWithCounter; final String removeString = "Remove a " + chosen.getName() + " counter from " + cardWithCounter;
final String addOrRemove = getGui().one(putOrRemoveTitle, new String[]{putString,removeString}); final String addOrRemove = getGui().one(putOrRemoveTitle, ImmutableList.of(putString, removeString));
return new ImmutablePair<CounterType,String>(chosen,addOrRemove); return new ImmutablePair<CounterType,String>(chosen,addOrRemove);
} }
@@ -1061,9 +1065,9 @@ implements IGameController {
public byte chooseColor(final String message, final SpellAbility sa, final ColorSet colors) { public byte chooseColor(final String message, final SpellAbility sa, final ColorSet colors) {
final int cntColors = colors.countColors(); final int cntColors = colors.countColors();
switch (cntColors) { switch (cntColors) {
case 0: return 0; case 0: return 0;
case 1: return colors.getColor(); case 1: return colors.getColor();
default: return chooseColorCommon(message, sa == null ? null : sa.getHostCard(), colors, false); default: return chooseColorCommon(message, sa == null ? null : sa.getHostCard(), colors, false);
} }
} }
@@ -1071,29 +1075,25 @@ implements IGameController {
public byte chooseColorAllowColorless(final String message, final Card c, final ColorSet colors) { public byte chooseColorAllowColorless(final String message, final Card c, final ColorSet colors) {
final int cntColors = 1 + colors.countColors(); final int cntColors = 1 + colors.countColors();
switch (cntColors) { switch (cntColors) {
case 1: return 0; case 1: return 0;
default: return chooseColorCommon(message, c, colors, true); default: return chooseColorCommon(message, c, colors, true);
} }
} }
private byte chooseColorCommon(final String message, final Card c, final ColorSet colors, final boolean withColorless) { private byte chooseColorCommon(final String message, final Card c, final ColorSet colors, final boolean withColorless) {
int cntColors = colors.countColors(); final ImmutableList.Builder<String> colorNamesBuilder = ImmutableList.builder();
if(withColorless) {
cntColors++;
}
final String[] colorNames = new String[cntColors];
int i = 0;
if (withColorless) { if (withColorless) {
colorNames[i++] = MagicColor.toLongString((byte)0); colorNamesBuilder.add(MagicColor.toLongString(MagicColor.COLORLESS));
} }
for (final byte b : colors) { for (final Byte b : colors) {
colorNames[i++] = MagicColor.toLongString(b); colorNamesBuilder.add(MagicColor.toLongString(b.byteValue()));
} }
if (colorNames.length > 2) { final ImmutableList<String> colorNames = colorNamesBuilder.build();
if (colorNames.size() > 2) {
return MagicColor.fromName(getGui().one(message, colorNames)); return MagicColor.fromName(getGui().one(message, colorNames));
} }
final int idxChosen = getGui().confirm(CardView.get(c), message, colorNames) ? 0 : 1; final int idxChosen = getGui().confirm(CardView.get(c), message, colorNames) ? 0 : 1;
return MagicColor.fromName(colorNames[idxChosen]); return MagicColor.fromName(colorNames.get(idxChosen));
} }
@Override @Override
@@ -1105,7 +1105,7 @@ implements IGameController {
} }
@Override @Override
public CounterType chooseCounterType(final Collection<CounterType> options, final SpellAbility sa, final String prompt) { public CounterType chooseCounterType(final List<CounterType> options, final SpellAbility sa, final String prompt) {
if (options.size() <= 1) { if (options.size() <= 1) {
return Iterables.getFirst(options, null); return Iterables.getFirst(options, null);
} }
@@ -1202,7 +1202,7 @@ implements IGameController {
if (!faceUp) { if (!faceUp) {
final String p1Str = String.format("Pile 1 (%s cards)", pile1.size()); final String p1Str = String.format("Pile 1 (%s cards)", pile1.size());
final String p2Str = String.format("Pile 2 (%s cards)", pile2.size()); final String p2Str = String.format("Pile 2 (%s cards)", pile2.size());
final String[] possibleValues = { p1Str , p2Str }; final List<String> possibleValues = ImmutableList.of(p1Str , p2Str);
return getGui().confirm(CardView.get(sa.getHostCard()), "Choose a Pile", possibleValues); return getGui().confirm(CardView.get(sa.getHostCard()), "Choose a Pile", possibleValues);
} }
@@ -1239,7 +1239,7 @@ implements IGameController {
@Override @Override
public void revealAnte(final String message, final Multimap<Player, PaperCard> removedAnteCards) { public void revealAnte(final String message, final Multimap<Player, PaperCard> removedAnteCards) {
for (final Player p : removedAnteCards.keySet()) { for (final Player p : removedAnteCards.keySet()) {
getGui().reveal(message + " from " + Lang.getPossessedObject(MessageUtil.mayBeYou(player, p), "deck"), removedAnteCards.get(p)); getGui().reveal(message + " from " + Lang.getPossessedObject(MessageUtil.mayBeYou(player, p), "deck"), ImmutableList.copyOf(removedAnteCards.get(p)));
} }
} }
@@ -1568,7 +1568,7 @@ implements IGameController {
final Card card = game.getCard(getGui().oneOrNone("Add counters to which card?", CardView.getCollection(cards))); final Card card = game.getCard(getGui().oneOrNone("Add counters to which card?", CardView.getCollection(cards)));
if (card == null) { return; } if (card == null) { return; }
final CounterType counter = getGui().oneOrNone("Which type of counter?", CounterType.values()); final CounterType counter = getGui().oneOrNone("Which type of counter?", CounterType.values);
if (counter == null) { return; } if (counter == null) { return; }
final Integer count = getGui().getInteger("How many counters?", 1, Integer.MAX_VALUE, 10); final Integer count = getGui().getInteger("How many counters?", 1, Integer.MAX_VALUE, 10);
@@ -1746,7 +1746,7 @@ implements IGameController {
final Player player = game.getPlayer(getGui().oneOrNone("Which player should roll?", PlayerView.getCollection(game.getPlayers()))); final Player player = game.getPlayer(getGui().oneOrNone("Which player should roll?", PlayerView.getCollection(game.getPlayers())));
if (player == null) { return; } if (player == null) { return; }
final PlanarDice res = getGui().oneOrNone("Choose result", PlanarDice.values()); final PlanarDice res = getGui().oneOrNone("Choose result", PlanarDice.values);
if (res == null) { return; } if (res == null) { return; }
System.out.println("Rigging planar dice roll: " + res.toString()); System.out.println("Rigging planar dice roll: " + res.toString());

View File

@@ -1,5 +1,9 @@
package forge.util.gui; package forge.util.gui;
import java.util.List;
import com.google.common.collect.ImmutableList;
import forge.GuiBase; import forge.GuiBase;
import forge.assets.FSkinProp; import forge.assets.FSkinProp;
@@ -26,7 +30,7 @@ public class SOptionPane {
} }
public static void showMessageDialog(final String message, final String title, final FSkinProp icon) { public static void showMessageDialog(final String message, final String title, final FSkinProp icon) {
showOptionDialog(message, title, icon, new String[] {"OK"}, 0); showOptionDialog(message, title, icon, ImmutableList.of("OK"), 0);
} }
public static boolean showConfirmDialog(final String message) { public static boolean showConfirmDialog(final String message) {
@@ -46,16 +50,16 @@ public class SOptionPane {
} }
public static boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) { public static boolean showConfirmDialog(final String message, final String title, final String yesButtonText, final String noButtonText, final boolean defaultYes) {
final String[] options = {yesButtonText, noButtonText}; final List<String> options = ImmutableList.of(yesButtonText, noButtonText);
final int reply = SOptionPane.showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1); final int reply = SOptionPane.showOptionDialog(message, title, QUESTION_ICON, options, defaultYes ? 0 : 1);
return (reply == 0); return (reply == 0);
} }
public static int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options) { public static int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options) {
return showOptionDialog(message, title, icon, options, 0); return showOptionDialog(message, title, icon, options, 0);
} }
public static int showOptionDialog(final String message, final String title, final FSkinProp icon, final String[] options, final int defaultOption) { public static int showOptionDialog(final String message, final String title, final FSkinProp icon, final List<String> options, final int defaultOption) {
return GuiBase.getInterface().showOptionDialog(message, title, icon, options, defaultOption); return GuiBase.getInterface().showOptionDialog(message, title, icon, options, defaultOption);
} }
@@ -71,7 +75,7 @@ public class SOptionPane {
return showInputDialog(message, title, icon, initialInput, null); return showInputDialog(message, title, icon, initialInput, null);
} }
public static String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final String[] inputOptions) { public static String showInputDialog(final String message, final String title, final FSkinProp icon, final String initialInput, final List<String> inputOptions) {
return GuiBase.getInterface().showInputDialog(message, title, icon, initialInput, inputOptions); return GuiBase.getInterface().showInputDialog(message, title, icon, initialInput, inputOptions);
} }