Game Development Reference
In-Depth Information
We need to start at the last part in the list, as counterintuitive as that may sound. We move it to
the position of the part before it, and we repeat this for all other parts in the list, except for the
head, as there's no part before it. In the case of the head, we check which direction Mr. Nom is
currently heading and modify the head's position accordingly. Figure 6-7 illustrates this with a bit
more complicated configuration of Mr. Nom.
Figure 6-7. Mr. Nom advancing and taking his tail with him
This movement strategy works well with our eating strategy. When we add a new part to Mr.
Nom, it will stay at the same position as the part before it the next time Mr. Nom moves. Also,
note that this will allow us to implement wrapping Mr. Nom easily to the other side of the world
if he passes one of the edges. We just set the head's position accordingly, and the rest is done
automatically.
With all this information, we can now implement the Snake class representing Mr. Nom. Listing 6-10
shows the code.
Listing 6-10. Snake.java; Mr. Nom in Code
package com.badlogic.androidgames.mrnom;
import java.util.ArrayList;
import java.util.List;
public class Snake {
public static final int UP = 0;
public static final int LEFT = 1;
public static final int DOWN = 2;
public static final int RIGHT = 3;
public List < SnakePart > parts = new ArrayList < SnakePart > ();
public int direction;
We start off by defining a couple of constants that encode the direction of Mr. Nom. Remember
that Mr. Nom can only turn left and right, so the way we define the constants' values is
critical. It will later allow us to rotate the direction easily by plus and minus 90 degrees, just by
incrementing and decrementing the current direction of the constant by one.
Search WWH ::




Custom Search