如果您的动作范围非常有限(例如,涉及金钱、移动格子等的 2 或 3 个动作),那么我可能会使用以下类:
class Card {
// It would be a good practice to not make the following fields
// public and use getters/setters instead but I've made them this
// way just for illustration purposes
public String text;
public String action;
public int value;
Card(String text, String action, int value) {
this.text = text;
this.action = action;
this.value = value;
}
}
这样(正如其他一些答案已经指出的那样),您可以使用Cards 的数组而不是Strings 的数组。然后,您可以在一个字段中包含文本,在单独的字段中包含操作,在第三个字段中包含与该操作关联的值。例如,您可能有以下卡片:
Card lose25 = new Card("You lose $25", "money", -25);
Card move5squares = new Card("Move 5 squares ahead!", "move", 5);
当您“处理”卡片时,您可以通过以下方式进行:
...
if (card.action.equals("money") {
// Update user's money with card.value
} else if (card.action.equals("move") {
// Update user's position with card.value
} else if (card.action.equals("...") {
// and so on...
}
...
编辑:
如果卡片可以包含多个操作,您可以使用 HashMap 来存储该卡片的操作:
class Card {
public String text;
public HashMap<String, Integer> actions;
Card(String text) {
this.text = text;
actions = new HashMap<String, Integer>();
}
addAction(String action, int value) {
actions.put(action, value);
}
}
HashMap 是一个可以存储键值对的集合。所以对于一张有 2 个动作的卡片,你可以使用上面的代码:
Card aCard = new Card("Lose $25 and move back 3 spaces!");
aCard.addAction("money", -25);
aCard.addAction("move", -3);
现在,当您实际处理卡片时,您需要检查HashMap 以了解存储在此卡片中的所有操作。遍历HashMap 的一种方法是执行以下操作:
Card processCard = ...;
for (Map.Entry<String, Integer> entry : processCard.actions.entrySet()) {
// This loop will get each 'action' and 'value' that you added to
// the HashSet for this card and process it.
String action = entry.getKey();
int value = entry.getValue();
// Add the earlier 'card processing' code here...
if (action.equals("money") {
// Update user's money with value
} else if (action.equals("move") {
// Update user's position with value
} else if (action.equals("...") {
// and so on...
}
}