Reputation: 1
I've written some code to create an ArrayList of cards I downloaded, and now am trying to shuffle them and then display them by using the paint method. How would I display ten cards using the g.drawImage?
import java.awt.Image;
import java.applet.Applet;
import java.util.*;
public class DeckofCards1 extends Applet {
public void init ( ) {
String[] suits = {"c", "s", "h", "d"};
String[] values = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "j", "q", "k"};
ArrayList<Image> images = new ArrayList<Image>( );
for(String suit : suits){
for(String value : values){
Image img = getImage ( getDocumentBase ( ), "images/" + suit + value + ".gif" );
images.add(img);
}
}
Collections.shuffle ( images ); //get ten cards randomly?
}
public void paint ( Graphics g ) { //display ten cards here?
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 10, this );
g.drawImage ( img, 10, 30, this ); //what goes in place of img (which I know isn't right, simply a placeholder for now
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );
g.drawImage ( img, 10, 30, this );
}
}
Upvotes: 0
Views: 1116
Reputation: 695
I had a quick look and it seems like you can use this piece of code to get img:
BufferedImage img = ImageIO.read(imageSrc);
Source: http://docs.oracle.com/javase/tutorial/2d/images/drawimage.html
Also, depending on where you want to draw those images, you can probably put it into a loop and control the coordinates using the loop variables.
Make images a variable within your class (so you can use it in the paint function).
public class DeckofCards1 extends Applet {
private ArrayList<Image> images;
....
In your init function, change the Image creation line from
Image img = getImage ( getDocumentBase ( ), "images/" + suit + value + ".gif");
to
BufferedImage img = ImageIO.read(new File("images/" + suit + value + ".gif"));
In your paint function, change it so that it loops through the images array and for each, draws it using this
for(int i = 0; i < images.size(); i++) {
g.drawImage(images.get(i), i*10, i*10, null);
}
Check out this pastebin for an updated version of your code that should compile if you have the images: http://pastebin.com/43t7zhYL
Updated pastebin using a different image read method: http://pastebin.com/15tigYFd
Upvotes: 1
Reputation: 312
Concerning shuffling, Collections.shuffle ( images );
will permute the elements of images
randomly. But I recommand adding this line :
private final Random random = new Random(4454776669L);
and using Collections.shuffle ( images, random);
instead. Here the number 4454776669L is a seed for the pseudorandom number generator, and when you use the same seed you reproduce the same sequence of random numbers, which can be useful if you want to reproduce the same game or just for debugging purposes.
Upvotes: 1