]> code.bitgloo.com Git - clyne/gamedev.git/commitdiff
cleaning source
authorClyne Sullivan <tullivan99@gmail.com>
Tue, 13 Oct 2015 12:24:04 +0000 (08:24 -0400)
committerClyne Sullivan <tullivan99@gmail.com>
Tue, 13 Oct 2015 12:24:04 +0000 (08:24 -0400)
include/common.h
main.cpp

index 7df147f0b99403ad124cbf28b8d2487355e91d54..b2ef8a33d2f833a13c5633de506b7a4f3ab17233 100644 (file)
@@ -39,7 +39,9 @@ enum GENDER{
 #define initRand(s) srand(s)
 #define getRand()      rand()
 
-template<typename T, size_t N>                                         //this fuction returns the size of any array
+#define DEBUG_printf( message, ...) DEBUG_prints(__FILE__, __LINE__, message, __VA_ARGS__ )
+
+template<typename T, size_t N>                         //this fuction returns the size of any array
 int eAmt(T (&)[N]){return N;}
 
 extern bool gameRunning;
@@ -55,6 +57,4 @@ extern Mix_Chunk *horn;
 GLuint loadTexture(const char *fileName);
 void DEBUG_prints(const char* file, int line, const char *s,...);
 
-#define DEBUG_printf( message, ...) DEBUG_prints(__FILE__, __LINE__, message, __VA_ARGS__) //IF THERE IS NO VA_ARGS AT THE END OF A CALL, SUBSTITUTE IT WITH [ NULL ]
-
 #endif // COMMON_H
index 145df6e006532ff5d423d2775cf5435a69a34ef7..386d4191735d531381ee83b683b3a984d2190fd4 100644 (file)
--- a/main.cpp
+++ b/main.cpp
@@ -1,41 +1,46 @@
+#include <cstdio> // fopen
+#include <chrono> // see millis()
+
 #include <common.h>
 #include <world.h>
 #include <ui.h>
 #include <entities.h>
-#include <cstdio>
-#include <chrono>
 
-#define TICKS_PER_SEC 20
-#define MSEC_PER_TICK (1000/TICKS_PER_SEC)
+#define TICKS_PER_SEC 20                                       // The amount of game ticks that should occur in one second
+#define MSEC_PER_TICK (1000/TICKS_PER_SEC)     // The amount of milliseconds there should be between ticks
 
-SDL_Window    *window = NULL;
-SDL_Surface   *renderSurface = NULL;
+SDL_Window    *window = NULL;                  // The game's window
 SDL_GLContext  mainGLContext = NULL;
 static GLuint  bgImage;
 
-bool gameRunning = true;
+bool gameRunning = true;       // The game will exit if this is false
+
+World  *currentWorld=NULL;     // A pointer to the world that the player is currently in
+Player *player;                                // The player
+
+std::vector<Entity*>entity;            // An array of all entities in existance
+std::vector<NPC>npc;                   // An array of all NPCs in existance            (entries in `entity` point to these)
+std::vector<Structures *>build;        // An array of all Structures in existance      (entries in `entity` point to these)
+std::vector<Mob>mob;                   // An array of all Mobs in existance            (entries in `entity` point to these)
 
-World *currentWorld=NULL;
-Player *player;
+unsigned int tickCount   = 0,  // The amount of generated ticks since the game entered the main loop
+                        deltaTime   = 0;       // Used for frame regulation / smooth animation n' stuff
 
-std::vector<Entity*>entity;
-std::vector<NPC>npc;
-std::vector<Structures *>build;
-std::vector<Mob>mob;
+int mx, my;            // The mouse's coordinates in the window
 
-int mx, my;
-FILE* names;
+FILE *names;   // A pointer to the file containing possible NPC names
 
 Mix_Music *music;
 Mix_Chunk *horn;
-unsigned int loops = 0;
+unsigned int loops = 0;        // Used for texture animation
 
-extern void initEverything(void);
+extern void initEverything(void);      // Sets up the worlds and NPCs, see gameplay.cpp
 
-void logic();
-void render();
-void mainLoop(void);
+void logic();                  // Handles entity logic and input events
+void render();                 // Draws everything to the screen
+void mainLoop(void);   // Runs render() and logic()
 
+// Used for millisecond timing
 unsigned int millis(void){
        std::chrono::system_clock::time_point now=std::chrono::system_clock::now();
        return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
@@ -56,26 +61,25 @@ int main(int argc, char *argv[]){
        atexit(IMG_Quit);
 
         //Initialize SDL_mixer 
-       if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 ){
+       if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0){
                std::cout << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << std::endl;
        }
        atexit(Mix_Quit);
-       // Turn on double buffering
+       // Enable double buffering
     SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
     // Create the window
     window = SDL_CreateWindow("Independent Study v.0.2 alpha", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL
-                              #ifdef FULLSCREEN
-                              | SDL_WINDOW_FULLSCREEN
-                              #endif // FULLSCREEN
+#ifdef FULLSCREEN
+                                                         | SDL_WINDOW_FULLSCREEN
+#endif // FULLSCREEN
                               );
     if(window==NULL){
                std::cout << "The window failed to generate! Error: " << SDL_GetError() << std::endl;
                std::cout << "Window address: "<<window<<std::endl;
         return -1;
     }
-    //set OpenGL context
-    mainGLContext = SDL_GL_CreateContext(window);
-    if(mainGLContext == NULL){
+    // Set OpenGL context
+    if((mainGLContext = SDL_GL_CreateContext(window)) == NULL){
                std::cout << "The OpenGL context failed to initialize! Error: " << SDL_GetError() << std::endl;
         return -1;
     }
@@ -89,18 +93,10 @@ int main(int argc, char *argv[]){
        glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
        SDL_ShowCursor(SDL_DISABLE);                                            // Hide mouse cursor so we can draw our own
 
-       //************************************************************************//
-       //      WORLD GENERATION STUFF                                                                                            //
-       //************************************************************************//
-
        names = fopen("assets/names_en-us", "r+");      // Open the names file
        
        initEverything();                                                       // Run world maker thing in src/gameplay.cpp
        
-       /**************************
-       ****     GAMELOOP      ****
-       **************************/
-       
        //Load music
        music = Mix_LoadMUS("assets/BennyHillTheme.wav");
        horn = Mix_LoadWAV("assets/air-horn-club-sample_1.wav");
@@ -110,19 +106,23 @@ int main(int argc, char *argv[]){
        Mix_VolumeMusic(15);
        Mix_PlayMusic( music, -1 );
        
-       bgImage=loadTexture("assets/bg.png");
+       bgImage=loadTexture("assets/bg.png");   // Load a background image
        
-       initInventorySprites();
+       initInventorySprites(); // Load sprites used for items and the inventory
+       
+       /**************************
+       ****     GAMELOOP      ****
+       **************************/
        
        while(gameRunning){
                mainLoop();
        }
        
        /**************************
-       ****  CLOSE PROGRAM    ****
+       ****   CLOSE PROGRAM   ****
        **************************/
        
-    //closes the window and frees resources
+    // Close the window and free resources
     fclose(names);
     SDL_GL_DeleteContext(mainGLContext);
     SDL_DestroyWindow(window);
@@ -132,43 +132,41 @@ int main(int argc, char *argv[]){
 static unsigned int fps=0;
 static float debugY=0;
 
-unsigned int deltaTime=0;
-
 void mainLoop(void){
        static unsigned int debugDiv=0;
-       static unsigned int tickCount = 0,
-                                               prevTime    = 0,
-                                               currentTime = 0,
-                                               deltatime   = 0;
-       unsigned int i;
+       unsigned int i,
+                                prevTime    = 0,
+                                currentTime = 0;
        
        if(!currentTime)currentTime=millis();
        prevTime = currentTime;
        currentTime = millis();
-       deltatime = currentTime - prevTime;
-       deltaTime = deltatime;
-       
+       deltaTime = currentTime - prevTime;
+
        if(prevTime + MSEC_PER_TICK >= millis()){
                logic();
                prevTime = millis();
        }
 
-       player->loc.y+=player->vel.y*deltatime;
-       player->loc.x+=(player->vel.x*player->speed)*deltatime;
+       player->loc.y+=player->vel.y*deltaTime;
+       player->loc.x+=(player->vel.x*player->speed)*deltaTime;
        for(int i=0;i<=entity.size();i++){
-               entity[i]->loc.x += entity[i]->vel.x * deltatime;
-               entity[i]->loc.y += entity[i]->vel.y * deltatime;
+               entity[i]->loc.x += entity[i]->vel.x * deltaTime;
+               entity[i]->loc.y += entity[i]->vel.y * deltaTime;
                if(entity[i]->vel.x<0)entity[i]->left=true;
                if(entity[i]->vel.x>0)entity[i]->left=false;
        }
        
        if(++debugDiv==20){
-               fps=1000/deltatime;
+               fps=1000/deltaTime;
                debugDiv=0;
        }else if(!(debugDiv%10)){
                debugY = player->loc.y;
        }
        
+       mx = (ui::mouse.x+player->loc.x) - (SCREEN_WIDTH/2);
+       my = SCREEN_HEIGHT - ui::mouse.y;
+       
        render();
 }
 
@@ -191,72 +189,74 @@ void render(){
        **** RENDER STUFF HERE ****
        **************************/
 
-       glEnable(GL_TEXTURE_2D);
-       glBindTexture(GL_TEXTURE_2D,bgImage);
-       glBegin(GL_QUADS);
-               glTexCoord2i(0,1);glVertex2i(-SCREEN_WIDTH*2,0);
-               glTexCoord2i(1,1);glVertex2i( SCREEN_WIDTH*2,0);
-               glTexCoord2i(1,0);glVertex2i( SCREEN_WIDTH*2,SCREEN_HEIGHT);
-               glTexCoord2i(0,0);glVertex2i(-SCREEN_WIDTH*2,SCREEN_HEIGHT);
-       glEnd();
-       glDisable(GL_TEXTURE_2D);
+       glEnable(GL_TEXTURE_2D);                                                                                        // Draw the background image
+       glBindTexture(GL_TEXTURE_2D,bgImage);                                                           //
+       glBegin(GL_QUADS);                                                                                                      //
+               glTexCoord2i(0,1);glVertex2i(-SCREEN_WIDTH*2,0);                                //
+               glTexCoord2i(1,1);glVertex2i( SCREEN_WIDTH*2,0);                                //
+               glTexCoord2i(1,0);glVertex2i( SCREEN_WIDTH*2,SCREEN_HEIGHT);    //
+               glTexCoord2i(0,0);glVertex2i(-SCREEN_WIDTH*2,SCREEN_HEIGHT);    //
+       glEnd();                                                                                                                        //
+       glDisable(GL_TEXTURE_2D);                                                                                       //
 
-       player->near=true;
+       player->near=true;                      // Ensure the player's name is always drawn
        currentWorld->draw(player);     // Draw the world & the player
-       glColor3ub(255,255,255);
-       player->inv->draw();
+       glColor3ub(255,255,255);        // Draw the player's inventory
+       player->inv->draw();            //
 
-       ui::draw();                                                     // Draw any UI elements if they need to be
+       ui::draw();                                     // Draw any UI elements if they need to be
 
-       if(ui::debug){
+       if(ui::debug){                          // Draw the debug screen if it has been enabled
                ui::setFontSize(16);
                ui::putText(player->loc.x-SCREEN_WIDTH/2,SCREEN_HEIGHT-ui::fontSize,"FPS: %d\nG:%d\nRes: %ux%u\nE: %d\nPOS: (x)%+.2f\n     (y)%+.2f\nQc: %u",
                                        fps,player->ground,SCREEN_WIDTH,SCREEN_HEIGHT,entity.size(),player->loc.x,debugY,player->qh.current.size());
        }
+       
+       glColor3ub(255,255,255);                        // Draw the mouse
+       glBegin(GL_TRIANGLES);                          //
+               glVertex2i(mx,my);                              //
+               glVertex2i(mx+HLINE*3.5,my);    //
+               glVertex2i(mx,my-HLINE*3.5);    //
+       glEnd();                                                        //
 
        /**************************
-       ****  CLOSE THE LOOP   ****
+       ****  END RENDERING   ****
        **************************/
-       mx = ui::mouse.x + player->loc.x;
-       my = ui::mouse.y;
-       my = SCREEN_HEIGHT - my;
-       mx -= (SCREEN_WIDTH/2);
-       glColor3ub(255,255,255);
-       glBegin(GL_TRIANGLES);
-               glVertex2i(mx,my);
-               glVertex2i(mx+HLINE*3.5,my);
-               glVertex2i(mx,my-HLINE*3.5);
-       glEnd();
 
        glPopMatrix();                                                                  //take the matrix(s) off the stack to pass them to the renderer
        SDL_GL_SwapWindow(window);                                              //give the stack to SDL to render it
 }
 
 void logic(){
-       ui::handleEvents();
-       currentWorld->detect(player);
-        //loops through whole entity stack
-       for(int i=0;i<=entity.size();i++){
-                //only loops through entities that are alive
-               if(entity[i]->alive){
-                        //only loops through entities with type NPCT
-                       if(entity[i]->type == NPCT){
-                               entity[i]->wander((rand()%120 + 30), &entity[i]->vel); //makes the villager wander
-                               //makes sure the entity is close to the player, and the mouse cursor is over the NPC
-                               if( pow((entity[i]->loc.x - player->loc.x),2) + pow((entity[i]->loc.y - player->loc.y),2) <= pow(40*HLINE,2)){
-                                       if(mx >= entity[i]->loc.x && mx <= entity[i]->loc.x + entity[i]->width && my >= entity[i]->loc.y && my <= entity[i]->loc.y + entity[i]->width){
-                                               entity[i]->near=true; //sets near to true so we can toggle names later
+       ui::handleEvents();                             // Handle keyboard / mouse input
+       currentWorld->detect(player);   // Handle gravity and world bounds
+       
+       for(int i=0;i<=entity.size();i++){      // Loop through the whole entity stack
+               if(entity[i]->alive){                   // If the entity is alive
+                       switch(entity[i]->type){
+                       case NPCT:      // Handle NPCs
+                       
+                               entity[i]->wander((rand()%120 + 30), &entity[i]->vel); // Make the NPC wander
+                               
+                               // Check if the NPC is near the player and handle potential interaction
+                               if(pow((entity[i]->loc.x - player->loc.x),2) + pow((entity[i]->loc.y - player->loc.y),2) <= pow(40*HLINE,2)){
+                                       if(mx >= entity[i]->loc.x && mx <= entity[i]->loc.x + entity[i]->width &&
+                                          my >= entity[i]->loc.y && my <= entity[i]->loc.y + entity[i]->width){
+                                               entity[i]->near=true; // Allows the NPC's name to be drawn
                                                if(SDL_GetMouseState(NULL, NULL)&SDL_BUTTON(SDL_BUTTON_RIGHT)){
-                                                       entity[i]->interact(); //interacts with the NPCS
-                                                       //std::cout <<"["<<i<<"] -> "<< entity[i]->name << ", " << (std::string)(entity[i]->gender == MALE ? "Male" : "Female") << std::endl;
+                                                       entity[i]->interact(); // Interact with the player
                                                        //Mix_PlayChannel( -1, horn, 0);
                                                }
                                        }else entity[i]->near=false;
                                }
-                       }if(entity[i]->type == MOBT){
-                               entity[i]->wander((rand()%240 + 15),&entity[i]->vel);
+                               break;
+                       case MOBT:      // Handle mobs
+                               entity[i]->wander((rand()%240 + 15),&entity[i]->vel);   // Make the mob wander
+                               break;
+                       default:
+                               break;
                        }
                }
        }
        loops++;
-}
\ No newline at end of file
+}