Reputation: 2197
I have written a game of hangman and I would like to add some Java2D graphics too it. I am sure most people know this, but just in case let me make it explicit. In hangman, after each mistake a tiny little bit of a "hanging" stick figure is drawn until its complete.
Therefore, when I draw this the logical way is to run a for
loop and draw as many components as there are mistakes. Since I know what order I need to draw components in, I can loop through an array type in order for drawing. Now if I was just using java.awt.Rectangle
s than this would be easy, create an array of Rectangle
. However, since for hangman I also use one Ellipse2D
, I need a way to store both graphics components together in an array type format. What could I use to do this? (I have heard of ArrayLists but I don't really know how to use them at all and I believe you need to still specify an object type for these)
Example code would also be greatly apreciated. If this is impossible, let me know also, since I can just draw the head independently.
static int mistakes = 3;
static Ellipse2D head = new Ellipse2D.Double(420, 210, 160, 160);
static Rectangle torso = new Rectangle(3, 3, 3, 3);
static Rectangle leftArm = new Rectangle(3, 3, 3, 3);
static Rectangle rightArm = new Rectangle(3, 3, 3, 3);
static Rectangle leftLeg = new Rectangle(3, 3, 3, 3);
static Rectangle rightLeg = new Rectangle(3, 3, 3, 3);
Rectangle[] hangman = new Rectangle[5];
hangman[0] = torso;
hamgman[1] = leftArm;
//continue...
for(int i = 0; i < mistakes; i++) g2d.draw(hangman[i]); //but then the head is left out :(
Upvotes: 1
Views: 114
Reputation: 285403
You can use an array of Shape: [Shape]
say called shapes
, or an ArrayList<Shape>
and then fill it with Ellipse2D
, Rectangle2D
, Line2D
and similar objects. Note that to draw Shape derived objects, you will need to use a Graphics2D object, and so in your JPanel's paintComponent(Graphics g)
method, be sure to first cast the Graphics object to Graphics2D:
Graphics2D g2 = (Graphics2D) g;
Then your for loop can loop through your array, looping from 0 to errorCount (but making sure first that errorCount is never > array's length. e.g.,
Graphics2D g2 = (Graphics2D) g;
errorCount = Math.min(errorCount, shapes.length);
for (int i = 0; i < errorCount; i++) {
g2.draw(shapes[i]);
}
Upvotes: 1