Snake
3 Making The Snake Grow

Section Menu

Snake Home | 1 | 2 | 3 | 4 | 5

The snake is supposed to get longer each time it eats one of the munchies. Start by creating a sprite and solid object for the munchie graphic. Add the munchie to the room somewhere out of the way of the snake.

Create a sound using the ping sound file and call it snd_ping.

Now return to the object window for the snake head. Add a Collision Event with the munchie object and drag in a Play Sound action to play the ping noise when the munchie is eaten. You should also think about increasing the score at this point.

Now add an Execute Code action and fill in the code window as follows,

do
   {
   X:=16*floor(random(room_width/16));
   Y:=16*floor(random(room_height/16));
   }
until place_free(X,Y)
obj_munch.x = X;
obj_munch.y = Y;
room_speed += 0.2;
alarm[0] = 1;

The do ... until structure is used to find random coordinates that do not currently contain an object. When it finishes, the munchie object is moved to that location on the screen. The room speed is increased by 0.2, which will make the game get slightly quicker as more munchies are eaten by the snake. The last line calls the alarm event which will add another part to the body.

Screen Wrapping

At the moment, our snake can be directed off the screen. At a later point, we might add some blocks around the edge and a collision event to stop the snake hitting them. You may wish to have gaps however where the snake can go off one edge of the screen and return through the other.

Add an Outside Room Event to the snake head object window. Drag in an Execute Code action and type in the following statements,

if (x < 0) x = room_width + sprite_xoffset;
if (x > room_width) x = -sprite_width + sprite_xoffset;
if (y < 0) y = room_height + sprite_yoffset;
if (y > room_height) y = -sprite_height + sprite_yoffset;

Each line checks the location of the snake head. Depending on which edge of the screen the snake left, it will reappear at the other side. The sprite offset is added to account for the size of the sprite.

Save the work done so far and test the game to make sure these changes work.

⇐ Previous | Next ⇒