SDL drawing program is Freezing

392 views Asked by At

I'm not sure why my program is freezing after drawing the sixth square. It's frustrating. I mean it's just the same code over and over again, why is it executable the first 6 times and not the 7th? :/

Here is my code:

#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<conio.h>
#include<SDL.h>
using namespace std;

int main (int ,char**)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    int ProcN=0;
    int PageN;
    int TProc=0;
    int TPage;
    int FrameN=0;
    srand(time(NULL));
    SDL_Surface *screen;
    screen=SDL_SetVideoMode(860,540,32,SDL_SWSURFACE);

    Uint32 white=SDL_MapRGB(screen->format,0xff,0xff,0xff);
    Uint32 green=SDL_MapRGB(screen->format,0x22,0xff,0x22);
    Uint32 yellow=SDL_MapRGB(screen->format,0xff,0xbb,0x11);

    bool isrunning=true;
    const int fps=40;
    Uint32 start;
    Uint8 *keys = SDL_GetKeyState(NULL);

    SDL_FillRect(screen,&screen->clip_rect,white);  
    SDL_Rect rect[20];
    int ff=0;
    for(int i=0;i<4;i++)
    {
        for(int k=0;k<5;k++)
        {
            rect[ff].x=100+(k)*100+(k)*10;
            rect[ff].y=100+(i)*10+(i)*100;
            rect[ff].w=100;
            rect[ff].h=100;
            SDL_FillRect(screen,&rect[ff],yellow);

            printf("%d\t%d\t%d\n",ff,rect[ff].x,rect[ff].y);
            ff++;
            SDL_Flip(screen);
            SDL_Delay(1000);
        } 
    }

    SDL_Flip(screen);
}
1

There are 1 answers

2
doqtor On BEST ANSWER

It's because you don't process SDL events. SDL is quite low level and that needs to be done manually. In general you want to process them frequently enough where the plotting loops are so that you can move the window and can receive keyboard and mouse events. To fix your code replace line SDL_Delay(1000); with:

int cnt = 0;
while(++cnt < 1000)
{
    SDL_Event event;
    SDL_PollEvent( &event );
    SDL_Delay(1);
}