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 Gamepad N5110
Diff: snake/snake.cpp
- Revision:
- 2:934daa65f73d
- Parent:
- 1:b49c36604125
- Child:
- 6:feb6351e6f8e
--- a/snake/snake.cpp Sat Apr 13 10:07:50 2019 +0000
+++ b/snake/snake.cpp Sat Apr 13 15:45:03 2019 +0000
@@ -18,14 +18,15 @@
_x[0] = WIDTH/2 - _size/2;
_y[0] = HEIGHT/2 - _size/2;
- _x[1] = WIDTH/2 - _size/2 -1*size;
- _y[1] = HEIGHT/2 - _size/2;
+ _x[1] = _x[0] -size;
+ _y[1] = _y[0];
- _x[2] = WIDTH/2 - _size/2 -2*size;
- _y[2] = HEIGHT/2 - _size/2;
+ _x[2] = _x[0] -2*size;
+ _y[2] = _y[0];
+ ball( _length);
_score = 0; // start score from zero
-
+ over = 0;
}
int snake::get_length(){
@@ -40,16 +41,14 @@
_y[k] = _y[k-1];
}
if(direction == 0){
- _x[0] = _x[0] + 1;
+ _x[0] = _x[0] + _size;
}else if(direction == 1){
- _y[0] = _y[0] + 1;
+ _y[0] = _y[0] + _size;
}else if(direction == 2){
- _x[0] = _x[0] - 1;
+ _x[0] = _x[0] - _size;
}else if(direction == 3){
- _y[0] = _y[0] - 1;
+ _y[0] = _y[0] - _size;
}
-
-
}
@@ -58,21 +57,60 @@
// 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 == _x[i] && ball_y == _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;
+ }
+ }
}
-void snake::add_score()
-{
- _score++;
-}
-
int snake::get_score()
{
- return _score;
+ return _score;
}