Samuel Lashmar 201170334

Dependencies:   mbed

SnakeHead/SnakeHead.cpp

Committer:
sdlashmar
Date:
2020-05-24
Revision:
14:4356797fd16e
Parent:
12:cb3a81adf48b

File content as of revision 14:4356797fd16e:

#include "SnakeHead.h"


SnakeHead::SnakeHead()
{

}

SnakeHead::~SnakeHead()
{
    
}

void SnakeHead::init(int size, int speed) {
    //initialises head size and speed
    _size = size*2;
    _speed = speed;
    //head starts in centre of screen
    _x = WIDTH/2 - _size/2;
    _y = HEIGHT/2 - _size/2;
    //generates random number between 0 and 3
    srand(time(NULL));
    int direction = rand() %3;
    //sets initial direction of snake from the random number generated 
    if (direction == 0) { //snake moves north
        _velocity.x = -_speed;
        _velocity.y = 0;
        }
    else if (direction == 1) { //snake moves east
        _velocity.x = 0;
        _velocity.y = _speed;
        }
    else if (direction == 2) { //snake moves south
        _velocity.x = _speed;
        _velocity.y = 0;
        }
    else if (direction == 3){ //snake moves west
        _velocity.x = 0;
        _velocity.y = -_speed;
        }
}

void SnakeHead::draw(N5110 &lcd) {
    
    lcd.drawRect(_x,_y,_size,2,FILL_BLACK);
}

void SnakeHead::update() {

    _x += _velocity.x;
    _y += _velocity.y;
    /* wall collision debugging
    if (_x < 0) {
        _x = 1;
    } else if (_x > 84) {
        _x = 84 - _size;
    } else if (_y < 0) {
        _y = 1;
    } else if (_y > 48) {
        _y = 48 - _size;
    } */
    //printf("head x = %i\n", _x);
    //printf("head y = %i\n", _y);
}

void SnakeHead::change_direction(Direction d) {
        //changes direction of the head based on the direction of the joystick
        if (d == N) {
            _velocity.x = 0;
            _velocity.y = -_speed;
        } else if (d == E) {
            _velocity.x = _speed;
            _velocity.y = 0;
        } else if (d == S) {
            _velocity.x = 0;
            _velocity.y = _speed;
        } else if (d == W) {
            _velocity.x = -_speed;
            _velocity.y = 0;
        }
        
}

void SnakeHead::set_velocity(Vector2D v) {
    _velocity.x = v.x;
    _velocity.y = v.y;
}



Vector2D SnakeHead::get_velocity() {

    Vector2D v = {_velocity.x, _velocity.y};
    return v;
}

Vector2D SnakeHead::get_pos() {
        
        Vector2D p = {_x, _y};
        return p;
}

void SnakeHead::set_pos(Vector2D p) {
    
        _x = p.x;
        _y = p.y;
}