Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: mbed
Snake/Snake.cpp
- Committer:
- sdlashmar
- Date:
- 2020-05-08
- Revision:
- 4:c5addc5475d3
- Parent:
- 3:36f9e3a75905
File content as of revision 4:c5addc5475d3:
#include "Snake.h"
Snake::Snake()
{
}
Snake::~Snake()
{
}
void Snake::init(int size, int speed) {
_size = size*2;
_speed = speed;
_x = WIDTH/2 - _size/2;
_y = HEIGHT/2 - _size/2;
srand(time(NULL));
int direction = rand() %4;
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) { //sake moves south
_velocity.x = _speed;
_velocity.y = 0;
}
else { //snake moves west
_velocity.x = 0;
_velocity.y = -_speed;
}
}
void Snake::draw(N5110 &lcd) {
lcd.drawRect(_x,_y,_size,_size,FILL_BLACK);
}
void Snake::update() {
_x += _velocity.x;
_y += _velocity.y;
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;
}
}
void Snake::change_direction(Direction d) {
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 Snake::set_velocity(Vector2D v) {
_velocity.x = v.x;
_velocity.y = v.y;
}
Vector2D Snake::get_velocity() {
Vector2D v = {_velocity.x, _velocity.y};
return v;
}
Vector2D Snake::get_pos() {
Vector2D p = {_x, _y};
return p;
}
void Snake::set_pos(Vector2D p) {
_x = p.x;
_y = p.y;
}