A game for Lab 4 of ECE 4180
Dependencies: 4DGL-uLCD-SE LSM9DS1_Library SDFileSystem mbed-rtos mbed wave_player
Invader.cpp
00001 #include "Invader.h" 00002 #include <stdlib.h> /* srand, rand */ 00003 #include <time.h> /* time */ 00004 00005 #define WIDTH 10 00006 #define HEIGHT 10 00007 00008 Invader::Invader(uLCD_4DGL* startScreen, int w, int h) 00009 { 00010 /* initialize random seed: */ 00011 srand (time(NULL)); 00012 00013 windowWidth = w; 00014 windowHeight = h; 00015 screen = startScreen; 00016 resetLocationAndSpeed(); 00017 } 00018 00019 void Invader::update() 00020 { 00021 printf("x: %d, y: %d, spdY: %d\n\r", x,y, spdY); 00022 lastX = x; 00023 lastY = y; 00024 00025 x += spdX; 00026 y += spdY; 00027 00028 if (x <= -10 || y <= -10 || x+WIDTH >= windowWidth + 10 || y+HEIGHT >= windowHeight + 10) { 00029 // Then it is beyond the starting location for the box and we should reset it. 00030 resetLocationAndSpeed(); 00031 } 00032 } 00033 00034 void Invader::draw() 00035 { 00036 screen_mutex.lock(); 00037 screen->filled_rectangle(lastX-WIDTH/2-1, lastY-HEIGHT/2-1, lastX+3*WIDTH/2, lastY+3*HEIGHT/2, BLACK); 00038 screen->filled_rectangle(x, y, x+WIDTH, y+HEIGHT, RED); 00039 screen_mutex.unlock(); 00040 } 00041 00042 bool Invader::intersects(int otherX, int otherY, int otherWidth, int otherHeight) 00043 { 00044 if (((otherX > x && otherX <= x + WIDTH) || (otherX + otherWidth > x && otherX + otherWidth <= x + WIDTH)) && 00045 ((otherY > y && otherY <= y + HEIGHT) || (otherY + otherHeight > y && otherY + otherHeight <= y + HEIGHT))) { 00046 printf("Intersects\n"); 00047 return true; 00048 } 00049 else { 00050 printf("Not Intersecting\n\n"); 00051 return false; 00052 } 00053 } 00054 00055 void Invader::resetLocationAndSpeed() 00056 { 00057 int side = rand() % 4; 00058 switch(side) { 00059 case 0: // Left 00060 x = -9; 00061 y = (int)(rand() % (windowHeight - HEIGHT)); 00062 spdX = (int)(rand() % 3 + 1); 00063 spdY = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3); 00064 break; 00065 case 1: // Right 00066 x = windowWidth - 1; 00067 y = (int)(rand() % (windowHeight - HEIGHT)); 00068 spdX = (int) (-1*(rand() % 3 + 1)); 00069 spdY = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3); 00070 break; 00071 case 2: // Top 00072 x = (int)(rand() % (windowWidth - WIDTH)); 00073 y = -9; 00074 spdX = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3); 00075 spdY = (int)(rand() % 3 + 1); 00076 break; 00077 case 3: // Bottom 00078 x = (int)(rand() % (windowWidth - WIDTH)); 00079 y = windowWidth-1; 00080 spdX = (int)(((int)rand())==0 ? -1 : 1)*(rand() % 3); 00081 spdY = (int)(-1*(rand() % 3 + 1)); 00082 break; 00083 } 00084 }
Generated on Thu Jul 21 2022 04:01:54 by 1.7.2