ELEC2645 (2019/20) / Mbed 2 deprecated ELEC2645_Project_el17sdl_v2

Dependencies:   mbed

GameEngine/GameEngine.cpp

Committer:
sdlashmar
Date:
2020-05-22
Revision:
9:f0213e632379
Parent:
8:1e4182ebb063
Child:
10:3958fb08696d

File content as of revision 9:f0213e632379:

#include "GameEngine.h"

GameEngine::GameEngine() 
{
    
}

GameEngine::~GameEngine()
{
    
}

void GameEngine::init(int head_size, int head_speed) 
{
    _game_over = false;
    _score = 0;
    _mouse = 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);
    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);
    if (_mouse < 1) {
        spawn_mouse(lcd);
    };
}

void GameEngine::spawn_mouse(N5110 &lcd) 
{
    //create random x and y coordinates for mouse
    srand(time(NULL));
    int _mouse_x = rand() %WIDTH;
    int _mouse_y = rand() %HEIGHT;
    //check if mouse count is less than one, we only want one mouse spawned at a time 
    lcd.drawRect(_mouse_x, _mouse_y, 2, 2, FILL_BLACK);
    _mouse = 1;
        
}

void GameEngine::check_mouse_eaten(Gamepad &pad)
{
    Vector2D headPos = head.get_pos();
    int headX = headPos.x;
    int headY = headPos.y;
    
    if(headX == _mouse_x && headY == _mouse_y) {
        _score = _score + 10;
        _mouse = 0;
        pad.tone(750.0, 0.1);
    }
}

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();
    };
}