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_engine/snake_engine.cpp
- Committer:
- weiway
- Date:
- 2018-05-08
- Revision:
- 22:6dce4175795a
- Parent:
- 21:7f7d09a27cc8
File content as of revision 22:6dce4175795a:
#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)) {
//audio feedback. From Pong.engine sample code.
pad.tone(1000.0,0.1);
return true;
} else {
return false;
}
}
//lcd print the point
void snake_engine::printpoint(N5110 &lcd)//From pong sample code
{
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.
//audio feedback. From pong.engine samplecode
pad.tone(1500.0,0.5);
}
}