Ideas, stoopid code, and friends

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

Post Reply
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Ideas, stoopid code, and friends

Post by Aspirer »

I've started this topic mainly because I don't know whats causing my code to work improperly. Its lesson 17 (motion) in lazyfoo.nets tutorials, but I've got some remnants of my last program left in there. Its very disorganized and unformatted, so bear with me:

Code: Select all

#include"stdafx.h"
#include"SDL.h"
#include"SDL_ttf.h"
#include"SDL_image.h"
#include<vector>
#include <string>
#include <sstream>
using namespace std;


// It just doesn't move the box when I press the keys!

const int SQUARE_WIDTH = 20;
const int SQUARE_HEIGHT = 20;

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
const int FRAMES_PER_SECOND = 30;

SDL_Surface *background = NULL;

SDL_Surface *message = NULL;

SDL_Surface *screen = NULL;

SDL_Surface *collideMessage = NULL;

SDL_Surface *missMessage = NULL;

SDL_Surface *seconds = NULL;

SDL_Surface *boxgraphic = NULL;

//The event structure
SDL_Event event;

//The font
TTF_Font *font = NULL;

//The color of the font
SDL_Color textColor = {0, 0, 0 };

SDL_Rect wall;

bool quit = false;

class Timer { 
private:
	int startTicks, pausedTicks;

	bool paused, started;
	
public:

	Timer();

	void start();
	void stop();
	void pause();
	void unpause();

	int get_ticks();
	bool is_started();
	bool is_paused();
};
Timer::Timer() {

	startTicks = 0;

	pausedTicks = 0;

	paused = false;

	started = false;

}

void Timer::start() {

	started = true;

	paused = false;

	startTicks = SDL_GetTicks();

};


void Timer::stop() {

	started = false;

	paused = false;

}

int Timer::get_ticks() {

	if (started == true ) {

		if (paused == true ) {

			return pausedTicks;

		}
		else { return SDL_GetTicks() - startTicks;
		
		}
	}
	return 0;

}
void Timer::pause() {

	if (started == true && paused == false) {

		paused = true;

		pausedTicks = SDL_GetTicks() - startTicks;

		}
	}
			
void Timer::unpause() {
	if (paused == true) {
		paused = false;
		startTicks = SDL_GetTicks() - pausedTicks;
		pausedTicks = 0;
	}
}
bool Timer::is_started() {

			return started;
		}
bool Timer::is_paused() {

	return paused;
}

class Square {
	private:
		SDL_Rect box;
		int xVel,yVel;
	public:
		Square();
		void move();
		void show();
		void handle_input();
};

Square::Square () {
		 
	box.x = 25;
	box.y = 25;

	box.w = SQUARE_WIDTH;
	box.h = SQUARE_HEIGHT;

	xVel, yVel = 0;

}
void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect * clip = NULL) {
    //Holds offsets
    SDL_Rect offset;

    //Get offsets
    offset.x = x;
    offset.y = y;

    //Blit
    SDL_BlitSurface( source, clip, destination, &offset );
}


bool check_collision(SDL_Rect A, SDL_Rect B) { //The sides of the rectangles 
	int leftA,leftB; 
	int rightA, rightB;
	int topA, topB;
	int bottomA, bottomB;
	//Go through the A boboxes 
		//Calculate the sides of rect A 
		leftA = A.x; 
		rightA = A.x + A.w; 
		topA = A.y;
		bottomA = A.y + A.h; 
		//Go through the B boboxes
			//Calculate the sides of rect B
			leftB = B.y; 
			rightB = B.y + B.w; 
			topB = B.y; 
			bottomB = B.y + B.h;
			//If no sides from A are outside of B 
			if(  ( bottomA <= topB ) || ( topA >= bottomB ) || ( rightA <= leftB ) || ( leftA >= rightB )  ){
				//A collision is detected
				return true; 
			}
			else {
			//If neither set of collision boboxes touched
			return false; 
			}
}


void Square::move () {
	
	 box.x += xVel;

	if ( (box.x <= 0) || (box.x + SQUARE_WIDTH > SCREEN_WIDTH) || check_collision( box, wall) ) {
		box.x -= xVel;
}
	box.y += yVel;

	if ( (box.y <= 0) || (box.y + SQUARE_HEIGHT > SCREEN_HEIGHT) || check_collision( box, wall) ) {
		box.y -= yVel;
	}


}


void Square::handle_input() {
       //If a key was pressed

    if( event.type == SDL_KEYDOWN )
    {
        //Adjust the velocity
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: yVel -= SQUARE_HEIGHT / 2; break;
            case SDLK_DOWN: yVel += SQUARE_HEIGHT / 2; break;
            case SDLK_LEFT: xVel -= SQUARE_WIDTH / 2; break;
            case SDLK_RIGHT: xVel += SQUARE_WIDTH / 2; break;
        }
    }
    //If a key was released
     if( event.type == SDL_KEYUP )
    {
        //Adjust the velocity
        switch( event.key.keysym.sym )
        {
            case SDLK_UP: yVel -= SQUARE_HEIGHT / 2; break;
            case SDLK_DOWN: yVel += SQUARE_HEIGHT / 2; break;
            case SDLK_LEFT: xVel -= SQUARE_WIDTH / 2; break;
            case SDLK_RIGHT: xVel += SQUARE_WIDTH / 2; break;
        }
    }
}

void Square::show()
{
    //Show the square
    apply_surface( box.x, box.y, boxgraphic, screen); 
}


void clean_up()
{
    //Free the surfaces
    SDL_FreeSurface( background );
	SDL_FreeSurface( missMessage );
	SDL_FreeSurface( collideMessage );
	SDL_FreeSurface (boxgraphic);
	SDL_FreeSurface (seconds);
	SDL_FreeSurface (screen);
    //Close the font
    TTF_CloseFont( font );

    //Quit SDL_ttf
    TTF_Quit();

    //Quit SDL
    SDL_Quit();
}


SDL_Surface *load_image( std::string filename )
{
    //The image that's loaded
    SDL_Surface* loadedImage = NULL;

    //The optimized surface that will be used
    SDL_Surface* optimizedImage = NULL;

    //Load the image
    loadedImage = SDL_LoadBMP( filename.c_str() );

    //If the image loaded
    if( loadedImage != NULL )
    {
        //Create an optimized surface
        optimizedImage = SDL_DisplayFormat( loadedImage );

        //Free the old surface
        SDL_FreeSurface( loadedImage );

        //If the surface was optimized
        if( optimizedImage != NULL )
        {
            //Color key surface
            SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF ) );
        }
    }

    //Return the optimized surface
    return optimizedImage;
}
bool init()
{
    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return false;
    }

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
        return false;
    }

    //Initialize SDL_ttf
    if( TTF_Init() == -1 )
    {
        return false;
    }

    //Set the window caption
    SDL_WM_SetCaption( "Press an Arrow Key", NULL );

    //If everything initialized fine
    return true;
}

bool load_files()
{
    //Load the background image
    background = load_image( "background.bmp" );
	boxgraphic = load_image( "Square.bmp" );

    font = TTF_OpenFont( "lazy.ttf", 20 );
    //Open the font

    //If there was a problem in loading the background
	if( background == NULL || boxgraphic == NULL )
    {
        return false;
    }

    //If there was an error in loading the font
    if( font == NULL )
    {
        return false;
    }

    //If everything loaded fine
    return true;
}


int main ( int argc, char* args[] ) {

	int frame = 0;
	
	Square mySquare;

	bool running = false;

	Timer fps;
	Timer update;

	if (init() == false)  {
		return false;
	}
	if (load_files() == false ) {
		return false;
	}
	wall.x = 300;
	wall.y = 40;
	wall.w = 40;
	wall.h = 400;

	//Generate the message surfaces	
	collideMessage = TTF_RenderText_Solid( font, "Collision detected!", textColor );
    missMessage = TTF_RenderText_Solid( font, "No collisions detected.", textColor );
	message = TTF_RenderText_Solid( font, "Testing Frame Rate", textColor );

	//While the user hasn't quit
    while( quit == false )
	{
			update.start();

			fps.start();

			//If message needs to be displayed
			std::stringstream time;

			//If there's an event to handle
        if( SDL_PollEvent( &event ) )
		{
			mySquare.handle_input();

			if( event.type == SDL_QUIT )
            {
				fps.stop();
				update.stop();
                //Quit the program
                quit = true;
			 }
		}

		mySquare.move();

		SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF,0xFF, 0xFF ) );
		SDL_FillRect( screen, &wall, SDL_MapRGB( screen->format, 0x77, 0xFF, 0x77 ) );

		mySquare.show();

		if (running == true ) {
			time << "Timer: " << fps.get_ticks();
		}

		seconds = TTF_RenderText_Solid( font, time.str().c_str(), textColor);
		apply_surface ( 300,20,seconds,screen);

		apply_surface( ( SCREEN_WIDTH - message->w ) / 2, ( ( SCREEN_HEIGHT + message->h * 2 ) / FRAMES_PER_SECOND ) * ( frame % FRAMES_PER_SECOND ) - message->h, message, screen );
		

		        if( SDL_Flip( screen ) == -1 )
        {
            return 1;
		}
			frame+=1;

		if ( update.get_ticks() > 1000 ) {

		std::stringstream caption;
		caption << "Average number of frames per second " << frame / ( fps.get_ticks() / 1000.f );
		SDL_WM_SetCaption ( caption.str().c_str(), NULL );
		update.start();
		}
}


    //Clean up
    clean_up();
	return 0;
}
What happen when I run this is the box will only move up and down, after three keypresses, and even then its all the way to the edge of the screen. I've been over it several times, I don't have a clue, though its probably something very simple.

I also don't know how to debug an SDL program using a breakpoint, when I set one during a loop. It stops, minimizes the SDL program to the taskbar,then I can't open up the program to send a keypress! How would you do something like that?

The other thing I wanted to talk about was I have a lot of what I consider to be good ideas for games, and yet they keep getting turned into something in another game by a big developer, before I've even finished college, or made a game. Its really frustrating and disappointing. What would you guys say about that?

And lastly, I would love to have some friends who are into game development, and maybe start a project, except I don't have any good friends who are into all that! I'm above searching online for team members, because for one thing the majority of "applicants" are kids who know nothing and think it would be great to make a game but lack the talent. Any legitimate team members would be online, at risk to leak things, in my experience,and located halfway around the world! I may be just a beginner, but as you can tell I've got some big plans. I am quite an introvert, but I'm crawling out of my cave... I would like to make friends at school who are into this, I don't know how to find them. No computer classes yet...
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
Rebornxeno
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 85
Joined: Thu Jun 23, 2011 11:12 am

Re: Ideas, stoopid code, and friends

Post by Rebornxeno »

In your check collision function, there is a line I believe is slightly off!

rightB = B.y + B.w;

I think it should be rightB = B.x + B.w, and the line right above should use B.x too!

cheers
User avatar
Ultra64
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 3
Joined: Thu Jun 28, 2012 8:40 pm

Re: Ideas, stoopid code, and friends

Post by Ultra64 »

I have problems too on the same end of finding people to code with. I am in my first year of college, and still haven't found people who are into this yet haha, Its pretty demotivating sometimes. haha
It's what they don't tell you that I can't say.
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Re: Ideas, stoopid code, and friends

Post by Aspirer »

Ok, I missed that, thanks. And I figured out what else went wrong, I was combining code from two different lessons into one! I didn't realize I was reading the motion and collision tutorials which are similar.


Also the statement:

Code: Select all

	int xVel,yVel = 0;
did not do what I intentioned. I thought I saw something somewhere, which assigned the same value to multiple variables on one line that way. Instead it just declare uninitialized, and initialized variables. Makes sense, due to the syntax.
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
User avatar
Ultra64
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 3
Joined: Thu Jun 28, 2012 8:40 pm

Re: Ideas, stoopid code, and friends

Post by Ultra64 »

lol my bad. didn't mean for that to post like 4 times :P
It's what they don't tell you that I can't say.
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Re: Ideas, stoopid code, and friends

Post by Aspirer »

How come no one's replying? Is the forum slow lately?
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
User avatar
Ginto8
ES Beta Backer
ES Beta Backer
Posts: 1064
Joined: Tue Jan 06, 2009 4:12 pm
Programming Language of Choice: C/C++, Java

Re: Ideas, stoopid code, and friends

Post by Ginto8 »

Change the line

Code: Select all

if( SDL_PollEvent( &event ) )
to while() instead.

As it is, your program processes at most one event per frame, while the OS and the user are quite happy to throw a few more at it during that time. while() ensures that the event queue empties each frame.
Quit procrastinating and make something awesome.
Ducky wrote:Give a man some wood, he'll be warm for the night. Put him on fire and he'll be warm for the rest of his life.
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Re: Ideas, stoopid code, and friends

Post by Aspirer »

Thank you ginto. That was old code, and I discovered and fixed that part on my own. I've actually gotten the whole thing to work now.

I swear when it runs, but doesn't do as its intended, that's the hardest problem to find the root of...

BTW does anyone care to comment on anything else I mentioned? ;D
Last edited by Aspirer on Sun Jul 01, 2012 1:58 pm, edited 1 time in total.
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
Rebornxeno
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 85
Joined: Thu Jun 23, 2011 11:12 am

Re: Ideas, stoopid code, and friends

Post by Rebornxeno »

I think a lot of people have good ideas, and that is why many ideas you have yourself end up being thought up by AAA companies. Just look how many games are super similar! I have some pretty nifty ideas that I've never seen in ANY game though, so just keep thinking. Being original counts a whole lot!

I have yet to meet another developer in person. Yep! Crazy right? I don't go to school for it though, so i'm sure that has a lot to do with it. If you are really interested in starting a project though, maybe get one of your ideas to a running/working point, and try to pitch it to some people who might be interested in helping you. Like here on these forums!

Debugging is a huge topic on its own. When you set a breakpoint and the debugger kicks in, the program halts where the breakpoint was tripped. That's why you can't give it any more input, and it will remain frozen until you take off the breakpoint or tell the debugger to let the program continue. Though what's useful about setting breakpoints is that the program can't continue, and you are given options on how to continue from that point! For instance, you can step through the program's instructions one line at a time, and see exactly what might be causing a problem. This might not be what you were asking about, but I couldn't exactly understand what you were trying to type.
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Re: Ideas, stoopid code, and friends

Post by Aspirer »

Yeah, I think you're right about people. Sounds like something mom would say...

I'm going for a degree in graphic/web design right now, school resumes for me this fall. I plan on going and getting a degree in CS (or something game related) after that. Going to school twice for two different things may not make sense but, its a long story. I'm not rich by any standards.

I met a bunch of other programmers in HS in a few programming classes, but I didn't really make friends. The year I took those classes, I had a rough time with the other students. I was curious to know why they were in the class, but I didn't ask, I assume they wanted to make games. I even saw someone make a pac-man clone, but I'm still wondering how he did that.
Being original counts a whole lot!
Believe me, that's one thing I strive for, and I put a lot of pain and effort into that.
Debugging is a huge topic on its own. When you set a breakpoint and the debugger kicks in, the program halts where the breakpoint was tripped. That's why you can't give it any more input, and it will remain frozen until you take off the breakpoint or tell the debugger to let the program continue. Though what's useful about setting breakpoints is that the program can't continue, and you are given options on how to continue from that point! For instance, you can step through the program's instructions one line at a time, and see exactly what might be causing a problem. This might not be what you were asking about, but I couldn't exactly understand what you were trying to type.
I was saying I don't know how to debug a program when it takes events. Specifically because of what you outlined in that post. I can't send keystrokes if I've paused the program. Just curious to know how to debug something like that using the breakpoints.
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
Rebornxeno
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 85
Joined: Thu Jun 23, 2011 11:12 am

Re: Ideas, stoopid code, and friends

Post by Rebornxeno »

Ahh, when you debug events, you have to set the breakpoint on the event you want to check. I'm not even sure myself on how to send input to a stopped program to trigger an event, so I just set the breakpoints on the events, though there's probably a way.
User avatar
bbguimaraes
Chaos Rift Junior
Chaos Rift Junior
Posts: 294
Joined: Wed Apr 11, 2012 4:34 pm
Programming Language of Choice: c++
Location: Brazil
Contact:

Re: Ideas, stoopid code, and friends

Post by bbguimaraes »

The lazy answer is: "there is no way to do that".

But I can't think of a situation where this level of debugging would be necessary. If you could give us an example of what you're trying to debug, maybe we could provide you with a better explanation on how it can be done.
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Ideas, stoopid code, and friends

Post by dandymcgee »

You don't use breakpoints in that case. You use logging, or my personal favorite, message boxes (MessageBox.Show("Debug") in C#, alert('Debug') in javascript, etc.)
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
Aspirer
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 47
Joined: Tue May 01, 2012 8:20 pm

Re: Ideas, stoopid code, and friends

Post by Aspirer »

Ahh, when you debug events, you have to set the breakpoint on the event you want to check.
That helped! Thank you.

I just wanted to debug some functions which were called in a loop by an event. Since when you set a breakpoint on the loop it stops and won't let you back to the program you've written. There's no way to send a keystroke because the program is paused, and its in a loop.
"We got more information out of a German general with a game of chess or Ping-Pong than they do today, with their torture" --Henry Kolm
User avatar
bbguimaraes
Chaos Rift Junior
Chaos Rift Junior
Posts: 294
Joined: Wed Apr 11, 2012 4:34 pm
Programming Language of Choice: c++
Location: Brazil
Contact:

Re: Ideas, stoopid code, and friends

Post by bbguimaraes »

If I understand you correctly, you have to set the breakpoint on the function. Then, run the application and trigger the event (click on a button, type text, etc, depends on the type of event).
Post Reply