Reputation: 1332
I write my own Snake-game, where Snake is ArrayList of Points
and I use this method to check self-eating:
public void checkSelfEating() {
for (int i = 1; i < body.size(); i++) {
if (body.get(i).equals(body.get(0))) {
sgv.setGameOverState(true);
sgv.setMessage("Game over!");
System.out.println("SelfEatingdetected");
}
}
}
But it is too slow, and snake do about 5 moves until game is over. Is there a better solution?
Upvotes: 2
Views: 243
Reputation: 60818
Store the body units in a HashSet
via add
and remove
calls. O(1)
. Furthermore if you use a LinkedHashSet
it will be very easy to manage the head and tail (per comment).
This all being said, while this is the correct data structure and answers your question, I have absolutely no idea why having to do a for loop over a few dozen elements or so is making your program so horribly slow. I strongly recommend profiling and finding the actual bottleneck as I'm not even sure a hash set will be faster at this scale.
Upvotes: 3