• Advertisement
Sign in to follow this  

Need Help (Not sure what is wrong)

This topic is 4432 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I'm working on my pong game and adding a menu. The game worked fine until I decided to include game states and make a menu. Now it doesn't work. This is using C++ and SDL. My problem is when it goes to the menu, it shows the menu with a black background (which is what I set it to), then it stalls and then turns to a white background. After that I have to force it to quit (It says program is not responding, end it now?). If I change the game state to start by playing the game, the game works till I try to quit. Then I get the white background and have to force it to quit. I'm just going to post the whole main and if I need to post some of the other files let me know. I have a feeling it would be a small mistake that I have overlooked. Well here it is:
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>

// Include the following classes
#include "SDL_Graphics.h"
#include "SDL_Input.h"
#include "Sprite.h"
#include "Timer.h"

// Game states
#define MENU 1
#define GAME 2
#define QUIT 3

// Attributes of the window
const int SCREEN_WIDTH = 750;
const int SCREEN_HEIGHT = 750;
const int SCREEN_BPP = 32;
const std::string WINDOW_TITLE = "Pong";

// Attributes of background
const int BACKGROUND_RED = 0;
const int BACKGROUND_GREEN = 0;
const int BACKGROUND_BLUE = 0;

// Font type
const std::string FONT_TYPE = "Arial.ttf";
const int FONT_SIZE = 18;

// The frame rate
const int FRAMES_PER_SECOND = 20;

// Load paddle.bmp with these characteristics
const std::string PADDLE_FILENAME = "paddle.bmp";
const int PADDLE_X = 0;
const int PADDLE_Y = 0;
const int PADDLE_WIDTH = 20;
const int PADDLE_HEIGHT = 100;
// The color that will be made transparent to put in color key
const int PADDLE_TRED = 255;
const int PADDLE_TGREEN = 255;
const int PADDLE_TBLUE = 255;

// Load ball.bmp with these characteristics
const std::string BALL_FILENAME = "ball.bmp";
const int BALL_X = 0;
const int BALL_Y = 0;
const int BALL_WIDTH = 20;
const int BALL_HEIGHT = 20;
// The color that will be made transparent to put in color key
const int BALL_TRED = 255;
const int BALL_TGREEN = 255;
const int BALL_TBLUE = 255;

// Paddle 1 (User controlled) characteristics
const int PADDLE1_XPOS = 710;
const int PADDLE1_YPOS = 375;
const float PADDLE1_SPEED = 10.0;
const float P1_START_VX = 0.0;
const float P1_START_VY = 0.0;

// Paddle 2 (Computer controlled) characteristics
const int PADDLE2_XPOS = 20;
const int PADDLE2_YPOS = 375;
const float PADDLE2_SPEED = 10.0;
const float P2_START_VX = 0.0;
const float P2_START_VY = 0.0;

// Ball characteristics
const int BALL_XPOS = 375;
const int BALL_YPOS = 375;
const float BALL_SPEED = 1.0;
const float B_START_VX = 5.0;
const float B_START_VY = 5.0;

void HandleKeyboardInput();
void ComputerAI();
void Menu();
void Game();

// Global Variables
bool g_quit = false;
SDL_Graphics* g_graphics = NULL;
SDL_Input* g_input = NULL;
Timer* g_timer = NULL;
Sprite* g_paddle1 = NULL;
Sprite* g_paddle2 = NULL;
Sprite* g_ball = NULL;
int g_game_states = MENU;
int g_comp_score = 0;
int g_player_score = 0;

int main( int argc, char* args[] )
{
    g_graphics = new SDL_Graphics(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, 
                WINDOW_TITLE, BACKGROUND_RED, BACKGROUND_GREEN, BACKGROUND_BLUE);
    
    g_input = new SDL_Input();
    
    while(g_game_states != QUIT)
    {
         switch(g_game_states)
         {
              case MENU:
                   Menu();
                   break;
              case GAME:
                   Game();
                   break; 
         }             
    }
    
    delete g_input;
    delete g_graphics;
    
    return 0;    
}

void HandleKeyboardInput()
{
   if (g_input->getInput(SDLK_ESCAPE))
   {
      g_quit = true;
      g_game_states = MENU;
   }

   if ((g_input->getInput(SDLK_UP)) && ((g_paddle1->get_ypos()+PADDLE_HEIGHT)>= 10))
   {
      g_paddle1->moveUp();
   }
   else if ((g_input->getInput(SDLK_DOWN))&&((g_paddle1->get_ypos()) <= SCREEN_HEIGHT-10))
   {
      g_paddle1->moveDown();
   }
   else
   {
      // Stops paddle if the user is not pressing any keys
      g_paddle1->stopMoving();
   }

}

void ComputerAI()
{
     if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) > (g_ball->get_ypos()+BALL_HEIGHT/2))
            g_paddle2->moveUp();
     if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) < (g_ball->get_ypos()+BALL_HEIGHT/2))
            g_paddle2->moveDown();
     if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) == (g_ball->get_ypos()+BALL_HEIGHT/2))
            g_paddle2->stopMoving();
}

void Menu()
{     
     g_timer = new Timer(); 
      
     // Wait for user input to quit or go to game 
     while(g_game_states != MENU)
     {   
          g_timer->start();  
          g_input->readInput();
          
          if (g_input->getInput(SDLK_ESCAPE))
          {
              g_game_states = QUIT;
          }
          
          if (g_input->windowClosed())
          {
              g_game_states = QUIT;
          }
          
          if (g_input->getInput(SDLK_RETURN))
          {
              g_game_states = GAME;
          } 
          
          g_graphics->beginScene();
          g_graphics->drawText(FONT_TYPE, "Menu", FONT_SIZE,
                  300,50,255,255,255,0,0,0);
          g_graphics->endScene(); 
          
          // Control the frame rate
          while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
          {
             // wait
          }
        
          g_timer->stop();
     } 

     delete g_timer;
}

void Game()
{
    g_paddle1 = new Sprite(g_graphics, PADDLE_X, PADDLE_Y,PADDLE_WIDTH,
              PADDLE_HEIGHT,PADDLE_TRED, PADDLE_TGREEN, PADDLE_TBLUE, PADDLE_FILENAME,
              PADDLE1_SPEED, PADDLE1_XPOS, PADDLE1_YPOS, P1_START_VX, P1_START_VY);
    g_paddle2 = new Sprite(g_graphics, PADDLE_X, PADDLE_Y, PADDLE_WIDTH,
              PADDLE_HEIGHT, PADDLE_TRED, PADDLE_TGREEN, PADDLE_TBLUE, PADDLE_FILENAME,
              PADDLE2_SPEED, PADDLE2_XPOS, PADDLE2_YPOS, P2_START_VX, P2_START_VY);
    g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
           BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
           BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
    g_timer = new Timer();
    
    // While the user hasn't quit
    while(g_quit == false)
    {
        g_timer->start();
        
        g_input->readInput();
        
        if (g_input->windowClosed())
        {
              g_quit = true;
              g_game_states = QUIT;
        }
        
        // Get user input and move human paddle
        HandleKeyboardInput();
        
        // Computer AI for paddle movement
        ComputerAI();
        
        // Check for any collision with paddles and bounce the ball accordingly
        if(g_ball->checkCollision(g_paddle1) || g_ball->checkCollision(g_paddle2))
        {
              if(g_ball->get_Vx() < 0)
              {
                     if(g_ball->get_Vy() < 0)
                         g_ball->changeVelocity(-(g_ball->get_Vx())+BALL_SPEED,g_ball->get_Vy()-BALL_SPEED);
                     else
                         g_ball->changeVelocity(-(g_ball->get_Vx())+BALL_SPEED,g_ball->get_Vy()+BALL_SPEED);
              }
              else 
              {
                     if(g_ball->get_Vy() < 0)     
                         g_ball->changeVelocity(-(g_ball->get_Vx())-BALL_SPEED,g_ball->get_Vy()-BALL_SPEED);
                     else
                         g_ball->changeVelocity(-(g_ball->get_Vx())-BALL_SPEED,g_ball->get_Vy()+BALL_SPEED);
              }
        }
        
        // Check for any collision with vertical walls and bounce the ball accordingly
        if(g_ball->get_ypos() <= 0 || (g_ball->get_ypos()+BALL_HEIGHT) >= SCREEN_HEIGHT)
        {
              g_ball->changeVelocity(g_ball->get_Vx(),-(g_ball->get_Vy()));
        }
        
        // Check for player scoring
        if(g_ball->get_xpos() <= 0)
        {
             g_player_score++;
             delete g_ball;
             g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
                    BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
                    BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
        }  
        
        // Check for AI scoring
        if((g_ball->get_xpos()+BALL_WIDTH)>= SCREEN_WIDTH)
        {
             g_comp_score++;
             delete g_ball;
             g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
                    BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
                    BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
        }
        
        g_ball->update(g_timer->get_ticks());
        g_paddle1->update(g_timer->get_ticks());
        g_paddle2->update(g_timer->get_ticks());
        
        g_graphics->beginScene();
        
        g_ball->draw();
        g_paddle1->draw();
        g_paddle2->draw();
        
        // Convert scores into string and then draw them
        char temp[256];
        std::string c_score = "Computer Score: ";
        itoa(g_comp_score, temp, 10);
        c_score += temp;
        g_graphics->drawText(FONT_TYPE, c_score, FONT_SIZE,
                  25,10,255,255,255,0,0,0);
        std::string p_score = "Player Score: ";
        itoa(g_player_score, temp, 10);
        p_score += temp;
        g_graphics->drawText(FONT_TYPE, p_score, FONT_SIZE,
                  600,10,255,255,255,0,0,0);
        
        g_graphics->endScene();
        
        // Control the frame rate
        while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
        {
             // wait
        }
        
        g_timer->stop();
    }
    
    delete g_timer;
    delete g_ball;
    delete g_paddle1;
    delete g_paddle2;
    
}

Oh if you have any suggestions or criticisms feel free to post and let me know. Thanks.

Share this post


Link to post
Share on other sites
Advertisement
Firstly:
------------------------------------
[Source]
while(g_game_states != MENU)
{
g_timer->start();
g_input->readInput();

if (g_input->getInput(SDLK_ESCAPE))
{
g_game_states = QUIT;
}

if (g_input->windowClosed())
{
g_game_states = QUIT;
}

if (g_input->getInput(SDLK_RETURN))
{
g_game_states = GAME;
}

g_graphics->beginScene();
g_graphics->drawText(FONT_TYPE, "Menu", FONT_SIZE,
300,50,255,255,255,0,0,0);
g_graphics->endScene();

// Control the frame rate
while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
{
// wait
}

g_timer->stop();
}


In your menu function you have a while (game_state!= MENU), and i think you want that to be a while gamestate == menu

and then next,
-------------
// Control the frame rate
while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
{
// wait
}

Put a sleep(4) command there where "// wait" is

Share this post


Link to post
Share on other sites
Thank you very much!

Just wondering, is the sleep function there to make the game more efficient in memory usage?

Share this post


Link to post
Share on other sites
Quote:
Original post by eektor
Just wondering, is the sleep function there to make the game more efficient in memory usage?

The "Sleep()" function has little to do with memory. It basically tells the OS that the app does not require processing for at least the given amount of milliseconds. A call of Sleep(0) for example will result in a switch to other (system-)processes and allow for sending out pooled messages etc.
Note that the given parameter denotes the lower time limit. Sleep(4) will not leave the app for 4ms anyway, since the default timing has a resolution of something around 10ms (depending on the OS version and the thread priority), so the loop is likely to be left for around 10+ ms.
If you have many tasks running in the background, using a parameter other than zero may cause your game lag from time to time.
Using Sleep(0) basically tells Windows to "go back to the game as soon as possible", e.g. it only pauses until the end of the thread's time-slice and returns as soon as any OS messages arrive for the calling thread.

Share this post


Link to post
Share on other sites
[edit]darookie with the ninja post!! [lol]

Quote:
Original post by dawidjoubert
Put a sleep(4) command there where "// wait" is


For SDL, you can use the SDL_Delay(X) function where X is the delay time. However, the numbers are rounded up to the nearest 10ms, so any number in the range of 1-9 will be 10, 11-19 will be 20, and so on. That's because the resolution of the timer is 10ms.

Share this post


Link to post
Share on other sites
EDIT: Your reflexes astound me, fellow devvers!

Quote:
Original post by eektor
Thank you very much!

Just wondering, is the sleep function there to make the game more efficient in memory usage?


Yes - every time it goes through the loop it tells the computer it can take a break from running your program for 4 milliseconds, which is quite a bit in CPU-time; 'course not much to us.

Share this post


Link to post
Share on other sites
Another question, in the HandleKeyboardInput() I wanted to check if someone pressed escape. If they pressed escape it should go back to the menu. Unfortunately when I hit escape when running it, it will close the window. Now, I decided to change it to check for q instead of escape and it worked perfectly. Why does this happen? Does SDL think when checking for escape it is similar to someone clicking on the x button to close the window?

One more thing, when I run the game it starts on the menu. I press return to play the game, then press q to return to the menu. Now when I press return to play the game again it stalls and I have to force it to close. What could be causing this problem?

Thanks for all the help.

Share this post


Link to post
Share on other sites
Quote:
Original post by eektor
Another question, in the HandleKeyboardInput() I wanted to check if someone pressed escape. If they pressed escape it should go back to the menu. Unfortunately when I hit escape when running it, it will close the window. Now, I decided to change it to check for q instead of escape and it worked perfectly. Why does this happen? Does SDL think when checking for escape it is similar to someone clicking on the x button to close the window?

One more thing, when I run the game it starts on the menu. I press return to play the game, then press q to return to the menu. Now when I press return to play the game again it stalls and I have to force it to close. What could be causing this problem?

Thanks for all the help.

We'll need to see the updated code that implements it, but re: ESC vs 'q' I really have no idea what could cause that if the effect of pressing them is identical. Regarding gameplay->menu->gameplay, I would guess it has something to do with pointers, but I don't see any problem in the code offhand since it all seems to clean itself up each time a function ends. Did you write the #included files yourself? There could be a problem there.

Share this post


Link to post
Share on other sites
As for the code, I just changed SDLK_ESCAPE to SDLK_q. (After the changes that were suggested, changing != to == and adding a SDL_Delay(10);) Before when I hit escape in the game, it would quit and close the window. Now, when I hit 'q', in the game it will go back to the menu.

I wrote the classes in the included files. Do you think the problem might be in SDL_Graphics?

Share this post


Link to post
Share on other sites
Quote:
Original post by eektor
As for the code, I just changed SDLK_ESCAPE to SDLK_q. (After the changes that were suggested, changing != to == and adding a SDL_Delay(10);) Before when I hit escape in the game, it would quit and close the window. Now, when I hit 'q', in the game it will go back to the menu.

I wrote the classes in the included files. Do you think the problem might be in SDL_Graphics?

ESC vs. 'q': My next guess is that you didn't convert an ESC to a 'q' somewhere - maybe 'ESC' still fires whatever needs to be fired to make g_input->windowClosed() return true? As far as I know ESC is treated just like any other key in SDL country.

I'd say class SDL_Graphics is the most likely culprit for the menu problem, so if you could post the code that'd be great. :)

Share this post


Link to post
Share on other sites
Ok, here is SDL_Graphics.h

#ifndef INC_SDL_GRAPHICS_H
#define INC_SDL_GRAPHICS_H

#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>

class SDL_Graphics
{
public:
// This creates a window and initializes the graphics object.
// The last three parameters are the desired background color.
// Call setBackgroundColor() to change this later.
SDL_Graphics(int window_width, int window_height, int window_bpp,
const std::string window_title,
int bgR, int bgG, int bgB);
~SDL_Graphics();


// Each call to load_image() must have a corresponding call to close_image().
SDL_Surface* load_image(const std::string filename,
int transparentRed, int transparentGreen, int transparentBlue);
void close_image(SDL_Surface* image);

// These calls must go before and after any drawings
void beginScene();
void endScene();

void drawSprite(SDL_Surface* imageSurface,
int srcX, int srcY,
int dstX, int dstY,
int width, int height);

void drawText(const std::string font_type, const std::string string,
int size,
int x, int y,
int fR, int fG, int fB,
int bR, int bG, int bB);

void setBackgroundColor(int r, int g, int b);

private:
SDL_Surface* m_screen;

int m_backgroundColorRed;
int m_backgroundColorGreen;
int m_backgroundColorBlue;
};

#endif /* INC_SDL_GRAPHICS_H */



and here is SDL_Graphics.cpp

#include "SDL_Graphics.h"

SDL_Graphics::SDL_Graphics(int window_width, int window_height, int window_bpp,
const std::string window_title,
int bgR, int bgG, int bgB)
{
// Initialize all SDL sub systems
SDL_Init(SDL_INIT_EVERYTHING);
TTF_Init();

// Set up the screen
m_screen = SDL_SetVideoMode(window_width, window_height, window_bpp,
SDL_HWSURFACE | SDL_DOUBLEBUF);

// Set the window caption
SDL_WM_SetCaption(window_title.c_str(), 0);

setBackgroundColor(bgR, bgB, bgG);
}

SDL_Graphics::~SDL_Graphics()
{
TTF_Quit();
SDL_Quit();
}

SDL_Surface* SDL_Graphics::load_image(const std::string filename,
int transparentRed, int transparentGreen, int transparentBlue)
{
SDL_Surface* loadedImage = NULL;
SDL_Surface* optimizedImage = NULL;

loadedImage = IMG_Load(filename.c_str());

// Create an optimized image
optimizedImage = SDL_DisplayFormat(loadedImage);

SDL_FreeSurface(loadedImage);

// Set all pixels of color specified to be transparent
SDL_SetColorKey(optimizedImage, SDL_RLEACCEL | SDL_SRCCOLORKEY,
SDL_MapRGB(optimizedImage->format, transparentRed, transparentGreen, transparentBlue));

return optimizedImage;
}

void SDL_Graphics::close_image(SDL_Surface* image)
{
SDL_FreeSurface(image);
}

void SDL_Graphics::beginScene()
{
// Clear the screen
SDL_FillRect(m_screen,
NULL,
SDL_MapRGB(m_screen->format, m_backgroundColorRed,
m_backgroundColorGreen,
m_backgroundColorBlue));
}

// This just displays the scene.
void SDL_Graphics::endScene()
{
SDL_Flip(m_screen);
}

void SDL_Graphics::drawSprite(SDL_Surface* imageSurface,
int srcX, int srcY,
int dstX, int dstY,
int width, int height)
{
SDL_Rect srcRect;
srcRect.x = srcX;
srcRect.y = srcY;
srcRect.w = width;
srcRect.h = height;

SDL_Rect dstRect;
dstRect.x = dstX;
dstRect.y = dstY;
dstRect.w = width;
dstRect.h = height;

SDL_BlitSurface(imageSurface, &srcRect, m_screen, &dstRect);
}

void SDL_Graphics::drawText(const std::string font_type, const std::string text,
int size,
int x, int y,
int fR, int fG, int fB,
int bR, int bG, int bB)
{
TTF_Font* font = TTF_OpenFont(font_type.c_str(), size);

SDL_Color foregroundColor = { fR, fG, fB };
SDL_Color backgroundColor = { bR, bG, bB };

SDL_Surface* textSurface = TTF_RenderText_Shaded(font, text.c_str(),
foregroundColor, backgroundColor);

SDL_Rect textLocation = { x, y, 0, 0 };

SDL_BlitSurface(textSurface, NULL, m_screen, &textLocation);

SDL_FreeSurface(textSurface);

TTF_CloseFont(font);
}

void SDL_Graphics::setBackgroundColor(int r, int g, int b)
{
m_backgroundColorRed = r;
m_backgroundColorGreen = g;
m_backgroundColorBlue = b;
}

Share this post


Link to post
Share on other sites
I'm still having problems. I start the game and quit back to the menu. Then when I start the game again, it stalls and I have to close the program. Here is my updated main file.

#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>

// Include the following classes
#include "SDL_Graphics.h"
#include "SDL_Input.h"
#include "Sprite.h"
#include "Timer.h"

// Game states
#define MENU 1
#define GAME 2
#define QUIT 3
#define INTRO 4

// Attributes of the window
const int SCREEN_WIDTH = 750;
const int SCREEN_HEIGHT = 750;
const int SCREEN_BPP = 32;
const std::string WINDOW_TITLE = "Pong";

// Attributes of background
const int BACKGROUND_RED = 0;
const int BACKGROUND_GREEN = 0;
const int BACKGROUND_BLUE = 0;

// Font type
const std::string FONT_TYPE = "Arial.ttf";
const int FONT_SIZE = 18;

// The frame rate
const int FRAMES_PER_SECOND = 20;

// Load paddle.bmp with these characteristics
const std::string PADDLE_FILENAME = "paddle.bmp";
const int PADDLE_X = 0;
const int PADDLE_Y = 0;
const int PADDLE_WIDTH = 20;
const int PADDLE_HEIGHT = 100;
// The color that will be made transparent to put in color key
const int PADDLE_TRED = 255;
const int PADDLE_TGREEN = 255;
const int PADDLE_TBLUE = 255;

// Load ball.bmp with these characteristics
const std::string BALL_FILENAME = "ball.bmp";
const int BALL_X = 0;
const int BALL_Y = 0;
const int BALL_WIDTH = 20;
const int BALL_HEIGHT = 20;
// The color that will be made transparent to put in color key
const int BALL_TRED = 255;
const int BALL_TGREEN = 255;
const int BALL_TBLUE = 255;

// Paddle 1 (User controlled) characteristics
const int PADDLE1_XPOS = 710;
const int PADDLE1_YPOS = 375;
const float PADDLE1_SPEED = 10.0;
const float P1_START_VX = 0.0;
const float P1_START_VY = 0.0;

// Paddle 2 (Computer controlled) characteristics
const int PADDLE2_XPOS = 20;
const int PADDLE2_YPOS = 375;
const float PADDLE2_SPEED = 10.0;
const float P2_START_VX = 0.0;
const float P2_START_VY = 0.0;

// Ball characteristics
const int BALL_XPOS = 375;
const int BALL_YPOS = 375;
const float BALL_SPEED = 1.0;
const float B_START_VX = 5.0;
const float B_START_VY = 5.0;

void HandleKeyboardInput();
void ComputerAI();
void Menu();
void Intro();
void Game();

// Global Variables
bool g_quit = false;
SDL_Graphics* g_graphics = NULL;
SDL_Input* g_input = NULL;
Timer* g_timer = NULL;
Sprite* g_paddle1 = NULL;
Sprite* g_paddle2 = NULL;
Sprite* g_ball = NULL;
int g_game_states = MENU;
int g_comp_score = 0;
int g_player_score = 0;

int main( int argc, char* args[] )
{
g_graphics = new SDL_Graphics(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP,
WINDOW_TITLE, BACKGROUND_RED, BACKGROUND_GREEN, BACKGROUND_BLUE);

g_input = new SDL_Input();

while(g_game_states != QUIT)
{
switch(g_game_states)
{
case MENU:
Menu();
break;
case INTRO:
Intro();
break;
case GAME:
Game();
break;
}
}

delete g_input;
delete g_graphics;

return 0;
}

void HandleKeyboardInput()
{
if (g_input->getInput(SDLK_q))
{
g_quit = true;
g_game_states = MENU;
}

if ((g_input->getInput(SDLK_UP)) && ((g_paddle1->get_ypos()+PADDLE_HEIGHT)>= 10))
{
g_paddle1->moveUp();
}
else if ((g_input->getInput(SDLK_DOWN))&&((g_paddle1->get_ypos()) <= SCREEN_HEIGHT-10))
{
g_paddle1->moveDown();
}
else
{
// Stops paddle if the user is not pressing any keys
g_paddle1->stopMoving();
}

}

void ComputerAI()
{
if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) > (g_ball->get_ypos()+BALL_HEIGHT/2))
g_paddle2->moveUp();
if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) < (g_ball->get_ypos()+BALL_HEIGHT/2))
g_paddle2->moveDown();
if ((g_paddle2->get_ypos()+PADDLE_HEIGHT/2) == (g_ball->get_ypos()+BALL_HEIGHT/2))
g_paddle2->stopMoving();
}

void Menu()
{
g_timer = new Timer();

// Wait for user input to quit or go to game
while(g_game_states == MENU)
{
g_timer->start();
g_input->readInput();

if (g_input->getInput(SDLK_ESCAPE))
{
g_game_states = QUIT;
}

if (g_input->windowClosed())
{
g_game_states = QUIT;
}

if (g_input->getInput(SDLK_RETURN))
{
g_game_states = GAME;
}

if (g_input->getInput(SDLK_i))
{
g_game_states = INTRO;
}

g_graphics->beginScene();
g_graphics->drawText(FONT_TYPE, "Pong", FONT_SIZE,
353,50,255,255,255,0,0,0);
g_graphics->drawText(FONT_TYPE, "Press 'i' for instructions.", FONT_SIZE,
340,345,255,255,255,0,0,0);
g_graphics->drawText(FONT_TYPE, "Press <enter> to begin.", FONT_SIZE,
343,375,255,255,255,0,0,0);
g_graphics->drawText(FONT_TYPE, "Press 'q' to quit when playing.", FONT_SIZE,
339,415,255,255,255,0,0,0);
g_graphics->drawText(FONT_TYPE, "Press <escape> to exit.", FONT_SIZE,
343,445,255,255,255,0,0,0);
g_graphics->endScene();

// Control the frame rate
while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
{
// wait
SDL_Delay(10);
}

g_timer->stop();
}

delete g_timer;
}

void Intro()
{
g_timer = new Timer();

// Wait for user input to quit or go to game
while(g_game_states == INTRO)
{
g_timer->start();
g_input->readInput();

if (g_input->getInput(SDLK_q))
{
g_game_states = MENU;
}

if (g_input->windowClosed())
{
g_game_states = QUIT;
}

g_graphics->beginScene();
g_graphics->drawText(FONT_TYPE, "Instructions", FONT_SIZE,
350,50,255,255,255,0,0,0);
g_graphics->drawText(FONT_TYPE, "Press the up and down arrow key, to move your paddle.", FONT_SIZE,
275,345,255,255,255,0,0,0);
g_graphics->endScene();

// Control the frame rate
while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
{
// wait
SDL_Delay(10);
}

g_timer->stop();
}

delete g_timer;
}

void Game()
{
g_paddle1 = new Sprite(g_graphics, PADDLE_X, PADDLE_Y,PADDLE_WIDTH,
PADDLE_HEIGHT,PADDLE_TRED, PADDLE_TGREEN, PADDLE_TBLUE, PADDLE_FILENAME,
PADDLE1_SPEED, PADDLE1_XPOS, PADDLE1_YPOS, P1_START_VX, P1_START_VY);
g_paddle2 = new Sprite(g_graphics, PADDLE_X, PADDLE_Y, PADDLE_WIDTH,
PADDLE_HEIGHT, PADDLE_TRED, PADDLE_TGREEN, PADDLE_TBLUE, PADDLE_FILENAME,
PADDLE2_SPEED, PADDLE2_XPOS, PADDLE2_YPOS, P2_START_VX, P2_START_VY);
g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
g_timer = new Timer();

// While the user hasn't quit
while(g_quit == false)
{
g_timer->start();

g_input->readInput();

if (g_input->windowClosed())
{
g_quit = true;
g_game_states = QUIT;
}

// Get user input and move human paddle
HandleKeyboardInput();

// Computer AI for paddle movement
ComputerAI();

// Check for any collision with paddles and bounce the ball accordingly
if(g_ball->checkCollision(g_paddle1) || g_ball->checkCollision(g_paddle2))
{
if(g_ball->get_Vx() < 0)
{
if(g_ball->get_Vy() < 0)
g_ball->changeVelocity(-(g_ball->get_Vx())+BALL_SPEED,g_ball->get_Vy()-BALL_SPEED);
else
g_ball->changeVelocity(-(g_ball->get_Vx())+BALL_SPEED,g_ball->get_Vy()+BALL_SPEED);
}
else
{
if(g_ball->get_Vy() < 0)
g_ball->changeVelocity(-(g_ball->get_Vx())-BALL_SPEED,g_ball->get_Vy()-BALL_SPEED);
else
g_ball->changeVelocity(-(g_ball->get_Vx())-BALL_SPEED,g_ball->get_Vy()+BALL_SPEED);
}
}

// Check for any collision with vertical walls and bounce the ball accordingly
if(g_ball->get_ypos() <= 0 || (g_ball->get_ypos()+BALL_HEIGHT) >= SCREEN_HEIGHT)
{
g_ball->changeVelocity(g_ball->get_Vx(),-(g_ball->get_Vy()));
}

// Check for player scoring
if(g_ball->get_xpos() <= 0)
{
g_player_score++;
delete g_ball;
g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
}

// Check for AI scoring
if((g_ball->get_xpos()+BALL_WIDTH)>= SCREEN_WIDTH)
{
g_comp_score++;
delete g_ball;
g_ball = new Sprite(g_graphics, BALL_X, BALL_Y, BALL_WIDTH,
BALL_HEIGHT, BALL_TRED, BALL_TGREEN, BALL_TBLUE, BALL_FILENAME,
BALL_SPEED, BALL_XPOS, BALL_YPOS, B_START_VX, B_START_VY);
}

g_ball->update(g_timer->get_ticks());
g_paddle1->update(g_timer->get_ticks());
g_paddle2->update(g_timer->get_ticks());

g_graphics->beginScene();

g_ball->draw();
g_paddle1->draw();
g_paddle2->draw();

// Convert scores into string and then draw them
char temp[256];
std::string c_score = "Computer Score: ";
itoa(g_comp_score, temp, 10);
c_score += temp;
g_graphics->drawText(FONT_TYPE, c_score, FONT_SIZE,
25,10,255,255,255,0,0,0);
std::string p_score = "Player Score: ";
itoa(g_player_score, temp, 10);
p_score += temp;
g_graphics->drawText(FONT_TYPE, p_score, FONT_SIZE,
600,10,255,255,255,0,0,0);

g_graphics->endScene();

// Control the frame rate
while(g_timer->get_ticks() < 1000 / FRAMES_PER_SECOND)
{
// wait
SDL_Delay(10);
}

g_timer->stop();
}

delete g_timer;
delete g_ball;
delete g_paddle1;
delete g_paddle2;
}

Share this post


Link to post
Share on other sites
Quote:
Original post by rpg_code_master
Off topic I know, but why is your screen res 750*750? Is that an SDL thing or something?


its a window of size 750x750. its not fullscreen( from what i can see )

Share this post


Link to post
Share on other sites
Yes, what rip-off said. It creates a window that is 750x750 and it is not full screen.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement