I need to create a program that will randomly roll 5 dice and then display the faces of these dice in a JPanel, just like a Yahtzee game. I have images of each die face and am having trouble trying to attach my randomly rolled number to an image. So for instance if the random number is 1 then it will display the die face 1 for five different faces. What I have below is my Die class, Panel class and my GameDrive in that order. Sorry for all the codes copied over and not sure if the driver is needed to solve this problem but dint know where the code needed to be written to work.
public class Die implements Comparator {
private int face;
public Die() {
super();
face = (int)(Math.random() * 6) + 1;
}
public Die(int f){
super();
face = f;
}
public int getFace() {
return face;
}
public void setFace(int face) {
this.face = face;
}
@Override
public String toString() {
return "Die [face=" + face + "]";
}
@Override
public boolean equals(Object obj) {
return (this.getFace() == ((Die)obj).getFace());
}
@Override
public int compare(Object a, Object b) {
Die d1 = (Die)a;
Die d2 = (Die)b;
if (d1.getFace() == d2.getFace())
return 0;
if (d1.getFace() > d2.getFace())
return 1;
return -1;
}
}
panel class
public class Panel extends JPanel {
private BufferedImage [] img = new BufferedImage [6];
private int w = 0, h = 0, xloc = 0, yloc = 0;
public Panel() {
super();
try {
img[0] = ImageIO.read(new File("Die1.jpg"));
img[1] = ImageIO.read(new File("Die2.jpg"));
img[2] = ImageIO.read(new File("Die3.jpg"));
img[3] = ImageIO.read(new File("Die4.jpg"));
img[4] = ImageIO.read(new File("Die5.jpg"));
img[5] = ImageIO.read(new File("Die6.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
this.setPreferredSize(new Dimension(1300, 600));
w = img[0].getWidth();
h = img[0].getHeight();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
xloc = 0;
yloc = 0;
for (BufferedImage i : img)
{
g.drawImage(i, xloc, yloc, w, h, null);
xloc += w;
}
yloc += h;
xloc = 0;
for (int i = 0; i < img.length; i++)
{
g.drawImage(img[i], xloc, yloc, w, h, null);
xloc += w;
}
}
}
driver
public class GameDriver {
public static void main(String[] args) {
Frame f = new Frame();
ArrayList<Die> roll = new ArrayList<Die>(5);
for (int i =0; i < 5; i++)
roll.add(new Die());
roll.sort(roll.get(0));
for (Die e : roll)
System.out.println(e);
}
}
Aucun commentaire:
Enregistrer un commentaire