Ashwin Gupta Ashwin Gupta - 2 years ago 111
Java Question

Java- How to link AWT Rectangles?

I just started to write the game of snakes in java. (See this if you don't know what that is: or So, when the snake eats an object, its tail grows. In order for the turning physics of the game to work properly, each segment of the tail needs to have its own

hitbox. My question is how can I link these hitboxes/segments of his tail so they always stay together, but are seperate components on my
. Otherwise, if there is a better way to do this then let me know. Thanks.

Answer Source

There s should be a snake object, with a ordered set of simple snake piece, each piece showing type. Practice model view controller, each Snake piece should know nothing about graphics. When you at a segment, put by the last noon trail piece. So, your Snake would contain a list of pieces, like this:

List<SnakePieces> mPieces

SnakePieces should be simple, something like this

public class SnakePieces {
    public enum Type {Head,Body,Tail};
    public Type type;

Feel free to add other functions to SnakePieces as required. When you add a new piece, add it at the location


If you can, separate out the model (Snake movement), the view (Puts in the graphics for the piece depending on the type of SnakePiece), and the Controller (Feeds the inputs to the model). That's more advanced than required, but helpful. See Wikipedia on Model View Controller.

Also, see the Android Snake Game, which no doubt has some similarities to your application. Android does it via this:

 * mSnakeTrail: a list of Coordinates that make up the snake's body
 * mAppleList: the secret location of the juicy apples the snake craves.
private ArrayList<Coordinate> mSnakeTrail = new ArrayList<Coordinate>();

It just knows to draw the first and last tiles slightly differently.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download