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
GameEngine/GameEngine.cpp
- Committer:
- sdlashmar
- Date:
- 2020-05-23
- Revision:
- 11:c4b740a970f8
- Parent:
- 10:3958fb08696d
- Child:
- 12:cb3a81adf48b
File content as of revision 11:c4b740a970f8:
#include "GameEngine.h"
GameEngine::GameEngine()
{
}
GameEngine::~GameEngine()
{
}
void GameEngine::init(int head_size, int head_speed)
{
srand(time(NULL));
_mouse_x = rand() %WIDTH-4;
_mouse_y = rand() %HEIGHT-4;
_game_over = false;
_score = 0;
_mouse = 0;
_length = 0;
_head_size = head_size;
_head_speed = head_speed;
head.init(_head_size, _head_speed);
}
void GameEngine::read_input(Gamepad& pad)
{
_d = pad.get_direction();
}
void GameEngine::update(Gamepad &pad, N5110 &lcd)
{
head.change_direction(_d);
Vector2D prevHead = head.get_pos();
tail.update(prevHead, _length);
head.update();
check_mouse_eaten(pad);
check_wall_collision(pad, lcd);
}
void GameEngine::draw(N5110 &lcd)
{
lcd.drawRect(0, 0, WIDTH, HEIGHT, FILL_TRANSPARENT);
head.draw(lcd);
tail.draw(lcd, _length);
spawn_mouse(lcd);
}
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);
}
void GameEngine::check_mouse_eaten(Gamepad &pad)
{
Vector2D headPos = head.get_pos();
int headX = headPos.x;
int headY = headPos.y;
//printf("head x = %i\n", headX);
//printf("head y = %i\n", headY);
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-4;
_mouse_y = rand() %HEIGHT-4;
_length++;
}
}
void GameEngine::check_wall_collision(Gamepad &pad, N5110 &lcd)
{
Vector2D headPos = head.get_pos();
int headX = headPos.x;
int headY = headPos.y;
if (headX < 0+2 || headX > WIDTH-3) {
_game_over = true;
game_over(lcd, pad);
}
if (headY < 0+2 || headY > HEIGHT-3) {
_game_over = true;
game_over(lcd, pad);
}
}
void GameEngine::game_over(N5110 &lcd, Gamepad &pad)
{
pad.tone(NOTE_E5, 0.1);
wait(0.1);
pad.tone(NOTE_D5, 0.1);
wait(0.1);
pad.tone(NOTE_C5, 0.1);
while(_game_over == true){
lcd.clear();
lcd.printString(" GAME OVER! ", 5, 0);
char buffer[14];
sprintf(buffer, "%2d", _score);
lcd.printString(" You scored: ", 2, 2);
lcd.printString(buffer, 8, 4);
lcd.refresh();
};
}