I would suggest you setup an array of Cards, rather than 52 seperate Cards. Or load the data from a seperate flat file
It would be best to actually subclass ArrayList or List and make your own Deck object.
There is many ways to shuffle the Deck. You could generate a few random numbers (between 1 to 52), which will be used to deal the next bunch of cards. Or you could actually devise some type of formula to grab random indexes and swap them over.
Hrmm, the instructions specifically say to make a deck of 52 card objects. :O
So, am I doing that correctly? Because I have a knack to not follow directions properly. Heheh.
Hrm, about that formula to swap a few cards in and out. Hrm. Argh, that's hard to think of. I wish the ArrayList class had a method to randomize the indexes.
that is a lot of code. holy night. If i get a chance later i will post the code that is in my java book, that has code for shuffling cards. And no offense, but its a lil easier to read, and smaller
What I like to do is write two versions of the assignment or task; one to the lecturer's specifications and one to my specifications. Pretty sad, but it seems to pay off.
ArrayList deck=new ArrayList(); //the deck
Card cards[]=new Card[52]; //array to keep the cards in
for(int i=0; i<4; i++) {
for(int j=0; j<13; j++) {
cards[i*13+j]=new Card(j+1, i+1); //create the card
deck.add(cards[i*13+j]); //add that card object to the deck
}
}
In that manner, your card1 is the same as cards[0], and so on. As for randomizing it, perform a bunch of random swaps
Code:
for(int i=0; i<26; i++) {
//choose 2 random elements to swap
int swapIndex1=(int)Math.floor(Math.random()*52);
if(swapIndex1==52) swapIndex1--;
int swapIndex2=(int)Math.floor(Math.random()*52);
if(swapIndex2==52) swapIndex2--;
//swap them
Object tmp=deck.get(swapIndex1);
deck.set(swapIndex1, deck.get(swapIndex2));
deck.set(swapIndex2, tmp);
}
Kids, kids... you tried your best, and you failed miserably; the lesson is: never try.
BuezaWebDev, implementing a shuffle without keeping all the Card objects in an array is going to be damn near impossible.
Though I would implement the shuffle in this way ...
Code:
protected static final Random generator = new Random();
protected static void shuffle(Object[] a)
{
int i, j;
for (i = 0; i < a.length; ++i) {
j = generator.nextInt(a.length);
swap(a, i, j);
}
}
protected static void swap(Object[] a, int m, int n)
{
Object t;
t = a[m];
a[m] = a[n];
a[n] = t;
}
This method of shuffling iterates a number of times proportional to the size of the array, and it guarentees that every element is swapped at least once.
Bookmarks