我有 24 张卡片,您可以从中选择 6 张。如果您选择一张卡片,您有 6 个不同的位置可以放置该卡片(每张可选卡片一个)。
您将如何在 java
中编写代码,以便:
我尝试使用数组列表,将这些点的状态作为数字,以及已经选择的卡片(作为数字)。 然而,这会得到很多代码,因此应用程序非常慢......
所以我的问题是:实现这样的套牌选择应用的最佳和有效方法是什么?
答案 0 :(得分:2)
我试着记住 oop,这可能是你如何实现拿牌的逻辑,它看起来像很多代码,但这就是 java 的方式
// i don't know what Card should have in your game so it's empty
public static class Card {}
public static class Deck {
// cards are private as accessing card slots directly would defy purpose of deck
private final CardSlot[] cards;
public Deck(Card ...cards) {
this.cards = new CardSlot[cards.length];
for(int i = 0; i < cards.length; i++) {
this.cards[i] = new CardSlot(cards[i]);
}
}
// there are multiple options how things can go wrong so we are throwing exceptions
public Card takeCard(int pos) throws IndexOutOfBoundsException, IllegalAccessException {
if(pos < 0 || pos >= cards.length) {
throw new IndexOutOfBoundsException("you have to pull card from this deck");
}
if(cards[pos].taken) {
throw new IllegalAccessException("card is already taken");
}
cards[pos].taken = true;
return cards[pos].card;
}
private static class CardSlot {
boolean taken;
Card card;
public CardSlot(Card card) {
this.card = card;
}
}
}
public static class Hand {
// hand size should not change during game (or should depends on your game so final is optional)
public final int size;
// again exposing cards would defeat purpose of Hand class
private Card[] cards;
public Hand(int size) {
this.size = size;
}
// same as for deck we use exceptions
public void addCard(int pos, Card card) throws IndexOutOfBoundsException, IllegalAccessException {
if(pos < 0 || pos >= cards.length) {
throw new IndexOutOfBoundsException("you have to put card into your hand");
}
if(cards[pos] == null) {
throw new IllegalAccessException("card slot if already taken");
}
cards[pos] = card;
}
// try implement this
public Card getCard(int pos) {
return null;
}
}
public static void main(String[] args){
Deck deck = new Deck(new Card(),/* enumerate all cards here */ new Card(), new Card());
Hand hand = new Hand(6);
// though avoid nesting try catch if possible
try{
Card card = deck.takeCard(3);
try{
hand.addCard(1, card);
} catch(IllegalAccessException e) {
// handle exception, ask to insert card again
} catch(IndexOutOfBoundsException e) {
// same here
}
} catch (IllegalAccessException e){
// handle exception, ask to takeCard again
} catch (IndexOutOfBoundsException e) {
// same here
}
}