Reputation: 2197
I just started to write the game of snakes in java. (See this if you don't know what that is: http://codeincomplete.com/projects/snakes/ or http://elgoog.im/snake/). 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 java.awt.Rectangle
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 JPanel
. Otherwise, if there is a better way to do this then let me know. Thanks.
Upvotes: 0
Views: 103
Reputation: 39698
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
mSnakePieces.add(mSnakePieces.length()-1,newSnakePiece);
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.
Upvotes: 4