Have a variable hold the previous keystate.
I added that and cleaned your code up a little
(changes are listed in the comments):
Code: Select all
#include <SDL/SDL.h>
// the C++ const is a better choice than the C #define
const int SCREEN_WIDTH 640;
const int SCREEN_HEIGHT 480;
// the { doesn't have to be on the same line as main(), but since I'm editing it, and that's my style,
// that's how I made it
int main (int argc, char *argv[]) {
// moved this here because global vars are bad practice
SDL_Surface *buffer = NULL;
// variables of the same type can be declared in a comma-separated list
// and bools are by default false
// gDown is a bool of whether or not G was down last frame
bool grid,gDown;
SDL_Event event;
// calling functions and declaring variables in a mishmosh is bad taste, so I separated the two
SDL_Init(SDL_INIT_VIDEO);
buffer = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE);
SDL_WM_SetCaption("Window", NULL);
// an infinite loop
while(true) {
// inside of {'s, there should be indentation
SDL_FillRect(buffer,NULL,0x000000);
SDL_Rect area = {520, 360, (SCREEN_WIDTH -120), (SCREEN_HEIGHT -120)}; //{x,y,w,h}
SDL_FillRect(buffer,&area,0xBBBBBB);
Uint8 *key = SDL_GetKeyState (NULL);
// in if()'s, {s are only needed for multi-line actions
// ! is the opposite when it comes to bools
// if b is true, then !b is false
// and vice versa
if(key[SDLK_g] && !gDown)
grid = !grid;
gDown = key[SDLK_g];
// if(x) is basically the same as if((bool)x == true), so you don't need the "== true"
// and again, the { on the same line is just a stylistic preference
if(grid) {
for (int i = 0; i < SCREEN_WIDTH; i+=40) {
SDL_Rect grid_vertical = {i, 0, 2, SCREEN_HEIGHT};
SDL_FillRect(buffer,&grid_vertical,0xAAAAAA);
}
for (int i = 0; i < SCREEN_HEIGHT; i+=40) {
SDL_Rect grid_horizontal = {0, i, SCREEN_WIDTH, 2};
SDL_FillRect(buffer,&grid_horizontal,0xAAAAAA);
}
}
SDL_Flip(buffer);
while(SDL_PollEvent(&event)) {
// goto should only be used in situations like this, where there are nested loops
// otherwise, STAY AWAY FROM THEM
if (event.type == SDL_QUIT)
goto nested_loop_break;
}
}
nested_loop_break:
SDL_Quit();
return 0;
}
In case anyone bitches about the goto, it was ONLY for breaking out of nested loops. I have a thing against "done" variables for main game loops, so I prefer things like break. But since break wouldn't provide the wanted affect, I went with a goto for the SOLE PURPOSE of breaking out of the nested loop. AND I made an explicit comment stating NOT to use gotos in any other situation.
Edit: now WHY was I the only one to help with the overall bad practices? You people obviously forgotten what it's like to be a newbie
.
Edit 2: made buffer local rather than global