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
Diff: GameEngine/GameEngine.cpp
- Revision:
- 14:4356797fd16e
- Parent:
- 13:4fa0d5148216
--- a/GameEngine/GameEngine.cpp Sun May 24 15:08:31 2020 +0000
+++ b/GameEngine/GameEngine.cpp Sun May 24 15:27:53 2020 +0000
@@ -12,29 +12,34 @@
void GameEngine::init(int head_size, int head_speed)
{
+ //initial random coordinates for mouse spawn
srand(time(NULL));
- _mouse_x = rand() %WIDTH+2;
- _mouse_y = rand() %HEIGHT+2;
+ _mouse_x = rand() %80+4;
+ _mouse_y = rand() %44+4;
+ //initialise parameters
_game_over = false;
_score = 0;
_mouse = 0;
_length = 0;
_head_size = head_size;
_head_speed = head_speed;
-
+ //initialise the head
head.init(_head_size, _head_speed);
}
void GameEngine::read_input(Gamepad& pad)
{
+ //read direction from joystick
_d = pad.get_direction();
}
void GameEngine::update(Gamepad &pad, N5110 &lcd)
{
head.change_direction(_d);
+ //need to make sure the current head position is stored before updating as this then becomes the previous head position for updating the snake tail
Vector2D prevHead = head.get_pos();
+ //tail updated before head
tail.update(prevHead, _length);
head.update();
check_mouse_eaten(pad);
@@ -52,12 +57,8 @@
void GameEngine::spawn_mouse(N5110 &lcd)
{
- //create random x and y coordinates for mouse
- //printf("mouse x = %i\n", _mouse_x);
- //printf("mouse y = %i\n", _mouse_y);
- lcd.drawRect(_mouse_x, _mouse_y, 2, 2, FILL_BLACK);
-
-
+ // draw the mouse from given x and y coordinates
+ lcd.drawRect(_mouse_x, _mouse_y, 2, 2, FILL_BLACK);
}
void GameEngine::check_mouse_eaten(Gamepad &pad)
@@ -67,14 +68,14 @@
int headY = headPos.y;
//printf("head x = %i\n", headX);
//printf("head y = %i\n", headY);
-
+ //check if the head position is the same as the mouse position, if it is score increases by ten and new mouse coordinates generated
if((headX == _mouse_x || headX == _mouse_x+1 || headX == _mouse_x-1) && (headY == _mouse_y || (headY == _mouse_y+1 || headY == _mouse_y-1))) {
_score = _score + 10;
_mouse = 0;
pad.tone(750.0, 0.1);
srand(time(NULL));
- _mouse_x = rand() %WIDTH+2;
- _mouse_y = rand() %HEIGHT+2;
+ _mouse_x = rand() %80+4;
+ _mouse_y = rand() %44+4;
_length++;
}
}
@@ -84,7 +85,7 @@
Vector2D headPos = head.get_pos();
int headX = headPos.x;
int headY = headPos.y;
-
+ // checks if the snake head has it the wall, if it has then the game over function is run
if (headX < 0+2 || headX > WIDTH-3) {
_game_over = true;
game_over(lcd, pad);
@@ -97,8 +98,6 @@
void GameEngine::game_over(N5110 &lcd, Gamepad &pad)
{
-
-
pad.tone(NOTE_E5, 0.1);
wait(0.1);
pad.tone(NOTE_D5, 0.1);