سلام!
پاسخ تمرین سری قبل را می توانید در کد زیر مشاهده کنید.
#include <iostream>
#include <string>
#include "SDL/SDL.h"
using namespace std;
void closeProgram () {
SDL_Quit();
exit( 0 );
}
bool init( SDL_Surface *screen ) {
bool returnValue = true;
if ( SDL_Init( SDL_INIT_EVERYTHING ) == -1 ){
cout << "Failed to init SDL library; Error: " << SDL_GetError() << endl;
returnValue = false;
}
else {
screen = SDL_SetVideoMode( 640, 480, 32, SDL_HWSURFACE );
if ( screen == NULL ){
cout << "Failed to make the window; Error: " << SDL_GetError() << endl;
returnValue = false;
}
}
return returnValue;
}
string eventType( SDL_Event event ) {
string returnValue;
if ( event.type == SDL_KEYDOWN )
returnValue.append( SDL_GetKeyName( event.key.keysym.sym ) ).append( " is down now!" );
if ( event.type == SDL_KEYUP )
returnValue.append( SDL_GetKeyName( event.key.keysym.sym ) ).append( " is up now!" );
return returnValue;
}
string keyModifiers( SDL_Event event ) {
string returnValue;
if ( event.type == SDL_KEYDOWN )
if ( event.key.keysym.mod != 0 ){
if ( event.key.keysym.mod & KMOD_CTRL ) returnValue.append( "Control is down!" );
if ( event.key.keysym.mod & KMOD_ALT ) returnValue.append( "Alt is down!" );
if ( event.key.keysym.mod & KMOD_SHIFT ) returnValue.append( "Shift is down!" );
}
return returnValue;
}
string mouseModifiers( SDL_Event event, bool* state ){
string returnValue;
if ( event.type == SDL_MOUSEMOTION ){
for ( int i = 0; i < 323; i++ )
if ( state[ i ] ){
returnValue.append( "Down keys: " );
break;
}
for ( int i = 0; i < 323; i++ )
if ( state[ i ] )
returnValue.append( SDL_GetKeyName( i ) ).append( " " );
}
return returnValue;
}
void handleEvent( SDL_Event event, bool* state ) {
// Part A
cout << eventType( event ) << ' ';
// Part B
cout << keyModifiers( event ) << ' ';
// Part C
if ( event.type == SDL_KEYDOWN )
state[ event.key.keysym.sym ] = true;
if ( event.type == SDL_KEYUP )
state[ event.key.keysym.sym ] = false;
cout << mouseModifiers( event, state ) << ' ';
cout << endl;
}
int main () {
SDL_Surface *screen;
if ( !init( screen ) )
exit( 1 );
bool state[ 323 ];
for ( int i = 0; i < 323; i++)
state[ i ] = false;
SDL_Event event;
while ( 1 ) {
while ( SDL_PollEvent( &event ) ){
if ( event.type == SDL_QUIT )
closeProgram();
handleEvent( event, state );
}
}
}
موفق باشید!