bool CTarget::choose_single_target(bool monster, std::vector<CActor*>& Friend, std::vector<CActor*>& Enemy) { int ch, pos = 0; do { if (monster && Enemy.size() == 0) monster = !monster; else if (!monster && Friend.size() == 0) monster = !monster; clear(); if (monster) insert(Enemy[pos]); else insert(Friend[pos]); if (Party.battle) Party.battle->draw_monsters(*this); Party.draw(rightWindow, *this); switch (ch = _getch()) { case _KEY_UP: pos--; break; case _KEY_DOWN: pos++; break; case _KEY_LEFT: case _KEY_RIGHT: monster = !monster; break; case 'C': if (Party.battle) { Party.view_init_cards = !Party.view_init_cards; Party.battle->draw(); } break; } if (monster) { if (pos > (int)Enemy.size() - 1) pos = 0; else if (pos < 0) pos = Enemy.size() - 1; } if (!monster) { if (pos > (int)Friend.size() - 1) pos = 0; else if (pos < 0) pos = Friend.size() - 1; } } while (ch != KEY_ACCEPT && ch != _KEY_CANCEL); if (Party.battle) Party.battle->draw(); else Party.draw(rightWindow); if (ch == _KEY_CANCEL) return false; return true; }
void main() { print_output(); _getch(); }
int boot_menu(int argc, wchar_t *argv[]) { ldr_config conf; int resl; int is_small; is_small = is_param(L"-small"); do { if ( (argc == 3) && (wcscmp(argv[2], L"-enum") == 0) ) { wchar_t s_size[MAX_PATH]; wchar_t h_name[MAX_PATH]; wchar_t *str; u64 size; int i, bd_1, bd_2; wprintf( L"--------------------------------------------------------------\n" L"HDD | name | size | bootable | bootloader\n" L"----+--------------------------+---------+----------+-----------\n"); if (dc_get_boot_disk(&bd_1, &bd_2) != ST_OK) { bd_1 = bd_2 = -1; } for (i = 0; i < 100; i++) { if (size = dc_dsk_get_size(i, 0)) { dc_format_byte_size(s_size, sizeof_w(s_size), size); if (dc_get_hw_name(i, 0, h_name, sizeof_w(h_name)) != ST_OK) { h_name[0] = 0; } if (dc_get_mbr_config(i, NULL, &conf) == ST_OK) { str = L"installed"; } else { str = L"none"; } wprintf( L"hd%d | %-24s | %-8s| %-8s | %s\n", i, h_name, s_size, (i == bd_1) || (i == bd_2) ? L"yes":L"no", str ); } } resl = ST_OK; break; } if ( (argc >= 4) && (wcscmp(argv[2], L"-setmbr") == 0) ) { int d_num; if (dsk_num(argv[3], &d_num) == 0) { resl = ST_OK; break; } if ( (resl = dc_set_boot_interactive(d_num, is_small)) == ST_OK) { wprintf(L"Bootloader successfully installed to %s\n", argv[3]); } break; } if ( (argc == 4) && (wcscmp(argv[2], L"-delmbr") == 0) ) { int d_num; if (dsk_num(argv[3], &d_num) == 0) { resl = ST_OK; break; } if ( (resl = dc_unset_mbr(d_num)) == ST_OK ) { wprintf(L"Bootloader successfully removed from %s\n", argv[3]); } break; } if ( (argc == 4) && (wcscmp(argv[2], L"-updmbr") == 0) ) { int d_num; if (dsk_num(argv[3], &d_num) == 0) { resl = ST_OK; break; } if ( (resl = dc_update_boot(d_num)) == ST_OK ) { wprintf(L"Bootloader on %s successfully updated\n", argv[3]); } break; } if ( (argc >= 4) && (wcscmp(argv[2], L"-setpar") == 0) ) { if ( (resl = dc_set_boot(argv[3], 0, is_small)) == ST_FORMAT_NEEDED ) { wprintf( L"Removable media not correctly formatted\n" L"Format media? (Y/N)\n" ); if (tolower(_getch()) == 'y') { resl = dc_set_boot(argv[3], 1, is_small); } else { resl = ST_OK; break; } } if (resl != ST_OK) { break; } if ( (resl = dc_mbr_config_by_partition(argv[3], 0, &conf)) != ST_OK ) { break; } conf.options |= OP_EXTERNAL; conf.boot_type = BT_AP_PASSWORD; boot_conf_menu( &conf, L"Please set bootloader options:"); if ( (resl = dc_mbr_config_by_partition(argv[3], 1, &conf)) == ST_OK ) { wprintf(L"Bootloader successfully installed\n"); } break; } if ( (argc >= 4) && (wcscmp(argv[2], L"-makeiso") == 0) ) { if ( (resl = dc_make_iso(argv[3], is_small)) != ST_OK ) { break; } if ( (resl = dc_get_mbr_config(0, argv[3], &conf)) != ST_OK ) { break; } conf.options |= OP_EXTERNAL; conf.boot_type = BT_MBR_FIRST; boot_conf_menu( &conf, L"Please set bootloader options:"); if ( (resl = dc_set_mbr_config(0, argv[3], &conf)) == ST_OK ) { wprintf(L"Bootloader .iso image successfully created\n", argv[3]); } break; } if ( (argc >= 4) && (wcscmp(argv[2], L"-makepxe") == 0) ) { if ( (resl = dc_make_pxe(argv[3], is_small)) != ST_OK ) { break; } if ( (resl = dc_get_mbr_config(0, argv[3], &conf)) != ST_OK ) { break; } conf.options |= OP_EXTERNAL; conf.boot_type = BT_MBR_FIRST; boot_conf_menu( &conf, L"Please set bootloader options:"); if ( (resl = dc_set_mbr_config(0, argv[3], &conf)) == ST_OK ) { wprintf(L"Bootloader PXE image successfully created\n", argv[3]); } break; } if ( (argc == 4) && (wcscmp(argv[2], L"-config") == 0) ) { int d_num; wchar_t *file; int ispar; if ( ((argv[3][1] == L':') && (argv[3][2] == 0)) || ((argv[3][0] == L'\\') && (argv[3][5] == L':')) ) { ispar = 1; } else { if (dsk_num(argv[3], &d_num) == 0) { file = argv[3]; d_num = 0; } else { file = NULL; } ispar = 0; } if (ispar != 0) { resl = dc_mbr_config_by_partition(argv[3], 0, &conf); } else { resl = dc_get_mbr_config(d_num, file, &conf); } if (resl != ST_OK) { break; } boot_conf_menu( &conf, L"Please change bootloader options:"); if (ispar != 0) { resl = dc_mbr_config_by_partition(argv[3], 1, &conf); } else { resl = dc_set_mbr_config(d_num, file, &conf); } if (resl == ST_OK) { wprintf(L"Bootloader configuration successfully changed\n"); } break; } } while (0); return resl; }
int main(int argc, char * argv[]) { FMOD_SYSTEM *system; FMOD_SOUND *sound1, *sound2, *sound3; FMOD_SOUNDGROUP *soundgroup; FMOD_CHANNEL *channel[3]; FMOD_RESULT result; int key=0; int mode=1; unsigned int version; printf("======================================================================\n"); printf("soundgroups Example. Copyright (c) Firelight Technologies 2004-2011.\n"); printf("======================================================================\n"); printf("This example plays 3 sounds in a sound group, demonstrating the effect\n"); printf("of the three different sound group behavior modes\n"); printf("======================================================================\n\n"); /* Create a System object and initialize. */ result = FMOD_System_Create(&system); ERRCHECK(result); result = FMOD_System_GetVersion(system, &version); ERRCHECK(result); if (version < FMOD_VERSION) { printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION); return 0; } result = FMOD_System_Init(system, 100, FMOD_INIT_NORMAL, 0); ERRCHECK(result); /* Load some sound files from the hard disk. */ result = FMOD_System_CreateSound(system, "../media/drumloop.wav", FMOD_HARDWARE | FMOD_LOOP_NORMAL, 0, &sound1); ERRCHECK(result); result = FMOD_System_CreateSound(system, "../media/jaguar.wav", FMOD_HARDWARE | FMOD_LOOP_NORMAL, 0, &sound2); ERRCHECK(result); result = FMOD_System_CreateSound(system, "../media/swish.wav", FMOD_HARDWARE | FMOD_LOOP_NORMAL, 0, &sound3); ERRCHECK(result); /* Create the sound group with the following attributes: Name = MyGroup MaxAudible = 1 Behavior = Mute */ result = FMOD_System_CreateSoundGroup(system, "MyGroup", &soundgroup); ERRCHECK(result); result = FMOD_SoundGroup_SetMaxAudible(soundgroup, 1); ERRCHECK(result); result = FMOD_SoundGroup_SetMaxAudibleBehavior(soundgroup, FMOD_SOUNDGROUP_BEHAVIOR_MUTE); ERRCHECK(result); result = FMOD_SoundGroup_SetMuteFadeSpeed(soundgroup, 2); ERRCHECK(result); /* Put the sounds in the sound group */ result = FMOD_Sound_SetSoundGroup(sound1, soundgroup); ERRCHECK(result); result = FMOD_Sound_SetSoundGroup(sound2, soundgroup); ERRCHECK(result); result = FMOD_Sound_SetSoundGroup(sound3, soundgroup); ERRCHECK(result); /* Play the sounds (two will be muted because of the behavior mode) */ result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound1, FALSE, &channel[0]); ERRCHECK(result); result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound2, FALSE, &channel[1]); ERRCHECK(result); result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound3, FALSE, &channel[2]); ERRCHECK(result); /* Display help */ printf("=========================================================================\n"); printf("Press 1 BEAVIOR_FAIL \n"); printf(" 2 BEAVIOR_MUTE \n"); printf(" 3 BEAVIOR_STEALLOWEST\n"); printf(" Q Play/stop drumloop sound\n"); printf(" W Play/stop Jaguar sound\n"); printf(" E Play/stop shwish sound\n"); printf(" ESC Quit\n"); printf("=========================================================================\n"); do { float audibility; int index; if( _kbhit()) { key = _getch(); if( key=='1' ) { result = FMOD_SoundGroup_SetMaxAudibleBehavior(soundgroup, FMOD_SOUNDGROUP_BEHAVIOR_FAIL); ERRCHECK(result); } if( key=='2' ) { result = FMOD_SoundGroup_SetMaxAudibleBehavior(soundgroup, FMOD_SOUNDGROUP_BEHAVIOR_MUTE); ERRCHECK(result); } if( key=='3' ) { result = FMOD_SoundGroup_SetMaxAudibleBehavior(soundgroup, FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST); ERRCHECK(result); } if( key=='q' ) { result = FMOD_Channel_GetIndex(channel[0],&index); if (!index) { result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound1, FALSE, &channel[0]); if (result!=FMOD_ERR_MAXAUDIBLE) { ERRCHECK(result); } } else { result = FMOD_Channel_Stop(channel[0]); ERRCHECK(result); } } if( key=='w' ) { result = FMOD_Channel_GetIndex(channel[1],&index); if (!index) { result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound2, FALSE,&channel[1]); if (result!=FMOD_ERR_MAXAUDIBLE) { ERRCHECK(result); } } else { result = FMOD_Channel_Stop(channel[1]); ERRCHECK(result); } } if( key=='e' ) { result = FMOD_Channel_GetIndex(channel[2],&index); if (!index) { result = FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, sound3, FALSE,&channel[2]); if (result!=FMOD_ERR_MAXAUDIBLE) { ERRCHECK(result); } } else { result = FMOD_Channel_Stop(channel[2]); ERRCHECK(result); } } } // print out a small visual display { char s[80]; char s1[6]; char s2[3][6]; int i; FMOD_SOUNDGROUP_BEHAVIOR behavior; FMOD_SoundGroup_GetMaxAudibleBehavior(soundgroup, &behavior); switch (behavior) { case FMOD_SOUNDGROUP_BEHAVIOR_FAIL : { sprintf(s1,"FAIL"); break; } case FMOD_SOUNDGROUP_BEHAVIOR_MUTE : { sprintf(s1,"MUTE"); break; } case FMOD_SOUNDGROUP_BEHAVIOR_STEALLOWEST : { sprintf(s1,"STEAL"); break; } }; for (i=0; i<3; i++) { FMOD_Channel_GetAudibility(channel[i], &audibility); if (!audibility) { result = FMOD_Channel_GetIndex(channel[i], &index); if (!index) { sprintf(s2[i], "STOP"); } else { sprintf(s2[i], "MUTE"); } } else { sprintf(s2[i], "PLAY"); } } sprintf(s, "MODE:%6s | SOUND1: %s | SOUND2: %s | SOUND3: %s |", s1, s2[0], s2[1], s2[2]); printf("%s\r", s); } result = FMOD_System_Update(system); ERRCHECK(result); Sleep(10); }while (key!=27); return 0; }
void game::pause() { _getch(); // puts(""); // }
int main(int argc, char *argv[]) { FMOD_RESULT result; FMOD::EventSystem *eventsystem; FMOD::EventGroup *eventgroup; FMOD::Event *event; int key; printf("======================================================================\n"); printf("Programmer Sound. Copyright (c) Firelight Technologies 2006-2014.\n"); printf("======================================================================\n"); ERRCHECK(result = FMOD::EventSystem_Create(&eventsystem)); ERRCHECK(result = eventsystem->init(64, FMOD_INIT_NORMAL, 0, FMOD_EVENT_INIT_NORMAL)); ERRCHECK(result = eventsystem->setMediaPath((char *)MEDIA_PATH)); ERRCHECK(result = eventsystem->load("examples.fev", 0, 0)); ERRCHECK(result = eventsystem->getGroup("examples/FeatureDemonstration/SequencingAndStitching", FMOD_EVENT_DEFAULT, &eventgroup)); ERRCHECK(result = eventsystem->getSystemObject(&sys)); ERRCHECK(result = sys->createStream(FSB_NAME, FMOD_2D | FMOD_NONBLOCKING | FMOD_SOFTWARE, 0, &fsb)); initIndexMap(fsb); printf("======================================================================\n"); printf("Press 'Space' to start the 'Programmer Sound' event\n"); printf("Press '>' to increase sound index\n"); printf("Press '<' to decrease sound index\n"); printf("Press 'Esc' to quit\n"); printf("======================================================================\n"); printf("Sound index = %d\n", g_sound_index + 1); key = 0; do { if (_kbhit()) { key = _getch(); switch(key) { case ' ' : ERRCHECK(result = eventgroup->getEvent("ProgrammerSounds", FMOD_EVENT_DEFAULT, &event)); ERRCHECK(result = event->setCallback(eventcallback, 0)); ERRCHECK(result = event->start()); break; case '>' : case '.': ++g_sound_index; g_sound_index = (g_sound_index >= SOUND_INDEX_MAX) ? SOUND_INDEX_MAX - 1 : g_sound_index; printf("Sound index = %d\n", g_sound_index + 1); break; case '<' : case ',': --g_sound_index; g_sound_index = (g_sound_index < 0) ? 0 : g_sound_index; printf("Sound index = %d\n", g_sound_index + 1); break; } } ERRCHECK(result = eventsystem->update()); Sleep(10); } while (key != 27); ERRCHECK(result = eventsystem->unload()); ERRCHECK(result = fsb->release()); ERRCHECK(result = eventsystem->release()); return 0; }
/** Role : prepare frame rendering depending on status * Output : - */ void render_setRendering( CONFIG *pstParams, //parameters : status, timers, level, bonus float fPercentUpdate, //interpolation BALL *pstBall, //ball information : coord, speed PLAYER *astPlayers //players information: coord, offset, speed, score, bonus ) { /* display in-game frame */ if( pstParams->status == -2 ) { render_drawFrame( 0x0133, fPercentUpdate, pstParams, pstBall, astPlayers ); } /* display special frame (message, animation, pause) */ else { HANDLE hConsole = GetStdHandle( STD_OUTPUT_HANDLE ); COORD coord = { 0 }; switch( pstParams->status ) { /* NEW ROUND -> animation and reset */ case -7: render_drawFrame( 0x1113, fPercentUpdate, pstParams, pstBall, astPlayers ); /* start round if animation is over */ if( pstParams->bonus[0] >= 40 ) { pstParams->status = -2; pstParams->bonus[0] = 0; pstParams->clock[1] = 0; } break; /* NEW GAME -> instructions and wait */ case -1: coord.X = 6; coord.Y = 38; SetConsoleCursorPosition( hConsole, coord ); render_drawFrame( 0x0001, fPercentUpdate, pstParams, NULL, astPlayers ); /* message : useable commands */ if( pstParams->level != 4 ) //single player { SetConsoleTextAttribute( hConsole, 0x0F ); printf( " \x18\x19 " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "D\x82placer " ); SetConsoleTextAttribute( hConsole, 0x0F ); printf( "ESC " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "Afficher menu " ); SetConsoleTextAttribute( hConsole, 0x0F ); printf( "P " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "Mettre en pause" ); } else //2 players { SetConsoleTextAttribute( hConsole, 0x0F ); printf( "ZS " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "D\x82placer " ); SetConsoleTextAttribute( hConsole, 0x0F ); printf( "ESC " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "Menu " ); SetConsoleTextAttribute( hConsole, 0x0F ); printf( "P " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "Pause " ); SetConsoleTextAttribute( hConsole, 0x0F ); printf( "\x18\x19 " ); SetConsoleTextAttribute( hConsole, 0x07 ); printf( "D\x82placer" ); } /* message : instructions */ coord.X = 24; coord.Y = 19; SetConsoleCursorPosition( hConsole, coord ); printf( "Appuyez sur ENTER pour commencer." ); Sleep( 28 ); break; /* PAUSE -> animation */ case -3: coord.X = 35; coord.Y = 20; SetConsoleCursorPosition( hConsole, coord ); render_drawFrame( 0x0001, 0, pstParams, pstBall, astPlayers ); /* pause message */ if( pstParams->clock[0]%2 == 0 ) { SetConsoleTextAttribute( hConsole, 0x0F ); printf( "P A U S E" ); SetConsoleTextAttribute( hConsole, 0x07 ); } else { printf( "P A U S E" ); } Sleep( 28 ); break; /* ROUND END -> message and latence */ case -4: case -5: coord.X = 31; coord.Y = 19; SetConsoleCursorPosition( hConsole, coord ); render_drawFrame( 0x0103, 0, pstParams, NULL, astPlayers ); /* round message */ if( pstParams->level != 4 ) { if( pstParams->status == -4 ) printf( " Vous gagnez." ); else printf( " Vous perdez." ); } else { if( pstParams->status == -4 ) printf( "Le joueur 1 gagne." ); else printf( "Le joueur 2 gagne." ); } /* wait for one second */ if( pstParams->clock[1] > 1 ) { pstParams->status = -6; } Sleep( 28 ); break; /* GAME END -> message, latence and wait */ case -8: case -9: render_drawFrame( 0x0301, 0, pstParams, NULL, astPlayers ); /* message : results */ coord.X = 27; if( pstParams->level != 4 ) //single player { short sScore = 0; coord.Y = 17; SetConsoleCursorPosition( hConsole, coord ); if( pstParams->status == -8 ) printf( " Vous remportez la partie." ); else printf( " Vous avec perdu la partie." ); /* display details : difficulty */ coord.X = 31; coord.Y = 20; SetConsoleCursorPosition( hConsole, coord ); printf( "Difficult\x82 : " ); switch( pstParams->level ) { case 1: printf( "facile" ); break; case 3: printf( "expert" ); break; default: printf( "v\x82t\x82ran" ); } /* display details : time */ coord.X = 31; coord.Y = 21; SetConsoleCursorPosition( hConsole, coord ); printf( "Dur\x82\x65 jeu : %02hu:%02hu", pstParams->clock[0]/60, pstParams->clock[0]%60 ); /* display details : score */ coord.X = 31; coord.Y = 22; SetConsoleCursorPosition( hConsole, coord ); sScore = ( 2*astPlayers[0].score - astPlayers[1].score )*pstParams->level; if( sScore < 0 ) sScore = 0; printf( "Score moyen : %hd", sScore ); coord.Y = 25; } else //2 players { coord.Y = 19; SetConsoleCursorPosition( hConsole, coord ); if( pstParams->status == -8 ) printf( "Le joueur 1 gagne la partie." ); else printf( "Le joueur 2 gagne la partie." ); /* display details : time */ coord.X = 31; coord.Y = 21; SetConsoleCursorPosition( hConsole, coord ); printf( "Dur\x82\x65 partie : %02hu:%02hu", pstParams->clock[0]/60, pstParams->clock[0]%60 ); coord.Y = 23; } /* message : instructions */ Sleep( 800 ); coord.X = 19; SetConsoleCursorPosition( hConsole, coord ); printf( "Appuyez sur une touche pour revenir au menu." ); /* empty buffer and wait for reaction */ while( _kbhit() != 0 ) { _getch(); } do { _getch(); } while( _kbhit() != 0 ); pstParams->status = 1; render_clear(); break; }//switch }//else }//render_setRendering
int main(int argc, char *argv[]) { FMOD::System *system; FMOD::Sound *sound; FMOD::Channel *channel = 0; FMOD_RESULT result; int key; unsigned int version; /* Create a System object and initialize. */ result = FMOD::System_Create(&system); ERRCHECK(result); result = system->getVersion(&version); ERRCHECK(result); if (version < FMOD_VERSION) { printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION); return 0; } result = system->init(1, FMOD_INIT_NORMAL, 0); ERRCHECK(result); result = system->createStream("../media/wave.mp3", FMOD_HARDWARE | FMOD_LOOP_NORMAL | FMOD_2D, 0, &sound); ERRCHECK(result); printf("====================================================================\n"); printf("PlayStream Example. Copyright (c) Firelight Technologies 2004-2011.\n"); printf("====================================================================\n"); printf("\n"); printf("Press space to pause, Esc to quit\n"); printf("\n"); /* Play the sound. */ result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel); ERRCHECK(result); /* Main loop. */ do { if (_kbhit()) { key = _getch(); switch (key) { case ' ' : { bool paused; channel->getPaused(&paused); channel->setPaused(!paused); break; } case 'p' : { FMOD::ChannelGroup* masterGroup = NULL; system->getMasterChannelGroup(&masterGroup); if (masterGroup) { bool paused; masterGroup->getPaused(&paused); masterGroup->setPaused(!paused); } break; } } } system->update(); if (channel) { unsigned int ms; unsigned int lenms; bool playing; bool paused; result = channel->isPlaying(&playing); if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel->getPaused(&paused); if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = channel->getPosition(&ms, FMOD_TIMEUNIT_MS); if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE)) { ERRCHECK(result); } result = sound->getLength(&lenms, FMOD_TIMEUNIT_MS); if ((result != FMOD_OK) && (result != FMOD_ERR_INVALID_HANDLE)) { ERRCHECK(result); } printf("Time %02d:%02d:%02d/%02d:%02d:%02d : %s\r", ms / 1000 / 60, ms / 1000 % 60, ms / 10 % 100, lenms / 1000 / 60, lenms / 1000 % 60, lenms / 10 % 100, paused ? "Paused " : playing ? "Playing" : "Stopped"); } Sleep(10); } while (key != 27); printf("\n"); /* Shut down */ result = sound->release(); ERRCHECK(result); result = system->close(); ERRCHECK(result); result = system->release(); ERRCHECK(result); return 0; }
void main() { int arr[] = { 14,-2, 2, 16, -14, 27, -13, 82, -10,100 }; sub_arr(arr, 10); _getch(); }
int main(int argc, char* argv[]){ TetrisView tetrisView; int processType; int direction; DWORD tickCount; int isSetMainMenu = False; do{ TetrisView_ProcessMainMenu(&tetrisView); switch (tetrisView.mainMenu){ case START_MAIN_MENU: TetrisView_StartGame(&tetrisView); tickCount = GetTickCount(); while (True){ processType = AUTO; direction = DOWN; isSetMainMenu = False; while (True){ if (GetTickCount() - tickCount > TetrisView_GetDownMilliSecond(&tetrisView)){ processType = AUTO; direction = DOWN; tickCount = GetTickCount(); break; } if (_kbhit()){ int key = _getch(); if (key == 0xE0 && _kbhit()){ key = _getch(); if (key == UP_KEY_CODE){ processType = DIRECTION; direction = UP; break; } if (key == DOWN_KEY_CODE){ processType = DIRECTION; direction = DOWN; tickCount = GetTickCount(); break; } if (key == LEFT_KEY_CODE){ processType = DIRECTION; direction = LEFT; break; } if (key == RIGHT_KEY_CODE){ processType = DIRECTION; direction = RIGHT; break; } } else{ if (key == SPACE_BAR_KEY_CODE){ processType = DIRECT_DOWN; tickCount = GetTickCount(); break; } if (key == ESC_KEY_CODE){ TetrisView_PauseGame(&tetrisView); if (tetrisView.pauseMenu == MAIN_MENU_PAUSE_MENU){ isSetMainMenu = True; break; } processType = AUTO; tickCount = GetTickCount(); break; } if (key == L_KEY_CODE){ TetrisView_MakeHold(&tetrisView); } } } } //for selecting main menu at pause menu if (isSetMainMenu){ break; } TetrisView_ProcessGame(&tetrisView, processType, direction); if (tetrisView.endMenu == RANKING_END_MENU){ TetrisView_AddRanking(&tetrisView); TetrisView_ShowRanking(&tetrisView); break; } else if (tetrisView.endMenu == MAIN_MENU_END_MENU){ break; } else if (tetrisView.endMenu == EXIT_END_MENU){ tetrisView.mainMenu = EXIT_MAIN_MENU; break; } } break; case RANKING_MAIN_MENU: TetrisView_ShowRanking(&tetrisView); break; case SETTING_MAIN_MENU: TetrisView_ShowSetting(&tetrisView); break; } } while (tetrisView.mainMenu != EXIT_MAIN_MENU); return 0; }
char showdelparwin() { int nWidth; int i; char ch; char szResult = 'c'; char szdrv[40],szStrCheck[65]; char *str[] = {"[V]iew Partition","Delete [M]ethod" ,"[D]elete ","[C]ancel"}; static point ptvpar, ptoption,ptdelpardel,ptdelparcancel; _itemnode *pitemHD; char *szMethod[] = {"00 overwrite","FF overwrite", "random data","NSA method", "Old NSA method","DoD STD method", "NATO method","Gutmann method"}; _setvisualpage(PAGE_DELPAR); _setactivepage(PAGE_DELPAR); ptvpar.row = 23; ptvpar.col = 5; drawbox(1, 1, g_SysInfo.nmaxrows, g_SysInfo.nmaxcols); _settextposition(2, 4); _outtext("Select the partition to be deleted"); _settextposition(4, 5); _outtext("PhysicalDisk: Drive Type Size(MB) Active Pri/Log"); _settextposition(12, 4); // 2004.08.03 huapage modify begin // _outtext("Selected partition"); _outtext("Partition information:"); // 2004.08.03 huapage modify end //Add&Init Disk select window g_pDelParDiskWin = new cwindow(PAGE_DELPAR, 5, 4, 11, 20); for(i = 0; i < g_nDiskNum; i++) // no A: B: { sprintf(szdrv, DRIVEFORMAT, i + 1); g_pDelParDiskWin->additemNotSort(szdrv,i); } g_pDelParDiskWin->enabledscroll(); if(!g_delparinfo.nseldisk) g_delparinfo.nseldisk = g_pDelParDiskWin->m_pitemactive->btItem+DISKBASE; SetDelParDiskSel(g_delparinfo.nseldisk-DISKBASE); //Add&Init Partition select window g_pDelParPartWin = new cwindow(PAGE_DELPAR, 5, 22, 11, 78); writedriveletter(g_pDelParDiskWin, g_pDelParPartWin); //Add show selected partition information window g_pDelParSelWin = new cwindow(PAGE_DELPAR, 13, 4, 18, 78); //show delete method sprintf(szdrv,"Delete partition with %s",szMethod[g_nMethod]); _settextposition(19, 4); _outtext(szdrv); // Add function box nWidth = strlen(str[0]); _settextposition(ptvpar.row, ptvpar.col); _outtext(str[0]); drawbox(ptvpar.row - 1, ptvpar.col - 1, ptvpar.row + 1, ptvpar.col + nWidth); ptoption.row = ptvpar.row; ptoption.col = ptvpar.col + nWidth + 2; nWidth = strlen(str[1]); _settextposition(ptoption.row, ptoption.col); _outtext(str[1]); drawbox(ptoption.row - 1, ptoption.col - 1, ptoption.row + 1, ptoption.col + nWidth); nWidth = strlen(str[3]); ptdelparcancel.row = ptvpar.row; ptdelparcancel.col = g_SysInfo.nmaxcols - 2 - nWidth; _settextposition(ptdelparcancel.row, ptdelparcancel.col); _outtext(str[3]); drawbox(ptdelparcancel.row - 1, ptdelparcancel.col - 1, ptdelparcancel.row + 1, ptdelparcancel.col + nWidth); nWidth = strlen(str[2]); ptdelpardel.row = ptdelparcancel.row; ptdelpardel.col = ptdelparcancel.col - 2 -nWidth; _settextposition(ptdelpardel.row, ptdelpardel.col); _outtext(str[2]); drawbox(ptdelpardel.row - 1, ptdelpardel.col - 1, ptdelpardel.row + 1, ptdelpardel.col + nWidth); SetDelParSelDisk(); showtarparinfo(); winproc(g_pDelParPartWin, WM_INACTIVE); switch(g_delparinfo.nselect) { case 0: winproc(g_pDelParDiskWin, WM_ACTIVE); break; case 1: winproc(g_pDelParPartWin, WM_ACTIVE); break; case 2: selectstr(str[0], ptvpar.row, ptvpar.col, SELCOLOR); break; case 3: selectstr(str[1], ptoption.row, ptoption.col, SELCOLOR); break; case 4: selectstr(str[2], ptdelpardel.row, ptdelpardel.col, SELCOLOR); break; case 5: selectstr(str[3], ptdelparcancel.row, ptdelparcancel.col, SELCOLOR); break; } while(1) { ch = _getch(); switch(ch) { case 'm': case 'M': _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'm'; case 'v': case 'V': // if(g_delparinfo.nselpar == -1) if( SEL_PAR_INIT_VALUE == g_delparinfo.nselpar ) { ErrorMessageBox(NO_SELPAR); break; } _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'v'; case 'd': case 'D': // 2004.08.03 huapage modify begin // if(g_delparinfo.nselpar == -1) if( SEL_PAR_INIT_VALUE == g_delparinfo.nselpar) // 2004.08.03 huapage modify end { ErrorMessageBox(NO_SELPAR); break; } _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'd'; case 'C': case 'c': case ESC : _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'c'; case SPACE : if( 1 == g_delparinfo.nselect) // if the tab stop is in the proper window { pitemHD = g_pDelParPartWin->m_pitemhead; while(pitemHD!=NULL) { if(pitemHD->szitemtext[SELPOINT] == SELFLAG)//no selected { pitemHD->szitemtext[SELPOINT] = ' '; } pitemHD = pitemHD->pnext; } i=1; while(i<6) { g_pDelParPartWin->gettext(szStrCheck,i); szStrCheck[0]=0x20; if(szStrCheck[2]=='X') { writestr(PAGE_DELPAR, 5 + i, 23 + SELPOINT, " "); } i++; } if( g_delparinfo.nselpar != ( g_pDelParPartWin->m_pitemactive->btItem -1) ) { g_pDelParPartWin->m_pitemactive->szitemtext[SELPOINT] = SELFLAG; writestr(PAGE_DELPAR, 5 + g_pDelParPartWin->m_nactiverow, 23 + SELPOINT, SELFLAG_STRING); // 2004.08.02 huapage added begin // now we add select all, so nselpar should minus one g_delparinfo.nselpar = g_pDelParPartWin->m_pitemactive->btItem - 1; // 2004.08.02 huapage added end } else //already selected { // 2004.08.03 huapage comment begin // g_delparinfo.nselpar =-1; // 2004.08.03 huapage comment end g_delparinfo.nselpar = SEL_PAR_INIT_VALUE; } showtarparinfo(); } else { // do nothing if the focus is not // in the proper window and // user press space } break; case 0: switch(ch = _getch()) { case SHIFT_TAB: switch(g_delparinfo.nselect) { case 0: g_delparinfo.nselect = 5; selectstr(str[3], ptdelparcancel.row, ptdelparcancel.col, SELCOLOR); winproc(g_pDelParDiskWin, WM_INACTIVE); break; case 1: g_delparinfo.nselect = 0; winproc(g_pDelParDiskWin, WM_ACTIVE); winproc(g_pDelParPartWin, WM_INACTIVE); break; case 2: g_delparinfo.nselect = 1; selectstr(str[0], ptvpar.row, ptvpar.col, TEXTCOLOR); winproc(g_pDelParPartWin, WM_ACTIVE); //showtarparinfo(); break; case 3: g_delparinfo.nselect = 2; selectstr(str[0], ptvpar.row, ptvpar.col, SELCOLOR); selectstr(str[1], ptoption.row, ptoption.col, TEXTCOLOR); break; case 4: g_delparinfo.nselect = 3; selectstr(str[1], ptoption.row, ptoption.col, SELCOLOR); selectstr(str[2], ptdelpardel.row, ptdelpardel.col, TEXTCOLOR); break; case 5: g_delparinfo.nselect = 4; selectstr(str[2], ptdelpardel.row, ptdelpardel.col, SELCOLOR); selectstr(str[3], ptdelparcancel.row, ptdelparcancel.col, TEXTCOLOR); break; } break; case PAGEDOWN: case PAGEUP: case CTRL_END: case CTRL_HOME: case UP: case DOWN: if(g_delparinfo.nselect == 0) { g_pDelParDiskWin->m_pitemactive->szitemtext[1] = ' '; writestr(PAGE_DELPAR, 5+g_pDelParDiskWin->m_nactiverow , 6, " "); winproc(g_pDelParDiskWin, WM_KEY, ch); g_pDelParDiskWin->m_pitemactive->szitemtext[1] = '*'; writestr(PAGE_DELPAR, 5+g_pDelParDiskWin->m_nactiverow , 6, "*"); g_delparinfo.nseldisk = g_pDelParDiskWin->m_pitemactive->btItem+DISKBASE; writedriveletter(g_pDelParDiskWin, g_pDelParPartWin); // 2004.08.03 huapage modify begin // g_delparinfo.nselpar = -1; g_delparinfo.nselpar = SEL_PAR_INIT_VALUE; // 2004.08.03 huapage modify end showtarparinfo(); } if(g_delparinfo.nselect == 1) { winproc(g_pDelParPartWin, WM_KEY, ch); //showtarparinfo(); } break; } break; case TAB: switch(g_delparinfo.nselect) { case 0: g_delparinfo.nselect = 1; winproc(g_pDelParDiskWin, WM_INACTIVE); winproc(g_pDelParPartWin, WM_ACTIVE); //showtarparinfo(); break; case 1: g_delparinfo.nselect = 2; selectstr(str[0], ptvpar.row, ptvpar.col, SELCOLOR); winproc(g_pDelParPartWin, WM_INACTIVE); break; case 2: g_delparinfo.nselect = 3; selectstr(str[0], ptvpar.row, ptvpar.col, TEXTCOLOR); selectstr(str[1], ptoption.row, ptoption.col, SELCOLOR); break; case 3: g_delparinfo.nselect = 4; selectstr(str[1], ptoption.row, ptoption.col, TEXTCOLOR); selectstr(str[2], ptdelpardel.row, ptdelpardel.col, SELCOLOR); break; case 4: g_delparinfo.nselect = 5; selectstr(str[2], ptdelpardel.row, ptdelpardel.col, TEXTCOLOR); selectstr(str[3], ptdelparcancel.row, ptdelparcancel.col, SELCOLOR); break; case 5: g_delparinfo.nselect = 0; selectstr(str[3], ptdelparcancel.row, ptdelparcancel.col, TEXTCOLOR); winproc(g_pDelParDiskWin, WM_ACTIVE); break; } break; case CR: switch(g_delparinfo.nselect) { case 2: // if(g_delparinfo.nselpar == -1) if(SEL_PAR_INIT_VALUE == g_delparinfo.nselpar) { ErrorMessageBox(NO_SELPAR); break; } _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'v'; case 3: _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'm'; case 4: // 2004.08.03 huapage modify begin // if(g_delparinfo.nselpar == -1) if(SEL_PAR_INIT_VALUE == g_delparinfo.nselpar) // 2004.08.03 huapage modify end { ErrorMessageBox(NO_SELPAR); break; } _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'd'; case 5: _clearscreen(_GCLEARSCREEN); DeleteDelParWin(); return 'c'; } default:break; } } }
void DisplayResults(HSTMT lpStmt, SQLSMALLINT cCols) { BINDING *pFirstBinding, *pThisBinding; SQLSMALLINT siDisplaySize; RETCODE RetCode; int iCount = 0; // Allocate memory for each column AllocateBindings(lpStmt,cCols,&pFirstBinding, &siDisplaySize); // Set the display mode and write the titles DisplayTitles(lpStmt,siDisplaySize+1, pFirstBinding); // Fetch and display the data do { // Fetch a row if (iCount++ >= gHeight - 2) { int nInputChar; while(1) { printf(" "); SetConsole(siDisplaySize+2,TRUE); printf(" Press ENTER to continue, Q to quit (height:%d)", gHeight); SetConsole(siDisplaySize+2,FALSE); nInputChar = _getch(); printf("\n"); if ((nInputChar == 'Q') || (nInputChar == 'q')) { goto Exit; } else if ('\r' == nInputChar) { break; } // else loop back to display prompt again } iCount = 1; DisplayTitles(lpStmt,siDisplaySize+1, pFirstBinding); } TRYODBC(lpStmt,SQL_HANDLE_STMT, RetCode = SQLFetch(lpStmt)); if (RetCode == SQL_NO_DATA_FOUND) break; // Display the data. Ignore truncations for (pThisBinding = pFirstBinding; pThisBinding; pThisBinding = pThisBinding->sNext) { if (pThisBinding->indPtr != SQL_NULL_DATA) { _tprintf(pThisBinding->fChar ? TEXT(DISPLAY_FORMAT_C): TEXT(DISPLAY_FORMAT), PIPE, pThisBinding->siDisplaySize, pThisBinding->siDisplaySize, pThisBinding->szBuffer); } else { _tprintf(TEXT(DISPLAY_FORMAT_C), PIPE, pThisBinding->siDisplaySize, pThisBinding->siDisplaySize, "<NULL>"); } } _tprintf(TEXT(" %c\n"),PIPE); } while ( 1); SetConsole(siDisplaySize+2,TRUE); printf("%*.*s",siDisplaySize+2,siDisplaySize+2," "); SetConsole(siDisplaySize+2,FALSE); printf("\n"); Exit: // Clean up the allocated buffers while (pFirstBinding) { pThisBinding=pFirstBinding->sNext; free(pFirstBinding->szBuffer); free(pFirstBinding); pFirstBinding=pThisBinding; } }
void main() { int secim,boyut,en; printf("--------Geometrik Cisim Cizdirme Programi--------\n\n"); //programýn tekrarý için for (;;) { //bu döngü hatalý seçimde baþa sarmak için for (;;) { printf("Cizdirmek Istediginiz Cismi Seciniz\n\n"); printf("1.Ucgen\n"); printf("2.Kare\n"); printf("3.Dikdortgen\n"); printf("4.Eskenar Dortgen\n"); printf("5.Paralelkenar\n"); printf("0.Cikis\n\n"); printf("Seciminiz:"); scanf("%d", &secim); //bu durumlarda sonsuz döngünün dýþýna çýkýyor if (secim == 1 || secim == 2 || secim == 3 || secim == 4 || secim == 5 || secim == 0) break; else { system("cls"); // "\a" yý uyarý sesi olarak kullanabiliriz printf("Hatali Bir Secim Yaptiniz!!\a\n\n"); continue; } } switch (secim) { case 1: system("cls"); printf("Ucgenin Boyutu: "); scanf(" %d", &boyut); ucgenCiz(boyut); break; case 2: system("cls"); printf("Karenin Boyutu: "); scanf(" %d", &boyut); kareCiz(boyut); break; case 3: system("cls"); printf("Dikdortgenin Boyu: "); scanf(" %d", &boyut); printf("Dikdortgenin Eni: "); scanf(" %d", &en); dikdortgenCiz(boyut, en); break; case 4: system("cls"); //bu döngü eskenar dörtgen için çift sayý girilme durumunda baþa sarmak için for (;;) { printf("Eskenar Dortgenin Boyutu: "); scanf(" %d", &boyut); if (boyut % 2 == 1) break; else system("cls"); printf("Lutfen Tek Sayi Giriniz..\a\n"); } edortgenCiz(boyut); break; case 5: system("cls"); printf("Paralelkenarin Boyutu: "); scanf("%d", &boyut); paralelkenarCiz(boyut); break; case 0: break; } //programdan cýkýs if (secim == 0) break; _getch(); system("cls"); } }
bool CTarget::choose_multiple_targets(bool monster, std::vector<CActor*>& Friend, std::vector<CActor*>& Enemy) { prompt("Select any number of targets. Push A when done."); int ch, pos = 0; CTarget Cursor; do { if (monster && Enemy.size() == 0) monster = !monster; else if (!monster && Friend.size() == 0) monster = !monster; Cursor.clear(); if (monster) Cursor.insert(Enemy[pos]); else Cursor.insert(Friend[pos]); if (Party.battle) Party.battle->draw_monsters(Cursor, this); Party.draw(rightWindow, Cursor, this); switch (ch = _getch()) { case _KEY_UP: pos--; break; case _KEY_DOWN: pos++; break; case _KEY_LEFT: case _KEY_RIGHT: monster = !monster; break; case KEY_ACCEPT: if (count(*Cursor.begin())) erase(*Cursor.begin()); else insert(*Cursor.begin()); break; case 'a': ch = 'A'; break; case 'C': if (Party.battle) { Party.view_init_cards = !Party.view_init_cards; Party.battle->draw(); } break; } if (monster) { if (pos > (int)Enemy.size() - 1) pos = 0; else if (pos < 0) pos = Enemy.size() - 1; } if (!monster) { if (pos > (int)Friend.size() - 1) pos = 0; else if (pos < 0) pos = Friend.size() - 1; } } while (!(ch == _KEY_CANCEL || ch == 'A')); if (Party.battle) Party.battle->draw(); else Party.draw(rightWindow); if (empty() || ch == _KEY_CANCEL) return false; return true; }
inline void pressEnter(void){ #if defined(_WIN32) || defined(WIN32) || defined(__WIN32__) || defined(__TOS_WIN__) std::cout<<"Press any key to continue..."<<std::endl; _getch(); #endif }
int main(){ /* Initialize scene and its objects */ Racket r1 = Racket(); Racket r2 = Racket(); Racket * List [2] = { &r1,&r2 }; boolean difficulty = false; r2.isplayer = gameMenu(&difficulty); r2.difficulty = difficulty; Dot ball = Dot(); char screen[HEIGHT][WIDTH]; initializeRacket(screen, &r1, LEFT_SIDE); initializeRacket(screen, &r2, RIGHT_SIDE); seed(); //initializes dot randomly int dotRand = rand() % 3; switch (dotRand) { case 0: initializeDot(screen, &ball, DOWNLEFT); break; case 1: initializeDot(screen, &ball, UPLEFT); break; case 2: initializeDot(screen, &ball, LEFT); break; default: initializeDot(screen, &ball, UPLEFT); break; } while (true) // Main loop { initialize(screen); drawRacket(screen, &r1); drawRacket(screen, &r2); moveDot(screen, ball.direction, &ball, List); if (screen[ball.height][ball.width] == RACKET_BRUSH) { if (ball.width < (WIDTH/2)) { dotHitRacket(screen,&ball, &r1, List); } else { dotHitRacket(screen,&ball, &r2, List); } } if (_kbhit()) { /* _kbhit is used to know if user pressed a button (keyboard) */ char pressedKey = _getch(); if (pressedKey == 'w' || pressedKey == 'W'){ moveRacket(screen, &r1,UP); } if (pressedKey == 's' || pressedKey == 'S') { moveRacket(screen, &r1, DOWN); } //Check if the user choose pvp or pvc if (r2.isplayer) { //Choose multiplayer if (pressedKey == 'i' || pressedKey == 'I') { moveRacket(screen, &r2, UP); } if (pressedKey == 'k' || pressedKey == 'K') { moveRacket(screen, &r2, DOWN); } } } if (!r2.isplayer) { moveCPU(screen, &r2,ball.direction,ball.height); } for (int i = 0; i < 2; i++) { if (List[i]->score >= 10) { system("cls"); printf("Player %d Venceu!\n", i+1); _getch(); return 0; } } draw(screen); sleep(); } return 0; }
int main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_CHECK_CRT_DF | _CRTDBG_LEAK_CHECK_DF | _CRTDBG_CHECK_EVERY_16_DF); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); _CrtMemState s1, s2, s3; _CrtMemCheckpoint(&s1); ExePath(); //////////// most common way to use licensing module //// { time_t LicenseRemainingTime; time_t GracePeriodRemainingTime; int GraceStatusCode; int LicenseCheckRes = GetRemainingTime(&LicenseRemainingTime, &GracePeriodRemainingTime, &GraceStatusCode); if (LicenseCheckRes != 0 || (LicenseRemainingTime == 0 && GracePeriodRemainingTime == 0)) { printf("LicenseCheckRes %d", LicenseCheckRes); printf("LicenseRemainingTime %d", (int)LicenseRemainingTime); printf("GracePeriodRemainingTime %d", (int)GracePeriodRemainingTime); } char ActivationKeyBuffer[200]; int GetKeyRes = GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); if (GetKeyRes == 0) printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", ActivationKeyBuffer); else printf("License did not contain a valid activation key\n"); } //////////// most common way to use licensing module //// ///////////////////////////////////////// get the key using class //////////////////////////////////// //create a license License *TestLicense = new License; //TestLicense->SaveToFile("t.t", "LicenseSeed.dat"); if (TestLicense == NULL) { printf("Unexpected error: feature list object is NULL\n"); return 1; } //for testing, load up the saved license and check if we can extract feature keys printf("Load license into temp buffer\n"); int er = TestLicense->LoadFromFile("../License.dat"); if (er != 0) { printf("Error %d while loading license. Please solve it to continue\n",er); delete TestLicense; _getch(); return 1; } printf("Seach for activation key inside license\n"); //find the key we need to activate a feature char ActivationKeyBuffer[200]; int GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", ActivationKeyBuffer); else printf("License did not contain a valid activation key\n"); //cleanup delete TestLicense; ///////////////////////////////////////// get the key using class //////////////////////////////////// ///////////////////////////////////////// get the key in an async way //////////////////////////////////// /* GetActivationKeyAsync(ALMA, ALMA_KPI, &HandleAsyncKeyAssignCallback); while (ReceivedCallback==0) Sleep(10); printf("For project ALMA and Feature KPI we obtained activation key '%s'\n", GlobalKeyStoreTestCallback); printf("\n\nAll done. Push a key to exit."); _getch();*/ ///////////////////////////////////////// get the key in an async way //////////////////////////////////// ///////////////////////////////////////// simulate HW failure. Test Grace period //////////////////////////////////// // !! in previous tests we made a successfull query for an activation key. // Grace period should be initialized at this point and even if fingerprint is no longer valid, it should trigger grace period and allow us to gte the key TestLicense = new License; er = TestLicense->LoadFromFile("../License.dat", "../License.dat"); // !! we are loading a bad file as fingerprint !! if (er == 0) { // int GracePeriodTriggered; // int erGraceCall = IsLicenseInGracePeriod(&GracePeriodTriggered); char ActivationKeyBuffer[200]; int GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("Tested bad hardware configuration license check. Got key '%s'\n", ActivationKeyBuffer); } else printf("!!Load error\n"); delete TestLicense; TestLicense = NULL; ///////////////////////////////////////// simulate HW failure. Test Grace period //////////////////////////////////// ///////////////////////////////////////// simulate license expire. Test Grace period //////////////////////////////////// TestLicense = new License; er = TestLicense->LoadFromFile("../License.dat"); //set license expiration to a very short interval TestLicense->SetDuration(time(NULL), 1, 5 * 60); //wait for the license to expire Sleep(1000); //check if we can query an activation key. It should succeed as we are in grace period time_t GracePeriodTriggered; char IsGraceTriggered; GetKeyRes = TestLicense->IsGracePeriodTriggered(&GracePeriodTriggered, &IsGraceTriggered); GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == 0) printf("Got key '%s'. Grace period is triggered %d\n", ActivationKeyBuffer, GracePeriodTriggered); //make the license be valid again TestLicense->SetDuration(time(NULL), 10000, 5 * 60); //query an activation key to force grace period to get disabled GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //make license expire more than max grace period TestLicense->SetDuration(time(NULL) - MAX_GRACE_PERIOD_SECONDS, 1, 1); //wait for the license to expire Sleep(1000); //query an activation key. It should fail as grace period ended GetKeyRes = TestLicense->IsGracePeriodTriggered(&GracePeriodTriggered, &IsGraceTriggered); if (GetKeyRes != 0) printf("Error obtaining grace data %d\n", GetKeyRes); GetKeyRes = TestLicense->GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); //this is for debugging only, you should not need to check for return value inside siemens projects. Hacker might be able to intercept the event and track the variable used for the activation key if (GetKeyRes == WARNING_NO_LICENSE_FOUND) printf("Could not obtain license. Expected behavior as grace period expired. Status %d\n", GracePeriodTriggered); delete TestLicense; TestLicense = NULL; ///////////////////////////////////////// simulate license expire. Test Grace period //////////////////////////////////// ///////////////////////////////////////// simulate bad license file content and check error proofness //////////////////////////////////// #ifdef _DEBUG EnableErrorTests(); for (int i = 0; i < 201; i++) // the 500 is a fictional number, should know the sizeo of the license file { GetKeyRes = GetActivationKey(ALMA, ALMA_KPI, ActivationKeyBuffer, sizeof(ActivationKeyBuffer)); printf("Corrupting byte %d from license file. Got result '%s'\n", i, ActivationKeyBuffer); } #endif ///////////////////////////////////////// simulate bad license file content and check error proofness //////////////////////////////////// printf("\n\nAll done. Push a key to continue.\n"); _getch(); _CrtMemCheckpoint(&s2); if (_CrtMemDifference(&s3, &s1, &s2) && (s3.lCounts[0]>0 || s3.lCounts[1] > 0 || s3.lCounts[3] > 0 || s3.lCounts[3] > 0)) //ignore CRT block allocs, can't do much about them. Some come from printf... { _CrtMemDumpStatistics(&s3); printf("!!Memory issues detected. Investigate !\n"); _getch(); } _CrtCheckMemory(); _CrtDumpMemoryLeaks(); return 0; }
char System::GetChar() { return _getch(); }
int main(int argc, char **argv) { char *shmname = NULL; void *shmptr = NULL; int i, scan_to; gint shmsize; wg_int rlock = 0; wg_int wlock = 0; /* look for commands in argv[1] or argv[2] */ if(argc < 3) scan_to = argc; else scan_to = 3; shmsize = 0; /* 0 size causes default size to be used */ /* 1st loop through, shmname is NULL for default. If * the first argument is not a recognizable command, it * is assumed to be the shmname and the next argument * is checked against known commands. */ for(i=1; i<scan_to; i++) { if (!strcmp(argv[i],"help") || !strcmp(argv[i],"-h")) { usage(argv[0]); exit(0); } if (!strcmp(argv[i],"version") || !strcmp(argv[i],"-v")) { wg_print_code_version(); exit(0); } if (!strcmp(argv[i],"free")) { /* free shared memory */ wg_delete_database(shmname); exit(0); } if(argc>(i+1) && !strcmp(argv[i],"import")){ wg_int err, minsize, maxsize; int flags = 0; if(argv[i+1][0] == '-') { flags = parse_flag(argv[++i]); if(argc<=(i+1)) { /* Filename argument missing */ usage(argv[0]); exit(1); } } err = wg_check_dump(NULL, argv[i+1], &minsize, &maxsize); if(err) { fprintf(stderr, "Import failed.\n"); break; } shmptr=wg_attach_memsegment(shmname, minsize, maxsize, 1, (flags & FLAGS_LOGGING)); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } /* Locking is handled internally by the dbdump.c functions */ err = wg_import_dump(shmptr,argv[i+1]); if(!err) printf("Database imported.\n"); else if(err<-1) fprintf(stderr, "Fatal error in wg_import_dump, db may have"\ " become corrupt\n"); else fprintf(stderr, "Import failed.\n"); break; } else if(argc>(i+1) && !strcmp(argv[i],"export")){ wg_int err; int flags = 0; if(argv[i+1][0] == '-') { flags = parse_flag(argv[++i]); if(argc<=(i+1)) { /* Filename argument missing */ usage(argv[0]); exit(1); } } shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } /* Locking is handled internally by the dbdump.c functions */ if(flags & FLAGS_FORCE) err = wg_dump_internal(shmptr,argv[i+1], 0); else err = wg_dump(shmptr,argv[i+1]); if(err<-1) fprintf(stderr, "Fatal error in wg_dump, db may have"\ " become corrupt\n"); else if(err) fprintf(stderr, "Export failed.\n"); break; } #ifdef USE_DBLOG else if(argc>(i+1) && !strcmp(argv[i],"replay")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); err = wg_replay_log(shmptr,argv[i+1]); WULOCK(shmptr, wlock); if(!err) printf("Log suggessfully imported from file.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing, database may have "\ "become corrupt\n"); else fprintf(stderr, "Failed to import log (database unmodified).\n"); break; } #endif else if(argc>(i+1) && !strcmp(argv[i],"exportcsv")){ shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } RLOCK(shmptr, wlock); wg_export_db_csv(shmptr,argv[i+1]); RULOCK(shmptr, wlock); break; } else if(argc>(i+1) && !strcmp(argv[i],"importcsv")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); err = wg_import_db_csv(shmptr,argv[i+1]); WULOCK(shmptr, wlock); if(!err) printf("Data imported from file.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing, data may be partially"\ " imported\n"); else fprintf(stderr, "Import failed.\n"); break; } #ifdef USE_REASONER else if(argc>(i+1) && !strcmp(argv[i],"importprolog")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } err = wg_import_prolog_file(shmptr,argv[i+1]); if(!err) printf("Data imported from prolog file.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing, data may be partially"\ " imported\n"); else fprintf(stderr, "Import failed.\n"); break; } else if(argc>(i+1) && !strcmp(argv[i],"importotter")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } err = wg_import_otter_file(shmptr,argv[i+1]); if(!err) printf("Data imported from otter file.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing otter file, data may be partially"\ " imported\n"); else fprintf(stderr, "Import failed.\n"); break; } else if(argc>i && !strcmp(argv[i],"runreasoner")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } //printf("about to call wg_run_reasoner\n"); err = wg_run_reasoner(shmptr,argc,argv); //if(!err); //printf("wg_run_reasoner finished ok.\n"); //else //fprintf(stderr, "wg_run_reasoner finished with an error %d.\n",err); //break; break; } else if(argc>i && !strcmp(argv[i],"testreasoner")){ wg_int err; //printf("about to call wg_test_reasoner\n"); err = wg_test_reasoner(argc,argv); //if(!err); //printf("wg_test_reasoner finished ok.\n"); //else //fprintf(stderr, "wg_test_reasoner finished with an error %d.\n",err); //break; break; } #endif #ifdef HAVE_RAPTOR else if(argc>(i+2) && !strcmp(argv[i],"exportrdf")){ wg_int err; int pref_fields = atol(argv[i+1]); shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } printf("Exporting with %d prefix fields.\n", pref_fields); RLOCK(shmptr, wlock); err = wg_export_raptor_rdfxml_file(shmptr, pref_fields, argv[i+2]); RULOCK(shmptr, wlock); if(err) fprintf(stderr, "Export failed.\n"); break; } else if(argc>(i+3) && !strcmp(argv[i],"importrdf")){ wg_int err; int pref_fields = atol(argv[i+1]); int suff_fields = atol(argv[i+2]); shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } printf("Importing with %d prefix fields, %d suffix fields.\n,", pref_fields, suff_fields); WLOCK(shmptr, wlock); err = wg_import_raptor_file(shmptr, pref_fields, suff_fields, wg_rdfparse_default_callback, argv[i+3]); WULOCK(shmptr, wlock); if(!err) printf("Data imported from file.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing, data may be partially"\ " imported\n"); else fprintf(stderr, "Import failed.\n"); break; } #endif else if(!strcmp(argv[i],"test")) { /* This test function does it's own memory allocation. */ wg_run_tests(WG_TEST_QUICK, 2); break; } else if(!strcmp(argv[i],"fulltest")) { wg_run_tests(WG_TEST_FULL, 2); break; } else if(!strcmp(argv[i], "header")) { shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } RLOCK(shmptr, wlock); wg_show_db_memsegment_header(shmptr); RULOCK(shmptr, wlock); break; } #ifdef _WIN32 else if(!strcmp(argv[i],"server")) { int flags = 0; if(argc>(i+1) && argv[i+1][0] == '-') { flags = parse_flag(argv[++i]); } if(argc>(i+1)) { shmsize = parse_shmsize(argv[i+1]); if(!shmsize) fprintf(stderr, "Failed to parse memory size, using default.\n"); } shmptr=wg_attach_memsegment(shmname, shmsize, shmsize, 1, (flags & FLAGS_LOGGING)); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } printf("Press Ctrl-C to end and release the memory.\n"); while(_getch() != 3); break; } #else else if(!strcmp(argv[i],"create")) { int flags = 0; if(argc>(i+1) && argv[i+1][0] == '-') { flags = parse_flag(argv[++i]); } if(argc>(i+1)) { shmsize = parse_shmsize(argv[i+1]); if(!shmsize) fprintf(stderr, "Failed to parse memory size, using default.\n"); } shmptr=wg_attach_memsegment(shmname, shmsize, shmsize, 1, (flags & FLAGS_LOGGING)); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } break; } #endif else if(argc>(i+1) && !strcmp(argv[i], "fill")) { int rows = atol(argv[i+1]); if(!rows) { fprintf(stderr, "Invalid number of rows.\n"); exit(1); } shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); if(argc > (i+2) && !strcmp(argv[i+2], "mix")) wg_genintdata_mix(shmptr, rows, TESTREC_SIZE); else if(argc > (i+2) && !strcmp(argv[i+2], "desc")) wg_genintdata_desc(shmptr, rows, TESTREC_SIZE); else wg_genintdata_asc(shmptr, rows, TESTREC_SIZE); WULOCK(shmptr, wlock); printf("Data inserted\n"); break; } else if(argc>(i+1) && !strcmp(argv[i],"select")) { int rows = atol(argv[i+1]); int from = 0; if(!rows) { fprintf(stderr, "Invalid number of rows.\n"); exit(1); } if(argc > (i+2)) from = atol(argv[i+2]); shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } RLOCK(shmptr, wlock); selectdata(shmptr, rows, from); RULOCK(shmptr, wlock); break; } else if(argc>(i+1) && !strcmp(argv[i],"add")) { int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); err = add_row(shmptr, argv+i+1, argc-i-1); WULOCK(shmptr, wlock); if(!err) printf("Row added.\n"); break; } else if(argc>(i+2) && !strcmp(argv[i],"del")) { shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } /* Delete works like query(), except deletes the matching rows */ del(shmptr, argv+i+1, argc-i-1); break; break; } else if(argc>(i+3) && !strcmp(argv[i],"query")) { shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } /* Query handles it's own locking */ query(shmptr, argv+i+1, argc-i-1); break; } else if(argc>i && !strcmp(argv[i],"addjson")){ wg_int err; shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); /* the filename parameter is optional */ err = wg_parse_json_file(shmptr, (argc>(i+1) ? argv[i+1] : NULL)); WULOCK(shmptr, wlock); if(!err) printf("JSON document imported.\n"); else if(err<-1) fprintf(stderr, "Fatal error when importing, data may be partially"\ " imported\n"); else fprintf(stderr, "Import failed.\n"); break; } else if(argc>(i+1) && !strcmp(argv[i],"findjson")) { shmptr=wg_attach_database(shmname, shmsize); if(!shmptr) { fprintf(stderr, "Failed to attach to database.\n"); exit(1); } WLOCK(shmptr, wlock); findjson(shmptr, argv[i+1]); WULOCK(shmptr, wlock); break; } shmname = argv[1]; /* no match, assume shmname was given */ } if(i==scan_to) { /* loop completed normally ==> no commands found */ usage(argv[0]); } if(shmptr) { RULOCK(shmptr, rlock); WULOCK(shmptr, wlock); wg_detach_database(shmptr); } exit(0); }
int main(int argc, char *argv[]) { #ifdef _WIN32 DWORD numRead; DWORD numToWrite; if (argc != 2) { HANDLE namedPipe = CreateNamedPipe(TEXT("\\\\.\\pipe\\Pipe"), PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, NULL); if (namedPipe == INVALID_HANDLE_VALUE) { cout << "Can't create pipe. Error. Press any key to exit " << GetLastError(); _getch(); exit(0); } HANDLE serverSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("serverSemaphore")); HANDLE clientSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("clientSemaphore")); MyProcess *clientProcess = new MyProcess(argv[0]); ConnectNamedPipe(namedPipe, NULL); WaitForSingleObject(serverSemaphore, INFINITE); char *buffer = NULL; buffer = (char *)malloc(sizeof(char) * 1024); printf("Server process\n"); if (!WriteFile(namedPipe, "Ready", 1024, &numToWrite, NULL)) return 0; while (1) { ReleaseSemaphore(clientSemaphore, 1, NULL); WaitForSingleObject(serverSemaphore, INFINITE); if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL)) printf("Client message: %s", buffer); if (!strcmp(buffer, "exit")) { CloseHandle(namedPipe); CloseHandle(serverSemaphore); free(buffer); return 0; } printf("\nInput message to client: "); fflush(stdin); gets_s(buffer, 1024); if (!WriteFile(namedPipe, buffer, 1024, &numToWrite, NULL)) break; ReleaseSemaphore(clientSemaphore, 1, NULL); if (!strcmp(buffer, "exit")) { CloseHandle(namedPipe); CloseHandle(serverSemaphore); free(buffer); return 0; } } return 0; } else { HANDLE serverSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("serverSemaphore")); HANDLE clientSemaphore = OpenSemaphore(EVENT_ALL_ACCESS, FALSE, TEXT("clientSemaphore")); HANDLE namedPipe = CreateFile(TEXT("\\\\.\\pipe\\Pipe"), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (namedPipe == INVALID_HANDLE_VALUE) { printf("Can't create pipe. Error. Press any key to exit", GetLastError()); _getch(); exit(0); } ReleaseSemaphore(serverSemaphore, 1, NULL); char *buffer = NULL; buffer = (char *)malloc(sizeof(char) * 1024); printf("Client process\n"); while (1) { WaitForSingleObject(clientSemaphore, INFINITE); if (ReadFile(namedPipe, buffer, 1024, &numRead, NULL)) { if (!strcmp(buffer, "exit")) { CloseHandle(clientSemaphore); free(buffer); return 0; } printf("Server message: %s", buffer); char input[1024] = { '\0' }; cout << "\nInput message to server: "; fflush(stdin); gets_s(input, 1024); if (!WriteFile(namedPipe, input, 1024, &numToWrite, NULL)) break; if (!strcmp(input, "exit")) { ReleaseSemaphore(serverSemaphore, 1, NULL); CloseHandle(clientSemaphore); free(buffer); return 0; } } ReleaseSemaphore(serverSemaphore, 1, NULL); } return 0; } #elif __linux__ pid_t pid; key_t key = ftok("/home/", 0); struct sembuf serverSemaphore; struct sembuf clientSemaphore; int semaphoreId; int sharedMemoryId; char *segmentPtr; if (argc != 2) { switch (pid = fork()) { case -1: printf("Can't fork process %d\n", pid); break; case 0: execlp("gnome-terminal", "gnome-terminal", "-x", argv[0], "1", NULL); default: if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1) { if ((sharedMemoryId = shmget(key, 1024, 0)) == -1) { printf("error\n"); exit(1); } } if ((segmentPtr = (char*)shmat(sharedMemoryId, NULL, 0)) == (char*)(-1)) { printf("Can't attach shared memory\n"); exit(1); } semaphoreId = semget(key, 1, 0666 | IPC_CREAT); if (semaphoreId < 0) { printf("Can't get semaphore\n"); exit(EXIT_FAILURE); } if (semctl(semaphoreId, 0, SETVAL, (int)0) < 0) { printf("Can't initialize semaphore\n"); exit(EXIT_FAILURE); } serverSemaphore.sem_num = 0; serverSemaphore.sem_op = 0; serverSemaphore.sem_flg = 0; printf("Server process: "); while (1) { char *message = NULL; message = (char*)malloc(1024 * sizeof(char)); semop(semaphoreId, &serverSemaphore, 1); printf("\nInput message to client: "); fflush(stdin); cin >> message; strcpy(segmentPtr, message); serverSemaphore.sem_op = 3; semop(semaphoreId, &serverSemaphore, 1); serverSemaphore.sem_op = 0; semop(semaphoreId, &serverSemaphore, 1); if (!strcmp("exit", message)) return 0; strcpy(message, segmentPtr); printf("Client message: %s\n", message); } return 0; } } else { if ((sharedMemoryId = shmget(key, 1024, IPC_CREAT | IPC_EXCL | 0660)) == -1)
void GameManager::Networking() { Network network; PacketType type; ErrorType error; srand((unsigned int)time(NULL)); /* ** 네트워크 초기화 */ try { Network::Initialize(); } catch (Network::Exception) { puts("초기화 도중 문제가 발생했습니다."); return; } /* ** 서버에 연결 서버의 IP와 포트는 당일날 공지된다. */ const char* ip = "10.73.42.117"; const unsigned short port = 9001; try { network.Connect(ip, port); } catch (Network::Exception ex) { switch (ex) { case Network::NETWORK_ERROR: puts("서버와 연결에 실패했습니다."); break; case Network::PARAMETER_ERROR: puts("함수의 인수가 잘못되었습니다."); break; } return; } puts("접속 성공!"); try // 예외 처리를 위해 try문으로 모두 감싼다. { /* ** 이름&학번 전송 최대 길이는 MAX_NAME_LEN-1 == 15글자. 성공시 ET_OK가 리턴된다. 이미 있는 이름을 쓰면 ET_DUPLICATED_NAME이 온다. */ const wchar_t name[MAX_NAME_LEN] = L"버틸수없다"; const int studentID = 141044; error = network.SubmitName(name, studentID); if (error == ET_DUPLICATED_NAME) { puts("이미 존재하는 이름입니다."); return; } /* ** 게임 시작 대기 게임이 시작되면 상대방의 정보가 들어온다. Network::GameStartData 구조체로 상대방 정보를 가져온다. */ Network::GameStartData gameStartData; puts("게임 시작 대기중"); network.WaitForStart(&gameStartData); wprintf_s(L"매칭되었습니다. 상대방 이름: %s, 학번: %d\n", gameStartData.oppositionName, gameStartData.oppositionStudentID); /* ** 게임 시작 맵 제출부터 게임 종료까지 n회 반복한다. 하나의 게임이 끝나고 다음 게임을 시작해야 한다면 PKT_SC_NEXT_GAME 패킷이 모든 게임이 끝나면 PKT_SC_ALL_OVER 패킷이 들어온다. */ bool allOver = false; while (!allOver) { SetGame(); /* ** 맵 제출 자신이 배치한 맵 데이터를 서버로 전송한다. 맵 데이터를 만드는 방법에는 두 가지가 있다. 하나는 직접 MAP_WIDHT * MAP_HEIGHT 크기의 맵을 만드는 것이고, 하나는 ShipData 구조체를 이용해서 만드는 것이다. */ char mapData[MAP_SIZE]; //TransferMyMapData(mapData, m_Attacker); memset(mapData, MI_EMPTY, sizeof(mapData)); int shiptype = 1; for (auto ship : *m_Attacker->GetShipList()) { for (int i = 0; i < ship->GetShipType(); ++i){ auto position = ship->GetShipPos(i); mapData[position.y*MAP_WIDTH + position.x] = shiptype; } shiptype++; //하드코딩 } while (true) { error = network.SubmitMap(mapData); if (error == ET_INVALID_MAP) puts("유효하지 않은 맵 데이터입니다."); else break; } /* ** 게임 루프 내 차례라면 공격 위치를 전송한다. 차례가 끝나면 공격자와 공격 위치, 공격 결과를 받는다. 한 게임이 끝나면 PKT_SC_GAME_OVER 패킷이 들어온다. */ bool gameOver = false; while (!gameOver) { error = network.GetPacketType(&type); switch (type) { // 에러가 발생하는 경우(상대방의 접속 종료) case PKT_SC_ERROR: if (error == ET_OPPOSITION_DISCONNECTED) puts("상대방의 접속이 끊어졌습니다."); else puts("알 수 없는 에러입니다."); return; // 내 차례 case PKT_SC_MY_TURN: { /* ** 공격 위치 전송 x, y는 0~7 사이의 정수이다. */ while (true) { // Coord pos = MakeAttackPos(); Position attackpos = m_Attacker->RandomAttack(); error = network.SubmitAttack({ attackpos.x, attackpos.y }); if (error == ET_INVALID_ATTACK) puts("유효하지 않은 공격 위치입니다."); else break; } break; } // 공격 결과 case PKT_SC_ATTACK_RESULT: { Network::AttackResultData attackResult = network.GetAttackResult(); Position attackpos; attackpos.x = attackResult.pos.mX; attackpos.y = attackResult.pos.mY; HitResult hitResult = TranslateHitResult(attackResult.attackResult); if (attackResult.isMine){ // puts("공격 결과:"); m_Attacker->ReceiveHitResult(attackpos, hitResult); } else { puts("피격 결과:"); //HandleOpositionAttackResult(attackResult.attackResult, attackResult.pos.mX, attackResult.pos.mY); m_Zido_Attacker->ZidoMarkByGM(attackpos); } printf_s("X: %d, Y: %d, RESULT: %s\n", attackResult.pos.mX, attackResult.pos.mY, ATTACK_RESULT_STR[attackResult.attackResult]); break; } // 게임 종료 case PKT_SC_GAME_OVER: { Network::GameResultData gameResult = network.GetGameResult(); if (gameResult.isWinner) puts("승리!!!"); else puts("패배..."); printf_s("턴 수: %d\n", gameResult.turns); gameOver = true; break; } default: throw Network::UNEXPECTED_PACKET; break; } } /* ** 종료후 처리 */ network.GetPacketType(&type); if (type == PKT_SC_NEXT_GAME) { puts("다음 게임을 준비해주세요."); } else if (type == PKT_SC_ALL_OVER) { Network::FinalResultData finalResult = network.GetFinalResult(); puts("모두 종료"); printf_s("승리 횟수: %d, 평균 턴 수: %.1f", finalResult.winCount, finalResult.avgTurns); allOver = true; } else throw Network::UNEXPECTED_PACKET; } } catch (Network::Exception ex) { switch (ex) { case Network::NETWORK_ERROR: puts("네트워크에 문제가 발생했습니다."); break; case Network::SERVER_CLOSED: puts("서버와의 연결이 끊어졌습니다."); break; case Network::PARAMETER_ERROR: puts("함수의 인수가 잘못되었습니다."); break; case Network::UNEXPECTED_PACKET: puts("서버에서 잘못된 정보가 전송되었습니다."); break; default: break; } } /* ** 연결 종료 참고로 소멸시에도 자동으로 Disconnect를 호출한다. */ network.Disconnect(); _getch(); }
void movement::keyControl() { cout << "Tastatureingaben: " << endl; cout << "w: Vorwaerts; a: Linksdrehung; s: Rueckwaerts; d: Rechtdrehung" << endl; cout << "l: starten des LookaroundModus (Abbruch mit beliebiger Taste)" << endl; cout << "Aenderungen der Geschwindigkeiten: " << endl; cout << "1 bzw 2 zum Erhöhen bzw Senken der Fahrgeschwindigkeit" << endl; cout << "3 bzw 4 zum Erhöhen bzw Senken der Drehgeschwindigkeit" << endl; cout << "o beendet das Programm" << endl; cout << "Start mit Vel = "<<Vel_Value<< " RVEL = " << Rot_Value << endl; while(p3dxptr->isConnected()) { //bool kbh = kbhit(); if(kbhit()) { key = _getch(); if(key == '3') { Rot_Value += 5; //cout << "setze Rot_Value+5" << endl; cout << "Erhoehe Rot_Value: "<< Rot_Value << endl; //if(yesno == 'y' } if(key == '4') { Rot_Value -= 5; //cout << "setze Rot_Value -5"<<endl; cout << "Senke Rot_Value: "<< Rot_Value << endl; } if(key == '1') { Vel_Value += 5; //cout << "Setze Vel_Value +5" << endl; cout << "Erhoehe Vel_Value: "<< Vel_Value << endl; } if(key == '2') { Vel_Value -= 5; //cout << "setze Vel_Value -5" << endl; cout << "Senke Vel_Value: "<< Vel_Value << endl; } if(key == 'w') { p3dxptr->comInt(ArCommands::RVEL, 0); //cout << "Fahre vorwaerts" << endl; if(Vel_Value < 0) { //cout << "Vel_Value negativ rechne *-1" << endl; p3dxptr->comInt(ArCommands::VEL, -Vel_Value); } else p3dxptr->comInt(ArCommands::VEL, Vel_Value); //cout << "fahre normal" << endl; } if(key == 's') { p3dxptr->comInt(ArCommands::RVEL, 0); //cout << "rueckwaerts" << endl; //ArUtil::sleep(200); //cout << "Vel Value > 0 rechne *-1" << endl; p3dxptr->comInt(ArCommands::VEL, -Vel_Value); } if(key == 'a') { p3dxptr->comInt(ArCommands::VEL, 0); //cout << "drehe nach links" << endl; p3dxptr->comInt(ArCommands::RVEL, Rot_Value); } if(key == 'd') { p3dxptr->comInt(ArCommands::VEL, 0); //cout << "drehe nach rechts" << endl; p3dxptr->comInt(ArCommands::RVEL, -Rot_Value); } if(key == ' ') { cout << "Emergency Stop" << endl; p3dxptr->comInt(ArCommands::VEL, 0); p3dxptr->comInt(ArCommands::RVEL, 0); } if(key == 'l') { cout << "Starte LookAround Modus" << endl; movement::lookAround(); } if(key == 'o') { p3dxptr->disconnect(); } /*if(movement::checkWall()) { cout << "Automatischer Stop Grund: Wand" << endl; p3dxptr->comInt(ArCommands::VEL, 0); p3dxptr->comInt(ArCommands::RVEL, 0); }*/ } } //cout << test << endl; }
/* ================ Sys_ConsoleInput ================ */ char *Sys_ConsoleInput (void) { #ifdef _CONSOLE static char text[256], *t; static int len = 0; int c; // read a line out if (!isdaemon) while (_kbhit()) { c = _getch(); if (c == 224) { if (_kbhit()) { // assume escape sequence (arrows etc), skip _getch(); continue; } // assume character } if (c < 32 && c != '\r' && c != 8) continue; putch (c); if (c == '\r') { text[len] = 0; putch ('\n'); len = 0; return text; } if (c == 8) { if (len) { putch (' '); putch (c); len--; text[len] = 0; } continue; } text[len] = c; len++; text[len] = 0; if (len == sizeof(text)) len = 0; } #endif // If you searching where input added under non console application, then you should check DialogFunc WM_COMMAND. return NULL; }
int main() { srand(time(NULL)); const int Number_of_Rects = 5; // initialization Rect userRect(7, 5, 10, 9); // Controlled Square Size Rect * rect = new Rect[Number_of_Rects]; // creates an array of 5 rectangles. // Rect * rect1 = new Rect; // (1, 6, 5, 15) // rect1->setRandomByPointer(rect1); int userInput; for(int i = 0; i < Number_of_Rects; i++) // sets 5 rectanges to a random position { setRandom(rect[i]); } do { // draw for(int i = 0; i < Number_of_Rects; i++) // draw 5 rectangles that are numbered from 0 - 4 { rect[i].draw('0'+i); } //rect1->draw('1'); moveCursor(0, 0); // re-print instructions printf("move with 'w', 'a', 's', and 'd'"); userRect.draw('#'); moveCursor(40, 0); printf("No Collision"); checkCollision(userRect, rect, Number_of_Rects); // collision detection. Prints "+" if player collides with other Rects /*for(int i = 0; i < Number_of_Rects; ++i) // old collision detector { if(userRect.isOverlapping( rect[i] ) ) { userRect.draw('+'); moveCursor(40, 0); printf("Collision"); } else { moveCursor(40, 0); printf("No Collision"); } }*/ // user input userInput = _getch(); // update Vec2 move; switch(userInput) // takes userInput to move controlled rectangle { case 'w': move = Vec2( 0,-1); break; case 'a': move = Vec2(-1, 0); break; case 's': move = Vec2( 0,+1); break; case 'd': move = Vec2(+1, 0); break; } userRect.draw(' '); // un-draw before moving userRect.translate(move); // Draws square at new location }while(userInput != 27); // escape key delete [] rect; return 0; }
int PitchDetector::DetectPitch() { FMOD::System *system = 0; FMOD::Sound *sound = 0; FMOD::Channel *channel = 0; FMOD_RESULT result; FMOD_CREATESOUNDEXINFO exinfo; int key, driver, recorddriver, numdrivers, count, bin; unsigned int version; /* Create a System object and initialize. */ result = FMOD::System_Create(&system); ERRCHECK(result); result = system->getVersion(&version); ERRCHECK(result); if (version < FMOD_VERSION) { printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION); return(-1); } /* System initialization */ printf("---------------------------------------------------------\n"); printf("Select OUTPUT type\n"); printf("---------------------------------------------------------\n"); printf("1 : DirectSound\n"); printf("2 : Windows Multimedia WaveOut\n"); printf("3 : ASIO\n"); printf("---------------------------------------------------------\n"); printf("Press a corresponding number or ESC to quit\n"); do { //key = _getch(); key = '1'; //TODO: this uses the default io device rather than using user input } while (key != 27 && key < '1' && key > '5'); switch (key) { case '1' : result = system->setOutput(FMOD_OUTPUTTYPE_DSOUND); break; case '2' : result = system->setOutput(FMOD_OUTPUTTYPE_WINMM); break; case '3' : result = system->setOutput(FMOD_OUTPUTTYPE_ASIO); break; default : return(0); } ERRCHECK(result); /* Enumerate playback devices */ result = system->getNumDrivers(&numdrivers); ERRCHECK(result); printf("---------------------------------------------------------\n"); printf("Choose a PLAYBACK driver\n"); printf("---------------------------------------------------------\n"); for (count=0; count < numdrivers; count++) { char name[256]; result = system->getDriverInfo(count, name, 256, 0); ERRCHECK(result); printf("%d : %s\n", count + 1, name); } printf("---------------------------------------------------------\n"); printf("Press a corresponding number or ESC to quit\n"); do { //key = _getch(); key = '1'; //TODO: io devices if (key == 27) { return(0); } driver = key - '1'; } while (driver < 0 || driver >= numdrivers); result = system->setDriver(driver); ERRCHECK(result); /* Enumerate record devices */ result = system->getRecordNumDrivers(&numdrivers); ERRCHECK(result); printf("---------------------------------------------------------\n"); printf("Choose a RECORD driver\n"); printf("---------------------------------------------------------\n"); for (count=0; count < numdrivers; count++) { char name[256]; result = system->getRecordDriverInfo(count, name, 256, 0); ERRCHECK(result); printf("%d : %s\n", count + 1, name); } printf("---------------------------------------------------------\n"); printf("Press a corresponding number or ESC to quit\n"); recorddriver = 0; do { //key = _getch(); key = '1'; //TODO: io devices if (key == 27) { return(0); } recorddriver = key - '1'; } while (recorddriver < 0 || recorddriver >= numdrivers); printf("\n"); result = system->setSoftwareFormat(OUTPUT_RATE, FMOD_SOUND_FORMAT_PCM16, 1, 0, FMOD_DSP_RESAMPLER_LINEAR); ERRCHECK(result); result = system->init(32, FMOD_INIT_NORMAL, 0); ERRCHECK(result); /* Create a sound to record to. */ memset(&exinfo, 0, sizeof(FMOD_CREATESOUNDEXINFO)); exinfo.cbsize = sizeof(FMOD_CREATESOUNDEXINFO); exinfo.numchannels = 1; exinfo.format = FMOD_SOUND_FORMAT_PCM16; exinfo.defaultfrequency = OUTPUT_RATE; exinfo.length = exinfo.defaultfrequency * sizeof(short) * exinfo.numchannels * 5; result = system->createSound(0, FMOD_2D | FMOD_SOFTWARE | FMOD_LOOP_NORMAL | FMOD_OPENUSER, &exinfo, &sound); ERRCHECK(result); /* Start the interface */ printf("=========================================================================\n"); printf("Pitch detection example. Copyright (c) Firelight Technologies 2004-2011.\n"); printf("=========================================================================\n"); printf("\n"); printf("Record something through the selected recording device and FMOD will\n"); printf("Determine the pitch. Sustain the tone for at least a second to get an\n"); printf("accurate reading.\n"); printf("Press 'Esc' to quit\n"); printf("\n"); result = system->recordStart(recorddriver, sound, true); ERRCHECK(result); Sleep(100); /* Give it some time to record something */ result = system->playSound(FMOD_CHANNEL_REUSE, sound, false, &channel); ERRCHECK(result); /* Dont hear what is being recorded otherwise it will feedback. Spectrum analysis is done before volume scaling in the DSP chain */ result = channel->setVolume(0); ERRCHECK(result); bin = 0; /* Main loop. */ do { static float spectrum[SPECTRUM_SIZE]; float dominantHz = 0; float max; int dominantNote = 0; float binSize = BIN_SIZE; bool hasUpdated = false; char windowTitle[sizeof("Pitch Detector: ---")] = "Pitch Detector: ---"; int noteIndex; double noteDeviation; if (_kbhit()) { key = _getch(); } result = channel->getSpectrum(spectrum, SPECTRUM_SIZE, 0, FMOD_DSP_FFT_WINDOW_TRIANGLE); ERRCHECK(result); max = 0; for (count = 0; count < SPECTRUM_SIZE; count++) { if (spectrum[count] > 0.01f && spectrum[count] > max) { max = spectrum[count]; bin = count; hasUpdated = true; } } dominantHz = (float)bin * BIN_SIZE; /* dominant frequency min */ dominantNote = 0; for (count = 0; count < 120; count++) { if (dominantHz >= noteFreq[count] && dominantHz < noteFreq[count + 1]) { /* which is it closer to. This note or the next note */ if (fabs(dominantHz - noteFreq[count]) < fabs(dominantHz - noteFreq[count+1])) { dominantNote = count; } else { dominantNote = count + 1; } break; } } printf("Detected rate : %7.1f -> %7.1f hz. Detected musical note. %-3s (%7.1f hz)\r", dominantHz, ((float)bin + 0.99f) * BIN_SIZE, note[dominantNote], noteFreq[dominantNote]); // Sets the window title to Pitch Detector: (NOTE)(#|)([0-9]) \| (KEY_MAPPING) string noteStr = note[dominantNote]; noteStr = noteStr[0]; string keyMapping = " | " + mappingsInterface->GetBoxText(noteStr); strncpy(windowTitle + sizeof("Pitch Detector: ") - 1, note[dominantNote], 3); if (!hasUpdated) { strncpy(windowTitle + sizeof("Pitch Detector: ") - 1, "---", 3); keyMapping = ""; } string windowTitleStr = windowTitle; emit UpdateTitleSignal(QString((windowTitleStr + keyMapping).c_str())); // Sets the feedback of what note is being played if (!hasUpdated) { noteIndex = -1; noteDeviation = 0; } else { noteIndex = NoteToIndex(dominantNote); noteDeviation = GetNoteDeviation(dominantHz, dominantNote); } emit UpdateNoteDisplaySignal(noteIndex, noteDeviation); system->update(); Sleep(10); } while (key != 27); printf("\n"); /* Shut down */ result = sound->release(); ERRCHECK(result); result = system->release(); ERRCHECK(result); return 0; }
int main(int argc, char** argv) { CString sConfig; CString sDataDir = ""; srand((unsigned int)time(NULL)); // Win32 doesn't support shell escape codes, so we do this. CUtils::SetStdoutIsTTY(false); CString sConsoleTitle = "ZNC " + CZNC::GetVersion(); SetConsoleTitle(sConsoleTitle.c_str()); // register Ctrl handler if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)ConsoleCtrlHandler, TRUE) == NULL) { CUtils::PrintMessage("Couldn't register console Ctrl handler function!"); } // this prevents open()/read() and friends from stripping \r // from files... simply adding _O_BINARY to the modes doesn't seem // to be enough for some reason... // if we don't do this, Template.cpp will break // because it uses string.size() for file pos // calculations. _set_fmode(_O_BINARY); #ifdef HAVE_LIBSSL CRYPTO_malloc_init(); #endif // make sure the stuff in ZNC.dll matches this exe's version... bad crashes otherwise. if(CZNC::GetCoreVersion() != MODVERSION) { CUtils::PrintError("The version number in ZNC.dll doesn't match. Aborting."); return 1; } // process command line arguments int iArg, iOptIndex = -1; bool bMakeConf = false; bool bMakePass = false; bool bAllowRoot = false; #ifdef HAVE_LIBSSL bool bMakePem = false; while ((iArg = getopt_long(argc, argv, "hvcspd:D", g_LongOpts, &iOptIndex)) != -1) { #else while ((iArg = getopt_long(argc, argv, "hvcsd:D", g_LongOpts, &iOptIndex)) != -1) { #endif /* HAVE_LIBSSL */ switch (iArg) { case 'h': GenerateHelp(argv[0]); return 0; case 'v': cout << CZNC::GetTag() << endl; return 0; case 'c': bMakeConf = true; break; case 's': bMakePass = true; break; #ifdef HAVE_LIBSSL case 'p': bMakePem = true; break; #endif /* HAVE_LIBSSL */ case 'd': sDataDir = CString(optarg); break; case 'D': CUtils::SetDebug(true); break; case '?': default: GenerateHelp(argv[0]); return 1; } } if (optind < argc) { sConfig = argv[optind]; } if (!InitCsocket()) { CUtils::PrintError("Failed to initialize Csocket!"); exit(-1); } CZNC* pZNC = &CZNC::Get(); pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir); #ifdef HAVE_LIBSSL if (bMakePem) { pZNC->WritePemFile(); delete pZNC; return 0; } #endif /* HAVE_LIBSSL */ if (bMakePass) { CString sSalt; CString sHash = CUtils::GetSaltedHashPass(sSalt); CUtils::PrintMessage("Use this in the <User> section of your config:"); CUtils::PrintMessage("Pass = "******"#" + sHash + "#" + sSalt + "#"); delete pZNC; return 0; } if (bMakeConf) { if (!pZNC->WriteNewConfig(sConfig)) { delete pZNC; return 0; } /* Fall through to normal bootup */ } if (!pZNC->ParseConfig(sConfig)) { if(argc < 2) { CUtils::PrintMessage("\n"); CUtils::PrintMessage("Press any key to continue..."); _getch(); } else { CUtils::PrintError("Unrecoverable config error."); } delete pZNC; return 1; } if (!pZNC->OnBoot()) { CUtils::PrintError("Exiting due to module boot errors."); delete pZNC; return 1; } // removed: checks for isRoot, bForeground, forking and signal handlers int iRet = 0; try { pZNC->Loop(&g_bMainLoop); CUtils::PrintMessage("Terminating ..."); } catch (CException e) { switch (e.GetType()) { case CException::EX_Shutdown: iRet = 0; CUtils::PrintMessage("************** Shutting down ZNC... **************"); break; case CException::EX_Restart: { // strdup() because GCC is stupid char *args[] = { strdup(argv[0]), strdup("--datadir"), strdup(pZNC->GetZNCPath().c_str()), NULL, NULL, NULL, NULL, NULL }; int pos = 3; if (CUtils::Debug()) args[pos++] = strdup("--debug"); #if 0 else if (bForeground) args[pos++] = strdup("--foreground"); if (!CUtils::StdoutIsTTY()) args[pos++] = strdup("--no-color"); if (bAllowRoot) args[pos++] = strdup("--allow-root"); #endif args[pos++] = strdup(pZNC->GetConfigFile().c_str()); // The above code adds 4 entries to args tops // which means the array should be big enough CUtils::PrintMessage("************** Restarting ZNC... **************"); delete pZNC; /* stuff screws up real bad if we don't close all sockets etc. */ pZNC = NULL; execvp(args[0], args); CUtils::PrintError("Unable to restart znc [" + CString(strerror(errno)) + "]"); } /* Fall through */ default: iRet = 1; } } delete pZNC; #ifdef _DEBUG ::_getch(); #endif return iRet; }
int main() { testInputCases(); _getch(); }
int main() { PIMAGE_DOS_HEADER pDosHeader; PIMAGE_NT_HEADERS pImageHeader; PIMAGE_DATA_DIRECTORY pDataDirectory; PIMAGE_IMPORT_DESCRIPTOR pImportDescriptor; PIMAGE_THUNK_DATA32 pFirstThunk; PIMAGE_THUNK_DATA32 pOriginalFirstThunk; PIMAGE_IMPORT_BY_NAME pNameImg; PIMAGE_SECTION_HEADER pSecHeader; char szFileName[MAX_PATH]; DWORD dwName, dwTest; LPDWORD lpwdAddress; HANDLE hMap, hMapView; BOOL bFound = FALSE; LPVOID lpMap; printf("File: "); scanf("%s", szFileName); hFile = CreateFile(szFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile == INVALID_HANDLE_VALUE) Error(); hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if(!hMap) Error(); hMapView = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0); if(!hMapView) Error(); pDosHeader = (PIMAGE_DOS_HEADER)hMapView; if(pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) Error(); else printf("\n%x (MZ) found, valid PE\nPE Header offset: 0x%x\n", pDosHeader->e_magic, pDosHeader->e_lfanew); pImageHeader = (PIMAGE_NT_HEADERS)((char*)pDosHeader + pDosHeader->e_lfanew); if(pImageHeader->Signature != IMAGE_NT_SIGNATURE) Error(); else { printf("\n%x (PE00) signature found\nImageBase: 0x%x\n\n", pImageHeader->Signature, pImageHeader->OptionalHeader.ImageBase); if(pImageHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) printf("\"%s\" is GUI based", szFileName); else if(pImageHeader->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI) printf("\"%s\" is CLI based", szFileName); else printf("\"%s\" is something else", szFileName); } printf("\nAddress of Entry Point: 0x%x", pImageHeader->OptionalHeader.AddressOfEntryPoint); printf("\n\nLocating IAT\n"); pDataDirectory = &pImageHeader->OptionalHeader.DataDirectory[1]; pImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)((char*)pDosHeader + RvaToOffset(pImageHeader, pDataDirectory->VirtualAddress)); pOriginalFirstThunk = (PIMAGE_THUNK_DATA32)((char*)pDosHeader + RvaToOffset(pImageHeader, pImportDescriptor->OriginalFirstThunk)); pSecHeader = IMAGE_FIRST_SECTION(pImageHeader); printf("IAT Entrypoint: 0x%x\nDumping IAT...\n", (pDataDirectory - pSecHeader->VirtualAddress) + pSecHeader->PointerToRawData); while(pImportDescriptor->OriginalFirstThunk != 0 && !bFound) { dwName = (DWORD)((char*)lpMap + RvaToOffset(pImageHeader, pImportDescriptor->Name)); pOriginalFirstThunk = (PIMAGE_THUNK_DATA32)((char*)pDosHeader + RvaToOffset(pImageHeader, pImportDescriptor->OriginalFirstThunk)); pFirstThunk = (PIMAGE_THUNK_DATA32)((char*)pDosHeader + RvaToOffset(pImageHeader, pImportDescriptor->FirstThunk)); while(pOriginalFirstThunk->u1.AddressOfData != 0 && !bFound) { pNameImg = (PIMAGE_IMPORT_BY_NAME)((char*)pDosHeader + RvaToOffset(pImageHeader, pOriginalFirstThunk->u1.AddressOfData)); dwTest = (DWORD)pOriginalFirstThunk->u1.Function & (DWORD)IMAGE_ORDINAL_FLAG32; printf("\nAddr: 0x%x (0x%x) - Name: %s", pOriginalFirstThunk->u1.Function, pFirstThunk->u1.AddressOfData, (const char *)pNameImg->Name); if(dwTest == 0) if(strcmp("printf", (const char *)pNameImg->Name) == 0) { lpwdAddress = (LPDWORD)pFirstThunk->u1.Function; bFound = TRUE; } pOriginalFirstThunk++; pFirstThunk++; } pImportDescriptor++; } printf("\n...Done"); CloseHandle(hFile); _getch(); return 0; }
int main(){ int number = 0; printf("Enter your score => "); scanf("%d", &number); switch (number) { case 100: case 99: case 98: case 97: case 96: case 95: case 94: case 93: case 92: case 91: case 90: case 89: case 88: case 87: case 86: case 85: case 84: case 83: case 82: case 81: case 80: printf("grade = 4\n"); break; case 79: case 78: case 77: case 76: case 75: case 74: case 73: case 72: case 71: case 70: printf("grade = 3\n"); break; case 69: case 68: case 67: case 66: case 65: case 64: case 63: case 62: case 61: case 60: printf("grade = 2\n"); break; case 59: case 58: case 57: case 56: case 55: case 54: case 53: case 52: case 51: case 50: printf("grade = 1\n"); break; case 49: case 48: case 47: case 46: case 45: case 44: case 43: case 42: case 41: case 40: case 39: case 38: case 37: case 36: case 35: case 34: case 33: case 32: case 31: case 30: case 29: case 28: case 27: case 26: case 25: case 24: case 23: case 22: case 21: case 20: case 19: case 18: case 17: case 16: case 15: case 14: case 13: case 12: case 11: case 10: case 9: case 8: case 7: case 6: case 5: case 4: case 3: case 2: case 1: case 0: printf("grade = 0\n"); break; default: printf("Score is out of 0-100"); break; } _getch(); system("cls"); main(); }
int main(int argc, char *argv[]) { FMOD::System *system; FMOD::Sound *sound; FMOD::Channel *channel = 0; FMOD_RESULT result; int key; unsigned int version; HANDLE threadhandle; InitializeCriticalSection(&gCrit); threadhandle = (HANDLE)_beginthreadex(NULL, 0, ProcessQueue, 0, 0, 0); if (!threadhandle) { printf("Failed to create file thread.\n"); return 0; } /* Create a System object and initialize. */ result = FMOD::System_Create(&system); ERRCHECK(result); result = system->getVersion(&version); ERRCHECK(result); if (version < FMOD_VERSION) { printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION); return 0; } result = system->init(1, FMOD_INIT_NORMAL, 0); ERRCHECK(result); result = system->setStreamBufferSize(32768, FMOD_TIMEUNIT_RAWBYTES); ERRCHECK(result); result = system->setFileSystem(myopen, myclose, myread, myseek, myasyncread, myasynccancel, 2048); ERRCHECK(result); printf("====================================================================\n"); printf("Stream IO Example. Copyright (c) Firelight Technologies 2004-2011.\n"); printf("====================================================================\n"); printf("\n"); printf("\n"); printf("====================== CALLING CREATESOUND ON MP3 =======================\n"); result = system->createStream("../media/wave.mp3", FMOD_SOFTWARE | FMOD_LOOP_NORMAL | FMOD_2D | FMOD_IGNORETAGS, 0, &sound); ERRCHECK(result); printf("====================== CALLING PLAYSOUND ON MP3 =======================\n"); result = system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel); ERRCHECK(result); /* Main loop. */ do { if (sound) { FMOD_OPENSTATE openstate; bool starving; sound->getOpenState(&openstate, 0, &starving, 0); if (starving) { printf("Starving\n"); result = channel->setMute(true); } else { result = channel->setMute(false); ERRCHECK(result); } } if (_kbhit()) { key = _getch(); switch (key) { case ' ' : { result = sound->release(); if (result == FMOD_OK) { sound = 0; printf("Released sound.\n"); } break; } } } system->update(); Sleep(10); } while (key != 27); printf("\n"); /* Shut down */ if (sound) { result = sound->release(); ERRCHECK(result); } result = system->close(); ERRCHECK(result); result = system->release(); ERRCHECK(result); gThreadQuit = true; return 0; }