Reputation: 19
I have made a program using SDL that has a lot of keyboard and mouse input. At the moment the main SDL loop is almost 400 lines long, entirely because of the large number of separate cases in the switch function.
The whole program is about 1000 lines, and I am looking to split it up into separate files/modules. I would like to have a separate file for keyboard input and another for mouse input, each containing a function that will be called in the main SDL loop. I'm sure I saw an example a while ago that did this, but I can't find it.
Currently my code looks something like this
while( !quit && ( SDL_WaitEvent(&event) ) )
{
switch (event.type)
{
case SDL_MOUSEBUTTONDOWN:
{
switch(event.button.button)
{
case SDL_BUTTON_LEFT:
case SDL_BUTTON_MIDDLE:
case SDL_BUTTON_RIGHT:
}
}
case SDL_KEYDOWN:
switch (event.key.keysym.sym)
{
case SDLK_r:
case SDLK_i:
case SDLK_f:
case SDLK_g:
case SDLK_l:
I would like it to be like this...
while( !quit && ( SDL_WaitEvent(&event) ) )
{
switch (event.type)
{
HandleMouseInput();
HandleKeyboardInput();
I hope this makes sense and isn't too silly of a question, but I just can't seem to get started on this after a lot of Googling and thinking. I've never really written a program this large before and I'm not used to multiple source files.
Upvotes: 0
Views: 440
Reputation: 7773
A simple way to handle this would be to create an enum for the type of events you have, something like:
enum EEventCategory
{
EventCategory_Keyboard,
EventCategory_Mouse,
EventCategory_System
};
Then create a simple method that checks the event.type
and returns the category:
EEventCategory GetEventCategory(Uint8 in_type)
{
switch(in_type)
{
case SDL_KEYDOWN:
case SDL_KEYUP:
return EventCategory_Keyboard;
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
return EventCategory_Mouse;
// See SDL_events.h for more event categories...
default:
return EventCategory_System;
}
}
Then you could change your loop for something like:
while( !quit && ( SDL_WaitEvent(&event) ) )
{
switch (GetEventCategory(event.type))
{
case EventCategory_Keyboard:
HandleKeyboardInput(event);
break;
case EventCategory_Mouse:
HandleMouseInput(event);
break;
case EventCategory_System:
HandleSystemEvent(event);
break;
default:
assert(false); // unhandled event
}
}
Upvotes: 1