A game for Lab 4 of ECE 4180

Dependencies:   4DGL-uLCD-SE LSM9DS1_Library SDFileSystem mbed-rtos mbed wave_player

Invader.cpp

Committer:
Dogstopper
Date:
2016-03-14
Revision:
5:68f6014f10bd
Parent:
3:27889fffc2f7

File content as of revision 5:68f6014f10bd:

#include "Invader.h"
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

#define WIDTH 10
#define HEIGHT 10

Invader::Invader(uLCD_4DGL* startScreen, int w, int h) 
{
    /* initialize random seed: */
    srand (time(NULL));
  
    windowWidth = w;
    windowHeight = h;
    screen = startScreen;
    resetLocationAndSpeed();
}    

void Invader::update() 
{
    printf("x: %d, y: %d, spdY: %d\n\r", x,y, spdY);
    lastX = x;
    lastY = y;
    
    x += spdX;
    y += spdY;
    
    if (x <= -10 || y <= -10 || x+WIDTH >= windowWidth + 10 || y+HEIGHT >= windowHeight + 10) {
        // Then it is beyond the starting location for the box and we should reset it.
        resetLocationAndSpeed();
    }
}

void Invader::draw() 
{
    screen_mutex.lock();
    screen->filled_rectangle(lastX-WIDTH/2-1, lastY-HEIGHT/2-1, lastX+3*WIDTH/2, lastY+3*HEIGHT/2, BLACK);
    screen->filled_rectangle(x, y, x+WIDTH, y+HEIGHT, RED);
    screen_mutex.unlock();
}

bool Invader::intersects(int otherX, int otherY, int otherWidth, int otherHeight) 
{
    if (((otherX > x && otherX <= x + WIDTH) || (otherX + otherWidth > x && otherX + otherWidth <= x + WIDTH)) &&
        ((otherY > y && otherY <= y + HEIGHT) || (otherY + otherHeight > y && otherY + otherHeight <= y + HEIGHT))) {
            printf("Intersects\n");
            return true;
    }
    else {
        printf("Not Intersecting\n\n");
        return false;
    }
}

void Invader::resetLocationAndSpeed() 
{
    int side = rand() % 4;
    switch(side) {
        case 0: // Left
            x = -9;
            y = (int)(rand() % (windowHeight - HEIGHT));
            spdX = (int)(rand() % 3 + 1);
            spdY = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3);
            break;
        case 1: // Right
            x = windowWidth - 1;
            y = (int)(rand() % (windowHeight - HEIGHT));
            spdX = (int) (-1*(rand() % 3 + 1));
            spdY = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3);
            break;
        case 2: // Top
            x = (int)(rand() % (windowWidth - WIDTH));
            y = -9;
            spdX = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3);
            spdY = (int)(rand() % 3 + 1);
            break;
        case 3: // Bottom
            x = (int)(rand() % (windowWidth - WIDTH));
            y = windowWidth-1;
            spdX = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3);
            spdY = (int)(-1*(rand() % 3 + 1));
            break;
    }
}