ELEC2645 (2017/18) / Mbed OS el16ajm

Snek/Snek.cpp

Committer:
Andrew_M
Date:
2018-05-08
Revision:
17:2a909f7da973
Parent:
15:130900e5c268

File content as of revision 17:2a909f7da973:

#include "Snek.h"

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

}

Snek::~Snek()
{

}

void Snek::init(int x, int y)
{
    memset(_x, 0, sizeof(_x));  //clears the x coordinate array
    memset(_y, 0, sizeof(_y));  //clears the y coordinate array

    //Inital values for variables
    _length = 3;

    _oldDirection = 'N';

    for (int i = 0; i < _length; i++) { //sets the starting values for the snake coordinates
        _x[i] = x;                      //all have the same X coordinate
        _y[i] = y + i;                  //the Y coordinate is incremmented for each tail segment
    }
    
    printf("Snake Initialised\n");
}

void Snek::update(Direction d)
{
    for (int i = _length-1; i >= 1; i--) {
        _x[i] =  _x[i-1];
        _y[i] =  _y[i-1];
    }

    if (d == N && _oldDirection != 'S') {   //checks the new direction so the snake cannot go back on itself
        _y[0] -= 1;                         //changes a coordinate of the snake's head
        _oldDirection = 'N';                //updates the _oldDirection so the snake will travel in the new direction with no play input
        printf("Snake has changed North\n");
    } else if (d == S && _oldDirection != 'N') {
        _y[0] += 1;
        _oldDirection = 'S';
        printf("Snake has changed South\n");
    } else if (d == E && _oldDirection != 'W') {
        _x[0] += 1;
        _oldDirection = 'E';
        printf("Snake has changed East\n");
    }   else if (d == W && _oldDirection != 'E') {
        _x[0] -= 1;
        _oldDirection = 'W';
        printf("Snake has changed West\n");
    } else {                                //if there is no player input (new direction)...
        if (_oldDirection == 'N') {         //checks the old direction...
            _y[0] -= 1;                     //and changes a coordinate of the snake's head depending on the _oldDirection
        } else if (_oldDirection == 'S') {
            _y[0] += 1;
        } else if (_oldDirection == 'E') {
            _x[0] += 1;
        }  else if (_oldDirection == 'W') {
            _x[0] -= 1;
        }
        printf("Snake hasn't changed direction\n");
    }
}

int Snek::getX(int ref)
{
    return _x[ref];
}

int Snek::getY(int ref)
{
    return _y[ref];
}

int Snek::getLength()
{
    return _length;
}

void Snek::grow()
{
    _length+=1;  //increments the length of the snake
    printf("Snake has grown\n");
}