I am creating the basis for a card game right now, I am doing just some basic functions for cards. I want to shuffle the cards, but don't know how to write the function for it. It will be called in the main program here is the deck class I have so far:
import java.awt.*;
import javax.swing.*;
import java.awt.event.* ; //capture mouse events
import java.awt.Graphics ;
import java.awt.Event;
import java.util.Random;
public class Deck
{
private Random random = new Random ();
protected Card cards[] = new Card[52] ;
protected int numcards = 0;
public Deck()
{
int i = 0;
for (int s = 1; s<5 ; s++)
{
for (int n=1; n<14 ; n++)
{
cards[i] = new Card(n,s);
i++;
numcards = numcards + 1;
}
}
}
public void giveCard(Deck p)
{
numcards = numcards - 1;
p.takeCard(cards[numcards]);
return;
}
public void takeCard(Card c)
{
cards[numcards] = c;
numcards = numcards + 1;
}
public void shuffle ()
{
int temp;
for (int i = 0; i<52; i++)
{
//cards[i] = temp ;
}
}
public void draw (Container c ,Graphics g, int x , int y )
{
for (int i = 0; i<numcards; i++)
{
cards[i].draw(c, g, x+i*20,y) ;
}
}
}
If you change your
Card[]
intoList<Card>
instead, you can simply useCollections.shuffle(cards)
. Otherwise, loop through the array, at each point, swap the current card with a randomly selected card.