ELEC2645 (2017/18) / Mbed 2 deprecated el15ww

Dependencies:   mbed

snake_engine/snake_engine.cpp

Committer:
weiway
Date:
2018-05-08
Revision:
20:980b37fde361
Parent:
18:e58a1f8e72ad
Child:
21:7f7d09a27cc8

File content as of revision 20:980b37fde361:

#include "snake_engine.h"

snake_engine::snake_engine()
{
  clision = 0;// 0 means there is no collision
}

snake_engine::~snake_engine()
{
}

void snake_engine::init()
{
    s.init();

}
//draw the snake , fruit , and point
void snake_engine::draw(N5110 &lcd)
{
        lcd.refresh();
        lcd.clear();
        lcd.drawRect(0,8,WIDTH ,HEIGHT -8,FILL_TRANSPARENT);  // the squre on the screen  

    s.draw(lcd);
    f.draw(lcd);
    printpoint(lcd);
}


void snake_engine::update(Gamepad &pad, N5110 &lcd)//update the game
{
    s.update(_d,_mag); //update direction of snake
    collision(pad, lcd);//update collision
  

    if(getfruit(pad)) {//boolean value. return ture and false
        f.reborn(); //reborn randomly the fruit when the old fruit is ate by snake 
        s.point(); //update the point 
        
    }
}

//read the command from gamepad. From Pong sample code
void snake_engine::read_input(Gamepad &pad)
{
    _d = pad.get_direction();
    _mag = pad.get_mag();
}


bool snake_engine::getfruit(Gamepad &pad)//boolean function. if the snake eat fruit . returns true, else false.
{
    Vector2D _f_pos = f.get_pos();
    Vector2D _s_pos = s.get_pos();

    if ((_f_pos.y >= _s_pos.y || _f_pos.y == _s_pos.y-1) &&
            (_f_pos.y <= _s_pos.y || _f_pos.y+1 == _s_pos.y-1) &&
            (_f_pos.x >= _s_pos.x || _f_pos.x+1 >= _s_pos.x || _f_pos.x+1 >= _s_pos.x ) &&
            (_f_pos.x <= _s_pos.x || _f_pos.x+1 <= _s_pos.x)) { 
        
        return true;
    } else {
        return false;
    }
}

 
//lcd print the point
void snake_engine::printpoint(N5110 &lcd)
{
    int snakepoint = s.get_point();// from the snake function,  get the points 
    char buffer[14];
    sprintf(buffer,"%2d",snakepoint);
    lcd.printString(buffer,WIDTH/2 - 40,0); //print the point on the left top corner on the screen
}




void snake_engine::collision(Gamepad &pad,N5110 &lcd)//check whether the snake hit the wall or not.
{
    Vector2D _s_poss = s.get_pos();
        if (((_s_poss.x >= WIDTH -2) || (_s_poss.x <= 1)) ||((_s_poss.y >= HEIGHT -1) || (_s_poss.y <= 8))  ) {
            lcd.clear(); 
                 clision = 1;//if the snake position on X and Y equal to the wall. then it happens. clision = 1.
    }
   
}