0

I am writing a card game in java where I need to spread cards from a deck into several columns until I have fixed amount of cards left. This is how I do this.

public class Column extends ArrayList {}
List deck = Cards.createNewDeck();
Column[] columns = new Column[10];
int c = 0;

while (deck.size() > 50) {
    if (c == 10) {
        c = 0;
    }
    if (columns[c] == null) {
        columns[c] = new Column();
    }
    columns[c].add(Cards.dealTopCard(deck));
    c += 1;
}

This somehow seems clunky. Is there a more readable/comprehensive way of doing the same thing?

2 Answers 2

1
public class Column extends ArrayList {}
List deck = Cards.createNewDeck();
Column[] columns = new Column[10];
int c = 0;

for (int i = 0; deck.size() > 50; i = (i+1)%10)
{
  if (columns[i] == null)
    columns[i] = new Column();

  columns[i].add(Cards.dealTopCard(deck));
}

The modulo (%) operator gives the remainder of the integer division between the two numbers effectively giving you a number that goes back to 0 when reaching 10.

By the way you should decide: use a bidimensional array or just ArrayLists, don't mix things.

Then since generics do exist, use them instead that extending classes: that's what parametric polymorphism is for! Something like:

ArrayList<Int, ArrayList<Card>> columns = new ArrayList<ArrayList<Card>>();
Sign up to request clarification or add additional context in comments.

2 Comments

Well, array of lists seemed to be the best approach. I have a fixed number of columns, but I don't know how many cards will be in each column. A list of lists is a bit more verbose (columns[i] vs. columns.get(i)). Your example is nice, but I was looking for something more profound. In clojure I would write something like (def columns (partition 10 10 (list) (take 54 (create-deck)))
Unfortunately this is Java, not Clojure :) Verbosity is quite part of the game.
0
  • Don't use raw types.
  • Don't mix arrays with lists.

My suggestion is to define List<Pile<Card>> columns, where Pile<Card> has a List<Card>.

Then define a dealer type that converts a Deck<Card> into multiple Pile<Card>. That makes it easier to plug in different deck-to-piles strategies just in case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.