![](/media/cache/profiles/LinkedIn_0NghoZJ.jpeg.50x50_q85.jpg)
Snake vs Block Game to be run upon K64F.
Diff: GameObjects/Snake/Snake.cpp
- Revision:
- 71:4bd2b27693f3
- Parent:
- 70:7caab8069b9b
- Child:
- 77:5c6bd659c32d
diff -r 7caab8069b9b -r 4bd2b27693f3 GameObjects/Snake/Snake.cpp --- a/GameObjects/Snake/Snake.cpp Sat May 04 20:48:10 2019 +0000 +++ b/GameObjects/Snake/Snake.cpp Sat May 04 22:09:59 2019 +0000 @@ -20,6 +20,10 @@ void Snake::init(int length, int speed) { _length = length; + if(length >= 10) { + _length = 10; //to stop the snake length virtually at 10 when it goes past it. + } + _speed = speed;// change this according to the options selected m = 0; //Variable used to allow a starting location for the player. } @@ -57,6 +61,7 @@ Vector2D Snake::get_pos(int snakeIndex) { Vector2D snakepos; //Stores the snake position. + for(int i = (snakeIndex + 1); i<=10; i++) { if(_length == i) { snakepos.x = _x[i - (snakeIndex + 1)]; @@ -77,22 +82,31 @@ void Snake::update(Direction d, int* b) { - if(_length >= 10) { - _length = 10; //to stop the snake length virtually at 10 when it goes past it. - } + Snake::chainSnakeTogether(b); + + Snake::mooveSnake(d, b); + Snake::_setSnakeLimits(); +} + +void Snake::chainSnakeTogether(int* b) +{ //this makes all of the snake beeds chained together by making the lower ones drag towards where the top one was in the previous loop //the b[i] makes sure that the snake beed doesn't move if that beed is deactivated by colliding with a barrier. b[i] also signifies the specific beed number by i. - for(int i=0; i<=13; i++) { - if((_length > i+1)&&(_x[i] != _x[i+1])) { - if ((_x[i] > _x[i+1])&&(b[i+1] == 1)&&(b[i] == 1)) { - _x[i]-=_speed; + for(int i=0; i<=14; i++) { + if((_length > i)&&(_x[i-1] != _x[i])) { + if ((_x[i-1] > _x[i])&&(b[i] == 1)&&(b[i-1] == 1)) { + _x[i-1]-=_speed; } - if ((_x[i] < _x[i+1])&&(b[i+1] == 1)&&(b[i] == 1)) { - _x[i]+=_speed; + if ((_x[i-1] < _x[i])&&(b[i] == 1)&&(b[i-1] == 1)) { + _x[i-1]+=_speed; } } } +} + +void Snake::mooveSnake(Direction d, int* b) +{ //this makes the controls of W/E directions only exclusive to the top beed in the snake for(int i=14; i>=0; i--) { if((_length == i+1)&&(b[i] == 1)) { @@ -107,8 +121,11 @@ } } +} -// the following makes sure that when the length is increased, the snake stays where it was when it ate food. +void Snake::_setSnakeLimits() +{ + // the following makes sure that when the length is increased, the snake stays where it was when it ate food. for(int i=2; i<=15; i++) {