XJEL2645 (18/19) / Mbed 2 deprecated 2645_Mygame

Dependencies:   mbed Gamepad N5110

snake/snake.cpp

Committer:
694617778
Date:
2019-04-14
Revision:
7:d61290faf602
Parent:
6:feb6351e6f8e
Child:
9:18b059e5abb9

File content as of revision 7:d61290faf602:

#include "snake.h"

// nothing doing in the constructor and destructor
snake::snake()
{

}

snake::~snake()
{

}

void snake::init(int size,int length)
{
    _size = size;
    _length = length;
    for (int i = 0; i < 100;i++){
        _x[i] = 0;
        _y[i] = 0;
    }
    _x[0] = WIDTH/2 -  _size/2;
    _y[0] = HEIGHT/2 - _size/2;

    _x[1] = _x[0] -size;
    _y[1] = _y[0];
    
    _x[2] = _x[0] -2*size;
    _y[2] = _y[0];
     
    ball( _length);
    _score = 0;  // start score from zero
    over = 0;
}

int snake::get_length(){
    int d=_length;
    return d;
    }

void snake::update(int direction, int length)
{
    for(int k = length - 1; k > 0; k--){
    _x[k] = _x[k-1];
    _y[k] = _y[k-1];
    }
    if(direction == 0){
     _x[0] = _x[0] + _size;
     }else if(direction == 1){
         _y[0] = _y[0] + _size;
         }else if(direction == 2){
             _x[0] = _x[0] - _size;
             }else if(direction == 3){
                 _y[0] = _y[0] - _size;
    }
}
 

void snake::draw(N5110 &lcd, int length)
{

    // draw snake in screen buffer. 
        lcd.drawRect(0,0,WIDTH,HEIGHT,FILL_TRANSPARENT);
        lcd.drawRect(1,1,WIDTH-2,HEIGHT-2,FILL_TRANSPARENT);
        for (int i = 0; i < length; i++){
        lcd.drawRect(_x[i],_y[i],_size,_size,FILL_BLACK);
        }
        
    // draw ball in screen buffer.
        lcd.drawCircle(ball_x,ball_y,1,FILL_BLACK);
}

void snake::ball(int length)
{
    srand(time(NULL));
    ball_x = 3 + rand() % (WIDTH - 6); // randomise initial position of ball. 
    ball_y = 3 + rand() % (HEIGHT - 6);
    for (int i = 0; i < length; i++) {
        if(ball_x + _size > _x[i] && ball_x - _size < _x[i] && ball_y + _size > _y[i] && ball_y - _size < _y[i]){
                srand(time(NULL));
                ball_x = 3 + rand() % (WIDTH - 6); // randomise initial position of ball. 
                ball_y = 3 + rand() % (HEIGHT - 6);
            }
    }

}

void snake::check_eat(Gamepad &pad)
{
    //
    if (ball_x + _size >=  _x[0] && ball_x - _size <=  _x[0] && ball_y + _size >=  _y[0] && ball_y - _size <=  _y[0]) {
        _length++;
        _score++;
        ball(_length);
        pad.tone(1500.0,0.5);
        pad.leds_on();
        wait(0.05);
        pad.leds_off();
    }
}

void snake::check_over(N5110 &lcd)
{
    if ( _x[0] >= WIDTH - 2 | _x[0] <= 2 | _y[0] >= HEIGHT - 2 | _y[0] <= 2){
        over = 1;
        }
    for (int i = 1; i < _length; i++){
        if(_x[0] == _x[i] && _y[0] == _y[i]){
            over = 1;
            }
    }
}


int snake::get_score()
{
   return _score;
}