Win an Ipad
  Developer   Demos & Samples   Snake

Snake

Screenshot
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.

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.

large food - increases score by 20 points
small food - increases score by 10 points

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: 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 game.

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: 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.


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.

function _createTouchGameBttn()
{
    this._bNewGameTouch = new GameButton({image:M_NEW_GAME_TOUCH, eWidth: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.


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 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.

/**
    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.

/**     Event called within Scene onProcess
    @param GameScene sender
*/
function onProcess(sender)
{
   ...
   
    // 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.

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: function turnTouch

/**
    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.direction = #up;
       if (y>this.head.y)
            this.direction = #down;
    }     else if (this.direction == #up || this.direction == #down) {
        if (x             this.direction = #left;
        if (x>this.head.x)
            this.direction = #right;
    }
}

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.

/**
     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.

/**
    Add switcher, which turns part image into 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: Refresh function behavior

The code of refresh function is really simple:

/**
    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).

 Breakout   Memory Cards (Pairs, ... 
Write a Comment (0)
Subject
Please complete this mandatory field.
HTML Tags Not Allowed!
Comment
Please complete this mandatory field.