Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Snake game for tablets and Smartphones

4.91/5 (37 votes)
26 Jul 2012BSD8 min read 76.7K   7.2K  
This article shows how to create Snake game using Moscrif SDK.

 Image 1

Content  

Introduction 

The Snake game is a well-known game for mobile devices. The first time Snake made its debut was in 1997 and people usually know the game from Nokia 6110. Since then, this game changed many times and now it is time to adjust it for modern devices with touch display. Also, do not worry about different mobile platforms, because we are going to show you how it can be developed for multiple platforms with only one code.

The game overview

We all know what the goal of this game is but just to make sure that we are on the same page; the purpose is to feed the snake with food that appears randomly on the screen. To make this game slightly different from other snake games we added two types of food. The first smaller type of food adds ten points to your score, and the second larger type adds twenty points. The snake also becomes longer with every piece of food eaten.

Image 2small food - increase score by 10 points
Image 3large food - increase score by 20 points

System requirements  

Nowadays, the majority of mobile devices uses Andorid and iOS platform but there are still platforms like Bada OS or Windows Phone growing their market share. To cover the most of the devices available on the market, we used Moscrif SDK. Using Moscrif SDK, developers can create applications for iOS, Android and Bada OS with only one code base.

Our game has very small hardware requirements; and therefore, it even runs on devices with only 420MHz processor. It means that our game can run on low-end devices with low performing capabilities as well.

Graphic proposal

Every game design starts with ideas transformed into graphics proposal. It defines how the game should look like and what game objects it should contain. It also indicates the functionality of game. The game is friendly for all ages, because it does not use any controversial design but the colours work together in nice, eye-appealing fashion.

Image 4

Image: graphics proposal of our game

User interface

As you can see on the pictures above, the graphics show two parts of the game - introduction part, which is the first scene with menu and then the second scene, which is the actual game.

  • Menu - this is the introduction scene. It is displayed at the start or the end of the application and when the game is paused. Users can start a new game, continue in paused game or quit the application.
  • Game - this is the main scene where the game is played. It consists of sprite objects, which are spread on the game scene. Simply said, the snake moves on the screen and eats the food. Users can control snake by tapping the screen towards the direction where they want the snake to go.

Menu

The menu is the introduction scene. It is displayed when application starts and it enables the user to start new game, continue game (if it was paused) or quit the game. Due to Apple’s application policy of using quit button in applications, the button is not added to iOS version.

The menu is created by MenuScene class. It is extended from Scene class. When the instance of the class is created, init function is called. Menu scene class is overlaid by the parent’s init function. However, the parent init function is not called automatically, it is needed to call it by super.init() command to ensure correct object creation. Menu consist of three buttons which provide operation functionality: continue, new game or quit.

Image 5

Image: menu elements

All buttons are created by separate functions. However, as we mentioned before, make sure that quit button is not added to your iOS version. Apple will not accept it.

JavaScript
function init()
{
     super.init();
    
     this._computeScale();           // compute scale
     this._loadBg();                 // load background
     this._createContinueBttn();     // create continue button
     this._createTouchGameBttn();    // create new touch game button
     // check if application does not run on iOS
     if (System.OS_NAME != #iOS)
         this._createQuitGameBttn();     //create quit button
} 

Example: menu scene init function

The buttons are created as an instance of GameButton which has two states: pressed and „normal“. Both are placed in one source file as two frames. By default, the first frame is shown. When the button is pressed, the next frame is shown. The coordinates of one frame are set by frameWidth and frameHeight properties. GameButton also calls onClick event when tapped.

JavaScript
function _createTouchGameBttn()
{
     this._bNewGameTouch = new GameButton({image:M_NEW_GAME_TOUCH, frameWidth:327, frameHeight:66, scale : this._scale});
     this._bNewGameTouch.x = System.width/2;
     this._bNewGameTouch.y = this._bContinue.y + this._bContinue.scaledHeight + M_VERTICAL_SPACE;
     this._bNewGameTouch.onClick = function()
     {
         game.gameScene = new GameScene();
         game.push(game.gameScene, new SlideToLeft({duration:1000,transition:Animator.Transition.bouncy}));
         this super.showContinueBttn();
     }
     this.add(this._bNewGameTouch);
}

Example: _createTouchGameBttn shows how to create a game button

The added buttons are drawn automatically by Scene class. However, the background has to be drawn manually in draw function. Background image has been already loaded in init function. Also, parent’s draw function has to be called in draw function, because it draws added buttons and other elements.

JavaScript
function draw(canvas)
{
     // draw background scene
     canvas.drawBitmap(this._background, 0, 0);
     // call draw function on other objects in scene
     super.draw(canvas);
}

Example: draw function

Game

Game consists of many parts like snake, food, various buttons etc. It also has many functionalities like contact detection or food distribution. The base for all objects and functionalities is Game Scene class.

Image 6

Image: game elements

Game scene consists of background, menu button, score, snake and drops (snake's food). In init function we create all needed objects and create initial drops distribution.

JavaScript
function init()
{
     super.init();

     this._initVariables();  // init helper variables
     this._loadBg();         // load background image
     this._createMenuBttn(); // create and add to the scene menu button
     this._createScore();    // create and andd to the scene score
     this._loadStage();      // load stage from xml
     this._createBigDrops(); // create and distribute big drops
     this._createDrops();    // create and distribute drops
     this._createSnake();    // create snake object
}

Example: init function to create all needed objects

Function _createDrops distributes drops to the playground. The drops are distributed into random positions. However, we have to ensure that two foods will not overlap.

Firstly, we create new Drop object. Then - in while cycle - we try to find a location on the screen where our object isn’t in collision with any others. We get random position by function rand(Integer). We must detect, if there isn’t a collision with other objects. If everything is ok, we can jump from while cycle by using Stop variable. At the end, we add the drop to the our array this.food and to the scene.

JavaScript
function _createDrops()
{
     for (var i = 0; i < this.stage.drop_count; i++) {
         var b = new Drop();
         // Random position
         var stop = false;
         while (!stop) {
             stop = true;
             b.x = (1+rand(this.width/b.width-2))*b.width-10;
             b.y = (1+rand(this.height/b.height-2))*b.height-10;

             for (var i in this.food)
                 if (b.intersectsBounds(i))
                     stop = false;
         }
         // Add object to the container
         this.food.push(b);
         this.add(b);
     }
}

Example: distribute drops to random positions

Game scene has only one button which allows the users to return to the game menu. It is also created by GameButton class. Another UI element is score indicator.

Score  

Score is an important feature, which makes the game more challenging. In this game, the score depends on number and type of foods eaten and the target is to achieve the highest score without coming to contact with wall or part of the snake.

How to calculate the score?  

Score is recalculated each time the snake eats the food. We can take into consideration that the snake's head is the part eating the food. All the food distributed on the screen was pushed to one array called food. Having access to all food objects and also to the snake head allows us to check whether the food was eaten or not. We need to check if there is any food under the head by intersectsBounds function.

JavaScript
/**
Check intersects by object
@param Gameobject obj
@return Boolean
*/
function intersectsBounds(obj)
{
     assert obj instanceof GameObject;
     var tx = this._x;
     var ty = this._y;
     var ox = obj._x;
     var oy = obj._y;
     return (
         tx + this.width > ox && tx < ox + obj.width &&
         ty + this.height > oy && ty < oy + obj.height
     );
}

Example: intersectsBounds function - checks if objects overlap

Once we are able to check if objects overlap, it is easy to call this function for all food objects. The best place to do it is in onProcess event, where movement is managed as well. If the head overlaps with some food, we increase the value of score property (containing current score) by the value of food eaten.

JavaScript
/**
Event called within Scene onProcess
@param GameScene sender
*/
function onProcess(sender)
{
     ...
     // Check collisions with other parts of snake
     for (var b in sender.snake.body)
         if (this.intersectsBounds(b))
             sender.endGame();
        
     // Check collisions with food
     for (var f in sender.food)
         if (this.intersectsBounds(f)) {
             // Set new random positions
             var stop = false;
             while (!stop) {
                 stop = true;
                 f.x = (1+rand(sender.width/CELL_WIDTH-2))*CELL_WIDTH -10;
                 f.y = (1+rand(sender.height/CELL_HEIGHT-2))*CELL_HEIGHT -10;
                 for (var i in sender.food)
                     if (f != i && f.intersectsBounds(i))
                          stop = false;
                 for (var i in sender.walls)
                     if (f.intersectsBounds(i))
                         stop = false;
             }
             sender.snake.addPart(); // Add new part to the body.
             if (sender.score.value < 300)
                 sender.snake.timer.sleep -= f.speedValue; // It will be more often call method onProcess and snake will be faster.
             sender.score.value += f.score;
             break;
      }
      ...
    }

Example: Heat.intersectsBounds function - checks if objects overlap

Snake

Snake is the main game character and its movement is controlled by tapping on the screen.

Snake consists of sprite objects Head, Body and Tail, which have common parent Part. Class Part extends class Sprite with property direction, which is used to describe every snake’s part. It is a very important property, because it defines the movement direction. Snake class synchronises these objects with the help of Delay and Switch objects.

Snake class creates mentioned objects in constructor. Function addParts(count) creates and saves Body objects into array.

JavaScript
function this(x, y, count, direction)
{
     this.body = []; //Array for save snake's parts

     // Create Timer
     this.timer = new Delay();

     // Create Switch
     this._switch = new Switch(this);

     // Create head
     this.head = new Head(); //snake's head
     this.head.x = x;
     this.head.y = y;

     // Create tail
     this.tail = new Tail();
     this.tail.x = x;
     this.tail.y = y;
     this.tail.back(); // move with tail about one position back

     this.direction = direction;

     this.addParts(count);
}

Example: Snake constructor

Snake consists of body parts (and there can be plenty of body parts), which means that the snake turns gradually. First it turns its head, then it turns the first body part, second body part etc., and at last it turns the tail. These parts, including the head and then tail can turn on more than one place.

Every time the user taps on the screen (and the game is active) the turnTouch(x,y) function is called. This function first checks whether the snake (its head) is currently moving horizontally or vertically. If it is moving horizontally, it checks whether the user tapped above or below the snake’s head. If user taps above the snake head, it goes up. If user taps under the snake head, it goes down. The same process takes place if the snake moves horizontally.

Image 7

Image: function turnTouch

JavaScript
/**
Change direction of snake by x, y coordinates.
@param x int
@param y int
*/
function turnTouch(x,y)
{
     if (this.direction == #left || this.direction == #right) {
         if (y<this.head.y) this.direction="#up;">this.head.y)
             this.direction = #down;
     }

     else if (this.direction == #up || this.direction == #down) {
         if (x<this.head.x) this.direction="#left;">this.head.x)
             this.direction = #right;
     }
}
</this.head.x)></this.head.y)>

Example: function turnTouch

The direction property adds new edge into switch object. The edge allows the snake to make a turn at the place where the edge is placed.

JavaScript
/**
Property direction.
@get return direction of snake
@set set direction in head and add change direction to the switch
*/
property direction(value)
{
     get return this.head.direction;
     set {
         if (this.direction == #left && value == #up)
             this._switch.addEdge(#left_up);
         if (this.direction == #left && value == #down)
             this._switch.addEdge(#left_down);
         ...
             this._switch.addEdge(#down_right);
         this.head.direction = value;
         this._switch.add(value); // Change directions in the rest of the snake
     }
}

Example: direction property

Switch

The switch object manages snake’s turning. Every time the snake is making a turn, the edge is placed.The addEdge function only places new SwitchItem into an array in Switch object.
JavaScript
/**
Add switcher, which change image of part to edge image.
@param direction symbol
*/
function addEdge(direction)
{
     this.array.push(new SwitchItem(direction, 0))
}

Example: addEdge function

Edges are set in place where the snake should turn. Turning is managed by Refresh function of Switch object. This function is called every time when snake moves from snake object onProcess function. This function applies all the edges and also removes the edges if they are not needed anymore. Its behavior is shown in next image.

Image 8

Image: Refresh function behavior

The code of refresh function is really simple:

JavaScript
/**
It is loop which should call in onProccess function.
*/
function refresh()
{
     var del = 0;
     var j = 0;
     // go throw all edges (SwitchItems) in the array
     for (var i in this.array) {

         var it = i.next();
         if (it==this.snake.body.length)
             del++;
         else if (it >= 0) {
             // apply directory to the body
             this.snake.body[it].direction = i.direction;
             }

         j++;
     }
     if (del > 0) // delete switchs which are on the end
         for (var i = 0; i < del; i++) {
             this.snake.tail.direction = this.array[0].direction;
             this.array.remove(0);
         }
}

Example: refresh function

Summary

Now you know how to create one of the most popular games in mobile industry by using Moscrif SDK. This will ensure that you decrease the amount of work and you will achieve the best results. Our project is focused on mobile phones and tablets with iOS, Andorid or Bada. The wide range of supported devices and resolution independence of this game opens huge market placement opportunities. Do not waste your time on developing applications separately for every mobile platform and try Moscrif cross platform development tool (available for free here).

More resources 

More samples, demos and information about Moscrif can be found on www.moscrif.com

License

This article, along with any associated source code and files, is licensed under The BSD License