Пример #1
0
void GameManager::gameOver()
{
	initGame();
}
void moveTitleMenu() {
   int pad = getPadState();
   int btn = getButtonState();
   int bs = slcStg;
   if ( pad & PAD_DOWN ) {
      if ( mnp ) {
         if ( slcStg < STAGE_NUM-SAME_RANK_STAGE_NUM ) slcStg += SAME_RANK_STAGE_NUM;
         else if ( slcStg == QUIT_STAGE_NUM ) slcStg = -MODE_NUM;
         else slcStg = QUIT_STAGE_NUM;
      }
   } else if ( pad & PAD_UP ) {
      if ( mnp ) {
         if ( slcStg >= 0 ) slcStg -= SAME_RANK_STAGE_NUM;
         else slcStg = QUIT_STAGE_NUM ;
      }
   } else if ( pad & PAD_RIGHT ) {
      if ( mnp ) {
         if ( slcStg >= 0 ) {
            if ( (slcStg%SAME_RANK_STAGE_NUM) < SAME_RANK_STAGE_NUM-1 && slcStg != QUIT_STAGE_NUM ) {
               slcStg++;
            }
         } else if ( slcStg < -1 ) {
            slcStg++;
         }
      }
   } else if ( pad & PAD_LEFT ) {
      if ( mnp ) {
         if ( slcStg >= 0 ) {
            if ( (slcStg%SAME_RANK_STAGE_NUM) > 0 && slcStg != QUIT_STAGE_NUM ) {
               slcStg--;
            }
         } else if ( slcStg > -4 ) {
            slcStg--;
         }
      }
   } else if ( btn == 0 ) {
      mnp = 1;
   }
   if ( slcStg != bs ) {
      mnp = 0;
      initTitleStage(slcStg);
      titleCnt = 0;
   }
   if ( mnp && (btn & PAD_BUTTON1) ) {
      if ( slcStg == QUIT_STAGE_NUM  ) {
         quitLast();
      } else if ( slcStg < 0 ) {
         mnp = 0;
         setMode(MODE_NUM+slcStg);
      } else {
         hiScore.stage = slcStg;
         initGame(slcStg);
      }
   }
   if ( mnp && (btn & PAD_BUTTON2) ) {
      mnp = 0;
      setMode((mode+1)%MODE_NUM);
      initTitleStage(slcStg);
      titleCnt = 0;
   }
   titleCnt++;
}
Пример #3
0
Common::Error SciEngine::run() {
	_resMan = new ResourceManager();
	assert(_resMan);
	_resMan->addAppropriateSources();
	_resMan->init();

	// TODO: Add error handling. Check return values of addAppropriateSources
	// and init. We first have to *add* sensible return values, though ;).
/*
	if (!_resMan) {
		warning("No resources found, aborting");
		return Common::kNoGameDataFoundError;
	}
*/

	// Reset, so that error()s before SoundCommandParser is initialized wont cause a crash
	_soundCmd = NULL;

	// Add the after market GM patches for the specified game, if they exist
	_resMan->addNewGMPatch(_gameId);
	_gameObjectAddress = _resMan->findGameObject();

	_scriptPatcher = new ScriptPatcher();
	SegManager *segMan = new SegManager(_resMan, _scriptPatcher);

	// Read user option for forcing hires graphics
	// Only show/selectable for:
	//  - King's Quest 6 CD
	//  - King's Quest 6 CD demo
	//  - Gabriel Knight 1 CD
	//  - Police Quest 4 CD
	// TODO: Check, if Gabriel Knight 1 floppy supports high resolution
	//
	// Gabriel Knight 1 on Mac is hi-res only, so it should NOT get this option.
	// Confirmed by [md5] and originally by clone2727.
	if (Common::checkGameGUIOption(GAMEOPTION_HIGH_RESOLUTION_GRAPHICS, ConfMan.get("guioptions"))) {
		// GAMEOPTION_HIGH_RESOLUTION_GRAPHICS is available for the currently detected game,
		// so read the user option now.
		// We need to do this, because the option's default is "true", but we don't want "true"
		// for any game that does not have this option.
		_forceHiresGraphics = ConfMan.getBool("enable_high_resolution_graphics");
	}

	if (getSciVersion() < SCI_VERSION_2) {
		// Initialize the game screen
		_gfxScreen = new GfxScreen(_resMan);
		_gfxScreen->enableUndithering(ConfMan.getBool("disable_dithering"));
	} else {
		_gfxScreen = nullptr;
	}

	_kernel = new Kernel(_resMan, segMan);
	_kernel->init();

	_features = new GameFeatures(segMan, _kernel);
	// Only SCI0, SCI01 and SCI1 EGA games used a parser
	_vocabulary = (getSciVersion() <= SCI_VERSION_1_EGA_ONLY) ? new Vocabulary(_resMan, false) : NULL;
	// Also, XMAS1990 apparently had a parser too. Refer to http://forums.scummvm.org/viewtopic.php?t=9135
	if (getGameId() == GID_CHRISTMAS1990)
		_vocabulary = new Vocabulary(_resMan, false);

	_gamestate = new EngineState(segMan);
	_eventMan = new EventManager(_resMan->detectFontExtended());
#ifdef ENABLE_SCI32
	if (getSciVersion() >= SCI_VERSION_2_1_EARLY) {
		_audio32 = new Audio32(_resMan);
	} else
#endif
		_audio = new AudioPlayer(_resMan);
#ifdef ENABLE_SCI32
	if (getSciVersion() >= SCI_VERSION_2) {
		_video32 = new Video32(segMan, _eventMan);
	}
#endif
	_sync = new Sync(_resMan, segMan);

	// Create debugger console. It requires GFX and _gamestate to be initialized
	_console = new Console(this);

	// The game needs to be initialized before the graphics system is initialized, as
	// the graphics code checks parts of the seg manager upon initialization (e.g. for
	// the presence of the fastCast object)
	if (!initGame()) { /* Initialize */
		warning("Game initialization failed: Aborting...");
		// TODO: Add an "init failed" error?
		return Common::kUnknownError;
	}

	// we try to find the super class address of the game object, we can't do that earlier
	const Object *gameObject = segMan->getObject(_gameObjectAddress);
	if (!gameObject) {
		warning("Could not get game object, aborting...");
		return Common::kUnknownError;
	}

	script_adjust_opcode_formats();

	// Must be called after game_init(), as they use _features
	_kernel->loadKernelNames(_features);

	// Load our Mac executable here for icon bar palettes and high-res fonts
	loadMacExecutable();

	// Initialize all graphics related subsystems
	initGraphics();

	// Sound must be initialized after graphics because SysEx transfers at the
	// start of the game must pump the event loop to avoid making the OS think
	// that ScummVM is hanged, and pumping the event loop requires GfxCursor to
	// be initialized
	_soundCmd = new SoundCommandParser(_resMan, segMan, _kernel, _audio, _features->detectDoSoundType());

	syncSoundSettings();
	syncIngameAudioOptions();

	// Patch in our save/restore code, so that dialogs are replaced
	patchGameSaveRestore();
	setLauncherLanguage();

	// Check whether loading a savestate was requested
	int directSaveSlotLoading = ConfMan.getInt("save_slot");
	if (directSaveSlotLoading >= 0) {
		_gamestate->_delayedRestoreGame = true;
		_gamestate->_delayedRestoreGameId = directSaveSlotLoading;
		_gamestate->_delayedRestoreFromLauncher = true;

		// Jones only initializes its menus when restarting/restoring, thus set
		// the gameIsRestarting flag here before initializing. Fixes bug #6536.
		if (g_sci->getGameId() == GID_JONES)
			_gamestate->gameIsRestarting = GAMEISRESTARTING_RESTORE;
	}

	// Show any special warnings for buggy scripts with severe game bugs,
	// which have been patched by Sierra
	if (getGameId() == GID_LONGBOW) {
		// Longbow 1.0 has a buggy script which prevents the game
		// from progressing during the Green Man riddle sequence.
		// A patch for this buggy script has been released by Sierra,
		// and is necessary to complete the game without issues.
		// The patched script is included in Longbow 1.1.
		// Refer to bug #3036609.
		Resource *buggyScript = _resMan->findResource(ResourceId(kResourceTypeScript, 180), 0);

		if (buggyScript && (buggyScript->size == 12354 || buggyScript->size == 12362)) {
			showScummVMDialog("A known buggy game script has been detected, which could "
			                  "prevent you from progressing later on in the game, during "
			                  "the sequence with the Green Man's riddles. Please, apply "
			                  "the latest patch for this game by Sierra to avoid possible "
			                  "problems");
		}
	}

	if (getGameId() == GID_KQ7 && ConfMan.getBool("subtitles")) {
		showScummVMDialog("Subtitles are enabled, but subtitling in King's"
						  " Quest 7 was unfinished and disabled in the release"
						  " version of the game. ScummVM allows the subtitles"
						  " to be re-enabled, but because they were removed from"
						  " the original game, they do not always render"
						  " properly or reflect the actual game speech."
						  " This is not a ScummVM bug -- it is a problem with"
						  " the game's assets.");
	}

	// Show a warning if the user has selected a General MIDI device, no GM patch exists
	// (i.e. patch 4) and the game is one of the known 8 SCI1 games that Sierra has provided
	// after market patches for in their "General MIDI Utility".
	if (_soundCmd->getMusicType() == MT_GM && !ConfMan.getBool("native_mt32")) {
		if (!_resMan->findResource(ResourceId(kResourceTypePatch, 4), 0)) {
			switch (getGameId()) {
			case GID_ECOQUEST:
			case GID_HOYLE3:
			case GID_LSL1:
			case GID_LSL5:
			case GID_LONGBOW:
			case GID_SQ1:
			case GID_SQ4:
			case GID_FAIRYTALES:
				showScummVMDialog("You have selected General MIDI as a sound device. Sierra "
				                  "has provided after-market support for General MIDI for this "
				                  "game in their \"General MIDI Utility\". Please, apply this "
				                  "patch in order to enjoy MIDI music with this game. Once you "
				                  "have obtained it, you can unpack all of the included *.PAT "
				                  "files in your ScummVM extras folder and ScummVM will add the "
				                  "appropriate patch automatically. Alternatively, you can follow "
				                  "the instructions in the READ.ME file included in the patch and "
				                  "rename the associated *.PAT file to 4.PAT and place it in the "
				                  "game folder. Without this patch, General MIDI music for this "
				                  "game will sound badly distorted.");
				break;
			default:
				break;
			}
		}
	}

	if (gameHasFanMadePatch()) {
		showScummVMDialog("Your game is patched with a fan made script patch. Such patches have "
		                  "been reported to cause issues, as they modify game scripts extensively. "
		                  "The issues that these patches fix do not occur in ScummVM, so you are "
		                  "advised to remove this patch from your game folder in order to avoid "
		                  "having unexpected errors and/or issues later on.");
	}

	runGame();

	ConfMan.flushToDisk();

	return Common::kNoError;
}
Пример #4
0
//////////////////////////////////////////////////////////////////
// game
//
//
//
// Returns:
//    void
//
void game(void) {
    u8 moved;
    u8 *pvmem;
    u8 dir = 0;


    initGame();

    // Clear Screen
    clearScreen();

    pvmem = cpct_getScreenPtr(CPCT_VMEM_START, 61, 72);
    cpct_drawSprite(logo_small, pvmem, 15, 55);

    //drawFrame(2, 1, 49, 182);
    drawTable();
    drawText("NEXT", 62, 2, 0);
    printCells();
    highestCardGame = getHighestCard();
    drawText("HIGHEST", 59, 138, 0);
    pvmem = cpct_getScreenPtr(CPCT_VMEM_START, 63, 154);
    cpct_drawSprite(cards[highestCardGame], pvmem, CARD_W, CARD_H);

    moved = 0;
    // Loop forever
    while (1) {
        delay(24);

        rotatedCells = 0;

        if ((cpct_isKeyPressed(Joy0_Right)) || (cpct_isKeyPressed(keys.right))) {
            if (rotateCellsRight() > 0) {
                dir = RIGHT;
                addRandomCellTurn(RIGHT);
                moved = 1;
            }
        } else if ((cpct_isKeyPressed(Joy0_Left)) || (cpct_isKeyPressed(keys.left))) {
            if (rotateCellsLeft() > 0) {
                dir = LEFT;
                addRandomCellTurn(LEFT);
                moved = 1;
            }
        } else if ((cpct_isKeyPressed(Joy0_Down)) || (cpct_isKeyPressed(keys.down))) {
            if (rotateCellsDown() > 0) {
                dir = DOWN;
                addRandomCellTurn(DOWN);
                moved = 1;
            }
        } else if ((cpct_isKeyPressed(Joy0_Up)) || (cpct_isKeyPressed(keys.up))) {
            if (rotateCellsUp() > 0) {
                dir = UP;
                addRandomCellTurn(UP);
                moved = 1;
            }

        } else if ( cpct_isKeyPressed(keys.music)) {
            if (!playing) {
                activateMusic();
            } else {
                deActivateMusic();
            }
        } else if (cpct_isKeyPressed(keys.abort))
            break;

        if (moved) {
            //Empty the rotated cells buffer after ending the animation
            //cpct_waitVSYNC();

            if (changedCards.number > 0) {
                animate(dir);
                resetChangedCards();

                highestCardGame = getHighestCard();
                pvmem = cpct_getScreenPtr(CPCT_VMEM_START, 63, 154);
                cpct_drawSprite(cards[highestCardGame], pvmem, CARD_W, CARD_H);

                // Play sound Effect
                cpct_akp_SFXPlay(3, 14, 50 + (highestCardGame * 2), 1, 0, AY_CHANNEL_A);

            }

            moved = 0;
            if (anyMovesLeft() == 0) {
                cpct_akp_stop();
                cpct_akp_musicInit(song05);
                cpct_akp_musicPlay();
                drawScore();
                wait4UserKeypress();
                drawFrame(14, 60, 68, 130);
                drawText("NO MORE MOVES", 20, 70, 1);
                drawText("GAME OVER", 22, 90, 1);
                sprintf(aux_txt, "SCORE  %d", score);
                drawText(aux_txt, 22, 110, 1);
                delay(200);
                wait4UserKeypress();
                setHighScore(score);
                drawScoreBoard();
                cpct_akp_stop();
                cpct_akp_musicInit(song02);
                cpct_akp_musicPlay();
                break;
            }
        }

    }
}
Пример #5
0
int main(int argc, char *argv[])
{
    Game *g = (Game*) malloc(sizeof(Game));
    SDL_Event event;
    Uint8 *keystates;
    Uint8 quit = false;
    long lastplayerupdate = ms_time();
    long lastenemyupdate = ms_time();
    long lastshotupdate = ms_time();
    long lastufoupdate = ms_time();
    
    srand((unsigned int) time(NULL));
    
    // SDL initialisieren
    if (SDL_Init(SDL_INIT_VIDEO) == -1) {
        printf("Kann Video nicht initialisieren: %s\n", SDL_GetError());
        exit(1);
    }
    
    atexit(SDL_Quit);
    
    g->screen = SDL_SetVideoMode(WIDTH, HEIGHT, 16, SDL_HWSURFACE);
    
    if (g->screen == NULL) {
        printf("Kann Video-Modus nicht festlegen: %s\n", SDL_GetError());
        exit(1);
    }
    
    TTF_Init();
    
    
    // Game initialisieren
    initGame(g);
    startNewLevel(g);
    updateScore(g);
    updateLives(g);
    showHighscore(g);
    updateBlocks(g);
    
    // Nächster Grafikzustand
    SDL_Flip(g->screen);
    
    // Loop
    while (!quit) {
        // SDL Events abfragen
        SDL_PollEvent(&event);
        
        // Tastenstatus laden
        keystates = SDL_GetKeyState(NULL);
        
        // Escape gedrückt -> beenden
        // TODO: Menü aufrufen statt beenden
        if (keystates[SDLK_ESCAPE]) {
            saveHighscore(g->score);
            quit = true;
        }
        
        // Nur wenn entweder Links oder Rechts, nicht beide zur selben Zeit
        if (keystates[SDLK_LEFT] != keystates[SDLK_RIGHT] && lastplayerupdate >= 100) {
            lastplayerupdate = ms_time();
            
            // Links
            if (keystates[SDLK_LEFT]) {
                movePlayer(g, Left);
            }
            // Rechts
            if (keystates[SDLK_RIGHT]) {
                movePlayer(g, Right);
            }
        }
        
        if (keystates[SDLK_SPACE]) {
            shoot(g);
        }
        
        // UFO
        if (ms_time() - lastufoupdate >= UFO_UPDATE) {
            lastufoupdate = ms_time();
            ufo(g);
        }
        
        // Alienposition aktualisieren?
        // Exponentialfunktion, die Level und Alienanzahl berücksichtigt
        if (ms_time() - lastenemyupdate >= ENEMY_UPDATE_BASE * pow(0.95, g->level * 3 + (ENEMY_COUNT - g->enemyContainer.aliveCount) / 4)) {
            lastenemyupdate = ms_time();
            updateBlocks(g);
            moveEnemys(g);
            alienShot(g);
        }
        
        // Schüsse aktualisieren
        if (ms_time() - lastshotupdate >= SHOT_UPDATE) {
            lastshotupdate = ms_time();
            updateShots(g);
            checkCollision(g);
            movePlayer(g, None);
        }
        
        usleep(20000); // begrenzt CPU Last
        // Nächster Grafikzustand
        SDL_Flip(g->screen);
    }
    
    SDL_Quit();
    return 0;
}
Пример #6
0
void Game::start(const LoadData* apSaveData)
{
	initGame(apSaveData);
}
Пример #7
0
void keyboardOperations(){

    if(!gameOver){


        //--------------------------- (Un)Pause
        if(keyStates['P'] || keyStates['p']){
            paused = !paused;
        }

        if(!paused){

            //--------------------------- forward
            if(keyStates['W'] || keyStates['w']){
                camera.Move(g_translation_speed);
                if( checkPlayerWallCollisions() ){
                    camera.Move(-g_translation_speed*bounceFactor); // undo
                }
                sounds.playWalkingSound();
            }

            //--------------------------- back
            if(keyStates['S'] || keyStates['s']){
                camera.Move(-g_translation_speed);
                if( checkPlayerWallCollisions() ){
                    camera.Move(g_translation_speed*bounceFactor); // undo
                }
                sounds.playWalkingSound();
            }

            //--------------------------- right
            if(keyStates['A'] || keyStates['a']){
                camera.Strafe(g_translation_speed);
                if( checkPlayerWallCollisions() ){
                    camera.Strafe(-g_translation_speed*bounceFactor); // undo
                }
                sounds.playWalkingSound();
            }

            //--------------------------- left
            if(keyStates['D'] || keyStates['d']){
                camera.Strafe(-g_translation_speed);
                if( checkPlayerWallCollisions() ){
                    camera.Strafe(g_translation_speed*bounceFactor); // undo
                }
                sounds.playWalkingSound();
            }


            //--------------------------- reload
            if(keyStates['R'] || keyStates['r']){
                reloadGun();
            }

            //--------------------------- main menu
            if(keyStates['M'] || keyStates['m']){
                isMenuActive = !isMenuActive;
            }


            // ------------------------------ move vertically for DEBUG
            //--------------------------- up
            if(keyStates['U'] || keyStates['u']){
                if(DEBUG_MODE) camera.Fly(g_translation_speed);
            }
            //--------------------------- down
            if(keyStates['J'] || keyStates['j']){
                if(DEBUG_MODE) camera.Fly(-g_translation_speed);
            }

        }
    }


    // restart game
    if(keyStates[' ']){
        gameOver = false;
        initGame();
    }

    //--------------------------- Escape
    if(keyStates[27]){
        exit(0);
    }

    glutPostRedisplay();

}
Пример #8
0
int loadContinueData()
{
	char itemName[MAX_MESSAGE_LENGTH], mapName[MAX_MESSAGE_LENGTH];
	char saveFile[MAX_PATH_LENGTH], *line, *savePtr;
	unsigned char *buffer;
	FILE *fp;

	savePtr = NULL;

	snprintf(saveFile, sizeof(saveFile), "%scontinuesave", gameSavePath);

	fp = fopen(saveFile, "rb");

	if (fp == NULL)
	{
		return FALSE;
	}

	fclose(fp);

	freeGameResources();

	initGame();

	game.canContinue = TRUE;

	buffer = decompressFile(saveFile);

	if (strlen((char *)buffer) == 0)
	{
		showErrorAndExit("Something went wrong when decompressing the continue file");
	}

	line = strtok_r((char *)buffer, "\n", &savePtr);

	while (line != NULL)
	{
		if (line[strlen(line) - 1] == '\n')
		{
			line[strlen(line) - 1] = '\0';
		}

		if (line[strlen(line) - 1] == '\r')
		{
			line[strlen(line) - 1] = '\0';
		}

		sscanf(line, "%s", itemName);

		if (strcmpignorecase("PLAY_TIME", itemName) == 0)
		{
			sscanf(line, "%*s %ld\n", &game.playTime);
		}

		else if (strcmpignorecase("PLAYER_KILLS", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.kills);
		}

		else if (strcmpignorecase("BATS_DROWNED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.batsDrowned);
		}

		else if (strcmpignorecase("TIMES_EATEN", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.timesEaten);
		}

		else if (strcmpignorecase("DISTANCE_TRAVELLED", itemName) == 0)
		{
			sscanf(line, "%*s %u\n", &game.distanceTravelled);
		}

		else if (strcmpignorecase("ATTACKS_BLOCKED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.attacksBlocked);
		}

		else if (strcmpignorecase("SLIME_TIME", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.timeSpentAsSlime);
		}

		else if (strcmpignorecase("ARROWS_FIRED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.arrowsFired);
		}

		else if (strcmpignorecase("SECRETS_FOUND", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.secretsFound);
		}

		else if (strcmpignorecase("CONTINUES", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.continues);
		}

		else if (strcmpignorecase("CHEATING", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.cheating);
		}

		else if (strcmpignorecase("PLAYER_LOCATION", itemName) == 0)
		{
			sscanf(line, "%*s %s\n", itemName);

			loadMap(itemName, FALSE);

			snprintf(mapName, sizeof(mapName), "MAP_NAME %s", itemName);
		}

		else if (strcmpignorecase(line, mapName) == 0)
		{
			loadResources(savePtr);
		}

		line = strtok_r(NULL, "\n", &savePtr);
	}

	free(buffer);

	copyFile(saveFile, tempFile);

	buffer = decompressFile(tempFile);

	free(buffer);

	cameraSnapToTargetEntity();

	freeMessageQueue();

	return TRUE;
}
Пример #9
0
int loadGame(int slot)
{
	char itemName[MAX_MESSAGE_LENGTH], mapName[MAX_MESSAGE_LENGTH], backup[MAX_PATH_LENGTH];
	char saveFile[MAX_PATH_LENGTH], *line, *savePtr, completion[5];
	double version = 0;
	float percentage, steps;
	unsigned char *buffer;
	int patchGame = FALSE, foundResources;
	FILE *fp;

	savePtr = NULL;

	snprintf(saveFile, sizeof(saveFile), "%ssave%d", gameSavePath, slot);

	fp = fopen(saveFile, "rb");

	if (fp == NULL)
	{
		return FALSE;
	}

	fclose(fp);

	freeGameResources();

	initGame();

	buffer = decompressFile(saveFile);

	line = strtok_r((char *)buffer, "\n", &savePtr);

	foundResources = FALSE;

	while (line != NULL)
	{
		if (line[strlen(line) - 1] == '\n')
		{
			line[strlen(line) - 1] = '\0';
		}

		if (line[strlen(line) - 1] == '\r')
		{
			line[strlen(line) - 1] = '\0';
		}

		sscanf(line, "%s", itemName);

		if (strcmpignorecase("VERSION", itemName) == 0)
		{
			sscanf(line, "%*s %s\n", itemName);

			version = atof(itemName);

			if (version > VERSION)
			{
				printf("Save file version is newer than game version. This game might not work correctly.\n");
			}
		}

		else if (strcmpignorecase("PLAY_TIME", itemName) == 0)
		{
			sscanf(line, "%*s %ld\n", &game.playTime);
		}

		else if (strcmpignorecase("PLAYER_KILLS", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.kills);
		}

		else if (strcmpignorecase("BATS_DROWNED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.batsDrowned);
		}

		else if (strcmpignorecase("TIMES_EATEN", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.timesEaten);
		}

		else if (strcmpignorecase("DISTANCE_TRAVELLED", itemName) == 0)
		{
			sscanf(line, "%*s %u\n", &game.distanceTravelled);
		}

		else if (strcmpignorecase("ATTACKS_BLOCKED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.attacksBlocked);
		}

		else if (strcmpignorecase("SLIME_TIME", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.timeSpentAsSlime);
		}

		else if (strcmpignorecase("ARROWS_FIRED", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.arrowsFired);
		}

		else if (strcmpignorecase("SECRETS_FOUND", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.secretsFound);
		}

		else if (strcmpignorecase("CONTINUES", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.continues);
		}

		else if (strcmpignorecase("CHEATING", itemName) == 0)
		{
			sscanf(line, "%*s %d\n", &game.cheating);
		}

		else if (strcmpignorecase("PLAYER_LOCATION", itemName) == 0)
		{
			if (version < VERSION)
			{
				patchGame = TRUE;

				break;
			}

			sscanf(line, "%*s %s\n", itemName);

			loadMap(itemName, FALSE);

			snprintf(mapName, sizeof(mapName), "MAP_NAME %s", itemName);
		}

		else if (strcmpignorecase(line, mapName) == 0)
		{
			foundResources = TRUE;

			loadResources(savePtr);
		}

		line = strtok_r(NULL, "\n", &savePtr);
	}

	if (patchGame == TRUE)
	{
		free(buffer);

		steps = (VERSION * 100) - (version * 100);

		steps = 100 / steps;

		percentage = 0;

		version += 0.01;

		/* Back up the original save file */

		snprintf(backup, sizeof(backup), "%s.bak", saveFile);

		copyFile(saveFile, backup);

		showPatchMessage("0%");

		while (TRUE)
		{
			getInput(IN_TITLE);

			patchSaveGame(saveFile, version);

			version += 0.01;

			percentage += steps;

			snprintf(completion, 5, "%d%%", (int)percentage);

			if ((int)(version * 100) > (int)(VERSION * 100))
			{
				break;
			}

			showPatchMessage(completion);
		}

		return loadGame(slot);
	}

	/* Fudge to make a game saved in the new Village map still load OK */

	if (foundResources == FALSE)
	{
		sscanf(mapName, "%*s %s\n", itemName);

		loadMap(itemName, TRUE);
	}

	free(buffer);

	copyFile(saveFile, tempFile);

	buffer = decompressFile(tempFile);

	free(buffer);

	cameraSnapToTargetEntity();

	freeMessageQueue();

	temporaryDataExists = TRUE;

	return TRUE;
}
Пример #10
0
int main(int argc, char* argv[])
{
  sSdlWrapper* wrap = initializeSDLWrapper("Snake", 800, 600, 32, 1, 1);
  game* gameEngine  = initGame(wrap, 32, 24);
  int Selection = 0;
  sTextGFX* startUnsel = createText(wrap, "Start Game", 0xFFFFFFFF);
  sTextGFX* startSel   = createText(wrap, "Start Game", 0xFFFFF000);
  sTextGFX* exitUnsel  = createText(wrap, "Exit Game" , 0xFFFFFFFF);
  sTextGFX* exitSel    = createText(wrap, "Exit Game" , 0xFFFFF000);
  sLinkedList* titleList = 0;
  FILE* titleFile = fopen("snake.pic", "r");
  listInitialize(&titleList, sizeofPoint(), NULL);
  for(int x = 0; x < 32; x++)
    for(int y = 0; y < 24; y++)
      if(x == 0 || x == (31) || y == 0 || y == (23))
      {
	point* toAdd = createPoint(x,y);
	listPushFront(titleList, (void*)toAdd);
	free(toAdd);
      }
  while(isRunning(wrap))
  {
    beginFrame(wrap);
    if(State == -1)
    {
      readTitleFile(titleList, titleFile);
      renderList(titleList, wrap);
    }
    else if(State == 1)
      tick(gameEngine);
    else
    {
      if(Selection == 0)
      {
	renderText(wrap, startSel, 400, 300);
	renderText(wrap, exitUnsel, 400, 325);
      }
      else
      {
	renderText(wrap, startUnsel, 400, 300);
	renderText(wrap, exitSel, 400, 325);
      }
      if(keyDown(wrap, SDLK_DOWN))
	Selection = 1;
      if(keyDown(wrap,SDLK_UP))
	Selection = 0;
      if(keyDown(wrap, SDLK_RETURN))
      {
	if(Selection == 0)
	{
	  State = 1;
	  setupGame(gameEngine);
	}
	else
	  toggleRunning(wrap);
      }
      renderList(titleList, wrap);
    }
    if(keyPressed(wrap, SDLK_ESCAPE))
      toggleRunning(wrap);
    endFrame(wrap);
  }
  listClear(titleList);
  free(titleList);
  destroyText(startUnsel);
  destroyText(startSel);
  destroyText(exitUnsel);
  destroyText(exitSel);
  deinitializeWrapper(wrap);
  destroyGame(gameEngine);
  free(wrap);
  return 0;
}
Пример #11
0
int main(int argc, char *argv[])
{
	unsigned int frameLimit;
	int go, i, mapID, loadSlot, recordingID, replayingID;
	int joystick, showCredits, languageID;

	go = TRUE;

	loadSlot = -1;

	game.fps = 1000 / 60;

	languageID = mapID = recordingID = replayingID = -1;

	joystick = 0;

	showCredits = FALSE;

	/* Load the resources */

	for (i=1;i<argc;i++)
	{
		if (strcmpignorecase("-record", argv[i]) == 0)
		{
			if (i + 1 >= argc)
			{
				printf("You must specify a file to record to\n");
				printf("Type %s -h for help\n", argv[0]);

				exit(1);
			}

			if (recordingID == -1)
			{
				recordingID = i + 1;
			}

			i++;
		}

		else if (strcmpignorecase("-playback", argv[i]) == 0)
		{
			if (i + 1 >= argc)
			{
				printf("You must specify a file to playback from\n");
				printf("Type %s -h for help\n", argv[0]);

				exit(1);
			}

			if (replayingID == -1)
			{
				replayingID = i + 1;
			}

			i++;
		}

		else if (strcmpignorecase("-load", argv[i]) == 0)
		{
			if (i + 1 >= argc)
			{
				printf("You must specify a slot to load from\n");
				printf("Type %s -h for help\n", argv[0]);

				exit(1);
			}

			loadSlot = atoi(argv[i + 1]);

			i++;
		}

		else if (strcmpignorecase("-nojoystick", argv[i]) == 0)
		{
			game.disableJoystick = TRUE;
		}

		else if (strcmpignorecase("-joystick", argv[i]) == 0)
		{
			if (i + 1 >= argc)
			{
				printf("You must specify a joystick slot to use\n");
				printf("Type %s -h for help\n", argv[0]);

				exit(1);
			}

			joystick = atoi(argv[i + 1]);

			i++;
		}

		else if (strcmpignorecase("-showcredits", argv[i]) == 0)
		{
			showCredits = TRUE;
		}

		else if (strstr(argv[i], "-lang") != NULL)
		{
			if (i + 1 >= argc)
			{
				printf("You must specify a language to use\n");
				printf("Type %s -h for help\n", argv[0]);

				exit(1);
			}

			languageID = i + 1;

			i++;
		}

		else if (strstr(argv[i], "-h") != NULL || strstr(argv[i], "-help") != NULL)
		{
			printf("The Legend of Edgar options\n\n");
			printf("\t-record <filename>: Captures keyboard input\n");
			printf("\t-playback <filename>: Replays keyboard input\n");
			printf("\t-load <save_slot>: Loads the game in slot <save_slot>. Slots start at 0\n");
			printf("\t-nojoystick: Disables the joystick\n");
			printf("\t-joystick <joystick_slot>: Use joystick <joystick_slot>. Slots start at 0\n");
			printf("\t-showcredits: Shows the end credits\n");
			printf("\t-language <language_code>: Use language <language_code>. e.g. en_US, es, pl\n\n");

			exit(0);
		}

		#if DEV == 1
			else if (strcmpignorecase("-saveonexit", argv[i]) == 0)
			{
				game.saveOnExit = TRUE;
			}

			else if (strcmpignorecase("-bmpwrite", argv[i]) == 0)
			{
				setScreenshotDir(argv[i + 1]);

				i++;
			}

			else
			{
				mapID = i;
			}
		#endif
	}

	setLanguage("edgar", languageID == -1 ? NULL : argv[languageID]);
	printf("Numeric is %s\n", setlocale(LC_NUMERIC, "C"));
	printf("atof(2.75) is %f\n", atof("2.75"));

	/* Call the cleanup function when the program exits */

	atexit(cleanup);

	/* Start up SDL */

	init(_("The Legend of Edgar"), joystick);

	loadRequiredResources();

	if (replayingID != -1 && recordingID != -1)
	{
		showErrorAndExit("Cannot record and replay at the same time");
	}

	#if DEV == 0
		verifyVersion();
	#endif

	/* Initialise the game variables */

	freeGameResources();

	initGame();

	if (loadSlot == -1)
	{
		if (recordingID != -1)
		{
			setRecordData(argv[recordingID]);

			setMapFile(mapID == -1 ? "map01" : argv[mapID]);
		}

		else if (replayingID != -1)
		{
			setReplayData(argv[replayingID], TRUE);

			setMapFile(mapID == -1 ? "map01" : argv[mapID]);
		}

		if (mapID != -1)
		{
			startOnMap(argv[mapID]);
		}

		else if (game.firstRun == TRUE)
		{
			tutorial();
		}

		else
		{
			game.status = IN_TITLE;
		}
	}

	else
	{
		if (recordingID != -1)
		{
			game.gameType = RECORDING;
		}

		else if (replayingID != -1)
		{
			game.gameType = REPLAYING;
		}

		if (loadGame(loadSlot) == FALSE)
		{
			showErrorAndExit("No saved game in slot %d", loadSlot);
		}

		if (recordingID != -1)
		{
			setRecordData(argv[recordingID]);

			setMapFile(getMapFilename());
		}

		else if (replayingID != -1)
		{
			setReplayData(argv[replayingID], TRUE);
		}
	}

	/* Loop indefinitely for messages */

	game.startTicks = SDL_GetTicks();

	#if DEV == 1
		printf("DEV Version\n");
	#else
		printf("Production Version\n");
	#endif

	frameLimit = SDL_GetTicks() + game.fps;

	if (showCredits == TRUE)
	{
		game.status = IN_CREDITS;
	}

	while (go == TRUE)
	{
		getInput(game.gameType);

		switch (game.status)
		{
			case IN_TITLE:
				doTitle();
			break;

			case IN_GAME:
				freeCollisionGrid();

				clearDrawLayers();

				doGame();

				doPlayer();

				doInventory();

				doMap();

				doEntities();

				doDecorations();

				doCollisions();

				doHud();

				doDialogBox();

				processMedals();
			break;

			case IN_INVENTORY:
				doInventoryMenu();
			break;

			case IN_MENU:
				doMenu();
			break;

			case IN_CREDITS:
				freeCollisionGrid();

				clearDrawLayers();

				doGame();

				doCredits();

				doDecorations();

				doCollisions();
			break;

			default:
				doMenu();
			break;
		}

		draw();

		/* Sleep briefly to stop sucking up all the CPU time */

		delay(frameLimit);

		frameLimit = SDL_GetTicks() + game.fps;

		game.frames++;
	}

	/* Exit the program */

	exit(0);
}
Пример #12
0
int main(){
		int s_ecoute, s_dial, cli_len;
		int option = 1;
		struct sockaddr_in serv_addr, cli_addr;
		fd_set readfds;
		/*buf contient le déplacement (compris entre 0 et 3)
		 * map contient la map (qu'il faudra renvoyer à chaque changement
		 * character contiendra les états des deux personnages, 0 sera le premier arrivé
		 */
		int buf[1] = {0};
		int map[20][15] = {(0,0)};
		int bufMapJoueur[310] ={0};
		int i,j,k;
		int continuer = 1;

		Character character[2];
		for(i=0;i<2;i++){
			character[i] = malloc(sizeof(struct character));
		}

		int so_reuseaddr = 1;

		int actualNumberClient = 0;
		int nb_client_aff = 0;
		int descmax = 0;
		int client[2];

		struct timeval compte_rebours;

		compte_rebours.tv_usec = 0;
		compte_rebours.tv_sec = 600;
		/*********/
		/*********/

		serv_addr.sin_family = AF_INET;
		serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
		serv_addr.sin_port = htons(31337);
		memset(&serv_addr.sin_zero, 0, sizeof(serv_addr.sin_zero));

		s_ecoute = socket(PF_INET, SOCK_STREAM, 0);
		setsockopt(s_ecoute, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr, sizeof so_reuseaddr);

		bind(s_ecoute, (struct sockaddr *)&serv_addr, sizeof serv_addr);

		while(1) {
		listen(s_ecoute, 5);

		actualNumberClient = 0;
		/*Premiere boucle afin de récupérer le bon nombre de joueur*/
		while(actualNumberClient < 2){
				FD_ZERO(&readfds);
				FD_SET(s_ecoute, &readfds);
				descmax = s_ecoute;
				for(i=0;i<actualNumberClient;i++){
						FD_SET(client[i], &readfds);
				}
				if(s_dial > descmax){
						descmax = s_dial;
				}

					nb_client_aff = select(descmax + 1, &readfds, NULL, NULL, &compte_rebours);

					/*Lorsque nb_client_aff > 0, un des descripteur surveillé a reçu quelque chose*/
					if(nb_client_aff){
								if(FD_ISSET(s_ecoute, &readfds)){
										cli_len = sizeof cli_addr;
										s_dial = accept(s_ecoute, (struct sockaddr *)&cli_addr,
														(socklen_t *)&cli_len);
										printf("Le client %s s'est connecte\n", inet_ntoa
														(cli_addr.sin_addr),
														ntohs(cli_addr.sin_port));
										client[actualNumberClient] = s_dial;
										actualNumberClient++;
								}
					}
		}
		/*Initialisation de la map et des joueurs
		 * A completer */
		initGame(character, map);
		k = 0;
		while(k < 300) {
			for(i=0;i<NB_BLOCS_LARGEUR;i++){
				for(j=0;j<NB_BLOCS_HAUTEUR;j++){
					bufMapJoueur[k] = map[i][j];
					k++;
				}
			}
		}
		bufMapJoueur[300] = character[0]->life;
		bufMapJoueur[301] = character[0]->key;
		bufMapJoueur[302] = character[0]->gold;
		bufMapJoueur[303] = character[0]->x;
		bufMapJoueur[304] = character[0]->y;

		bufMapJoueur[305] = character[1]->life;
		bufMapJoueur[306] = character[1]->key;
		bufMapJoueur[307] = character[1]->gold;
		bufMapJoueur[308] = character[1]->x;
		bufMapJoueur[309] = character[1]->y;

		printf("Envoi des données en cours\n");
		for(i=0;i<2;i++){
			write(client[i],bufMapJoueur,310*sizeof(int));
		}
		printf("Envoi des données fini\n");

		/*Tant que l'un des joueurs n'a pas gagné ou perdu...*/
		continuer = 1;
		while(continuer){

			printf("Waiting for client action\n");
			FD_ZERO(&readfds);
				FD_SET(s_ecoute, &readfds);
				descmax = s_ecoute;
				for(i=0;i<actualNumberClient;i++){
						FD_SET(client[i], &readfds);
				}
				if(s_dial > descmax){
						descmax = s_dial;
				}
					nb_client_aff = select(descmax + 1, &readfds, NULL, NULL, &compte_rebours);

					/*Lorsque nb_client_aff > 0, un des descripteur surveillé a reçu quelque chose*/
					if(nb_client_aff){
							printf("Received client action, proceding...\n");
							/*Lecture des touches */
							for(i = 0;i<actualNumberClient;i++){
									if(FD_ISSET(client[i], &readfds)){
											//printf("Un client est en train de parler\n");
											bzero(buf,1);
											if(read(client[i], buf, 1) == -1){
												perror("Erreur lors de la lecture du socket, client déconnecté\n");
											}
											/*Traitement des touches que l'on recoit
											 * i=J1 ou J2 (prendre i+1) */
											if(buf[0] == 5) {

												bufMapJoueur[0] = 30;
												bufMapJoueur[1] = 35;
												bufMapJoueur[3] = 0;

												write(client[i],bufMapJoueur,310*sizeof(int));

												bufMapJoueur[0] = 35;
												bufMapJoueur[1] = 30;
												bufMapJoueur[3] = 1;


												if(i == 0) {
													write(client[1],bufMapJoueur,310*sizeof(int));
												}
												else {
													write(client[0],bufMapJoueur,310*sizeof(int));
												}
												continuer = 0;
											}
											else if(buf[0] == 0 || buf[0] == 1 || buf[0] == 2 || buf[0] == 3 || buf[0] == 18 || buf[0] == 5){
												move_character(map, buf[0], character[i]);

												if(character[i]->life == 0 || character[i]->gold == 10) {

													bufMapJoueur[0] = 30;
													bufMapJoueur[1] = 35;
													bufMapJoueur[3] = 0;

													write(client[i],bufMapJoueur,310*sizeof(int));

													bufMapJoueur[3] = 1;

													if(i == 0) {
														write(client[1],bufMapJoueur,310*sizeof(int));
													}
													else {
														write(client[0],bufMapJoueur,310*sizeof(int));
													}
													continuer = 0;
												}
												else {
													k = 0;
													while(k < 300) {
														for(i=0;i<NB_BLOCS_LARGEUR;i++){
															for(j=0;j<NB_BLOCS_HAUTEUR;j++){
																bufMapJoueur[k] = map[i][j];
																k++;
															}
														}
													}
													bufMapJoueur[300] = character[0]->life;
													bufMapJoueur[301] = character[0]->key;
													bufMapJoueur[302] = character[0]->gold;
													bufMapJoueur[303] = character[0]->x;
													bufMapJoueur[304] = character[0]->y;

													bufMapJoueur[305] = character[1]->life;
													bufMapJoueur[306] = character[1]->key;
													bufMapJoueur[307] = character[1]->gold;
													bufMapJoueur[308] = character[1]->x;
													bufMapJoueur[309] = character[1]->y;
												}

												printf("Envoi des données en cours\n");
												for(i=0;i<2;i++){
													if(write(client[i],bufMapJoueur,310*sizeof(int)) == -1) {
														bufMapJoueur[0] = 30;
														bufMapJoueur[1] = 35;
														bufMapJoueur[3] = 0;
														printf("L'un des deux joueurs s'est déconnecté, arrêt de la partie.\n");
														if(i == 0) {
															write(client[1],bufMapJoueur,310*sizeof(int));
														}
														else {
															write(client[0],bufMapJoueur,310*sizeof(int));
														}
														continuer = 0;
													}
												}
												printf("Envoi des données fini\n");
											}
									}
							}
					}
					/*Il faut renvoyer les données de la map, les données des deux joueurs
					 * (life/key/gold/position
					 * aux deux joueurs
					 * Ou renvoyer une indication de fin de jeu si l'un des personnages
					 * a gagné et mettre continuer à 0 */
		}
		close(client[0]);
		printf("Deconnexion premier client.\n");
		close(client[1]);
		printf("Deconnexion second client.\n");
	}
		close(s_ecoute);
		printf("Deconnexion du serveur.\n");

		return 0;
}
Пример #13
0
	/**
	 * @see Client::setReadyToInit
	 */
	void setReadyToInit() {
		if (!game.get()) {
			initGame();
		}
	}
Пример #14
0
bool FrameFunc()
{
	float dt=hge->Timer_GetDelta();
	bool keyD = false;
	bool keyF = false;
	bool keyLeft = false;
	bool keyRight = false;

	switch (gamestate)
	{
	case enter:
		if(hge->Input_GetKeyState(HGEK_SPACE))
		{
			gamestate = init;
		}
		break;
	case init:
		initGame();
		gamestate = fighting;
		break;
	case fighting:
		//判断左右移动
		if(hge->Input_GetKeyState(HGEK_LEFT))
		{
			keyLeft = true;
		}
		if(hge->Input_GetKeyState(HGEK_RIGHT))
		{
			keyRight = true;
		}
		//判断跳跃
		if(hge->Input_GetKeyState(HGEK_D))
		{
			keyD = true;
		}
		//判断射击
		if(hge->Input_GetKeyState(HGEK_F))
		{
			keyF = true;
		}


		for(b2Body* b = world->GetBodyList();b;b=b->GetNext())
		{
			if (b->GetUserData() != NULL)
			{
				GameObj* obj = (GameObj*)b->GetUserData();
				if(obj->getType() == obj_Fighter)
				{
					Fighter* f = (Fighter*)b->GetUserData();

					//站立的情况下按跳跃键
					if(keyD && f->getState() == standing)
					{
						f->setState(jumping);
						b->ApplyLinearImpulse(b2Vec2(0,b->GetMass()*-FIGHTER_JUMP),b->GetWorldCenter());
					}

					//冷却状态按下射击键
					if(keyF && f->getColdDown() <= 0)
					{
						f->setColdDown(FIGHTER_CD);
						//添加勇士的子弹
						f->fire();
					}

					//处理移动键
					if(keyLeft)
					{
						b2Vec2 oldv = b->GetLinearVelocity();
						b->SetLinearVelocity(b2Vec2(-(float)FIGHTER_V/PTM_RATIO,oldv.y));
					}
					else if(keyRight)
					{
						b2Vec2 oldv = b->GetLinearVelocity();
						b->SetLinearVelocity(b2Vec2((float)FIGHTER_V/PTM_RATIO,oldv.y));
					}
					else
					{
						b2Vec2 oldv = b->GetLinearVelocity();
						b->SetLinearVelocity(b2Vec2(0,oldv.y));
					}


					//根据物理引擎更新fighter的信息
					f->setPositionX(b->GetPosition().x*PTM_RATIO);
					f->setPositionY(b->GetPosition().y*PTM_RATIO);
					if(f->getColdDown() > 0)
					{
						f->setColdDown(f->getColdDown() - dt);
					}
					
				}
				else if(obj->getType() == obj_boss)
				{
					//施加一个力抵消重力
					float32 m = b->GetMass();
					b->ApplyForceToCenter(b2Vec2(0,-m*10));
					
					float center = WIN_HEIGHT / 2;
					float top = center - BOSS_MOVE_PATH/2;
					float button = center + BOSS_MOVE_PATH/2;

					if((b->GetPosition().y) < top/PTM_RATIO || (b->GetPosition().y) > button/PTM_RATIO)
					{
						b2Vec2 oldv = b->GetLinearVelocity();
						oldv.x = oldv.x * -1;
						oldv.y = oldv.y * -1;
						b->SetLinearVelocity(oldv);
					}

					//根据物理引擎更新boss的信息
					boss->setPositionX(b->GetPosition().x*PTM_RATIO);
					boss->setPositionY(b->GetPosition().y*PTM_RATIO);
					boss->setNormalFireCounter(boss->getNormalFireCounter()-dt);
					if(boss->getNormalFireCounter() < 0)
					{
						boss->fire(B1Bullet);
					}
					if(boss->getGoingToFire() == true)
					{
						boss->fire(B2Bullet);
						boss->setGoingToFire(false);
					}
				}
				else if(obj->getType() == obj_bullet)
				{
					//施加一个力抵消重力
					float32 m = b->GetMass();
					b->ApplyForceToCenter(b2Vec2(0,-m*10));

					Bullet *bullet = (Bullet*)obj;
					bullet->setPositionX(b->GetPosition().x*PTM_RATIO);
					bullet->setPositionY(b->GetPosition().y*PTM_RATIO);	
				}
				else
				{

				}
			}
		}
		for(bodyit=willDelete->begin();bodyit != willDelete->end();)
		{
			
			b2Body *b = (b2Body*)*bodyit;
			Bullet* bullet = (Bullet*)b->GetUserData();	
			world->DestroyBody(b);
			willDelete->erase(bodyit++);
			bullets->remove(bullet);
			
		}
		
		world->Step(dt,8,8);
		break; 
	case over:
		if(hge->Input_GetKeyState(HGEK_SPACE))
		{
			gamestate = init;
		}
		if(hge->Input_GetKeyState(HGEK_ESCAPE))
		{
			return true;
		}
		break;
	case win:
		if(hge->Input_GetKeyState(HGEK_SPACE))
		{

		}
		break;
	}

	return false;
}
Пример #15
0
Game::Game(char **p)
{
	initGame(p);
}
Пример #16
0
GameScene::GameScene(QWidget *parent) :
    QGraphicsScene(parent),
    myLock(false)
{
  inputDisabled = true;

  dconfirm = new ConfirmDialog();
  addWidget(dconfirm, Qt::FramelessWindowHint);
  dconfirm->hide();

  menu = new MenuWidget();
  addWidget(menu);
  menu->activate();

  connect(menu, SIGNAL(menuNew()), this, SLOT(on_menuNew()));
  connect(menu, SIGNAL(menuContinue()), this, SLOT(on_menuContinue()));
  connect(menu, SIGNAL(menuExit()), this, SLOT(on_menuExit()));
  connect(menu, SIGNAL(menuPauseBack()), this, SLOT(on_menuPauseBack()));
  connect(menu, SIGNAL(menuRestartLevel()), this, SLOT(on_menuRestartLevel()));
  connect(menu, SIGNAL(menuAbandonGame()), this, SLOT(on_menuAbandonGame()));
  connect(menu, SIGNAL(menuThemeChanged()), this, SLOT(on_menuThemeChanged()));
  connect(menu, SIGNAL(menuGameStart()), this, SLOT(on_menuGameStart()));
  connect(menu, SIGNAL(menuLevelPack()), this, SLOT(on_menuLevelPack()));

  stat = new StatInfo();

  connect(gameProfile, SIGNAL(profileChanged()), this, SLOT(initProfile()));

  rows = cols = 0;

  xoff = 20;
  yoff = 10;

  advanceTimer = new QTimer(this);
  advanceTimer->setInterval(30);
  connect(advanceTimer, SIGNAL(timeout()), this, SLOT(nextCycle()));

  timeTimer = new QTimer(this);
  timeTimer->setInterval(1000);
  connect(timeTimer, SIGNAL(timeout()), this, SLOT(countTime()));

  bonusTimer = new QTimer(this);
  bonusTimer->setInterval(500);
  connect(bonusTimer, SIGNAL(timeout()), this, SLOT(countBonusTime()));

  hintTimer = new QTimer(this);
  hintTimer->setInterval(10000);
  connect(hintTimer, SIGNAL(timeout()), this, SLOT(hintAvailableMoves()));

  // init components
  GameStock::init();

  toolset = new ToolSet();

  gameBonus = new GameBonus();

  setSceneRect(0,0, WIDTH, HEIGHT);

  // set background
  gameBackground = new GameBackground();
  setBackgroundBrush(Qt::black);

  setDefaultGameCursor();

  // update max level for current pack
  max_level = gameProfile->levelPackCount(gameProfile->currentLevelPack());

  // very first initialization
  initGame();
}
Пример #17
0
void Application::start()
{
    light_enabled_demo[0] = light_enabled_demo[1] = false;

    skybox_enabled_demo = shadow_enabled_demo = reflection_enabled_demo = light_enabled_demo[0] = light_enabled_demo[1] = true;
    
    glfwSetErrorCallback(error_callback);
    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,  GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    //const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());

    //window_height = mode->height;
    //window_width= mode->width;
    
    window_height = 400;
    window_width = 800;

    midWindowX = window_width/2;
    midWindowY = window_height/2;
    window = glfwCreateWindow(window_width, window_height, "Chess3D", NULL, NULL);

    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);

#ifndef __APPLE__
    glewExperimental = GL_TRUE;
    glewInit();
#endif

    std::cout << "OpenGL version supported by this platform: " << glGetString(GL_VERSION) << std::endl;

    initOpenGL();

    initGame();

    glfwSwapInterval(0);
    glfwSetKeyCallback(window, key_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, mousepos_callback);
    glfwSetWindowSizeCallback(window, window_size_callback);

    lastTime = glfwGetTime();
    nbFrames = 0;
    nbFramesLastSecond = 100;

    while (!glfwWindowShouldClose(window))
    {
        display();

        /* computing fps */
        double currentTime = glfwGetTime();
        nbFrames++;
        if (currentTime - lastTime >= 1.0)
        {
            nbFramesLastSecond = nbFrames;
            setTitleFps();
            nbFrames = 0;
            lastTime += 1.0;
        }
        scene.move(nbFramesLastSecond);
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Пример #18
0
Engine::Engine() {
	initGame();
	initSystems();
	// initEntities();
}
Пример #19
0
Common::Error SagaEngine::run() {
	setTotalPlayTime(0);

	// Assign default values to the config manager, in case settings are missing
	ConfMan.registerDefault("talkspeed", "255");
	ConfMan.registerDefault("subtitles", "true");

	_musicVolume = ConfMan.getInt("music_volume");
	_subtitlesEnabled = ConfMan.getBool("subtitles");
	_readingSpeed = getTalkspeed();
	_copyProtection = ConfMan.getBool("copy_protection");
	_musicWasPlaying = false;
	_isIHNMDemo = Common::File::exists("music.res");
	_hasITESceneSubstitutes = Common::File::exists("boarhall.bbm");

	if (_readingSpeed > 3)
		_readingSpeed = 0;

	switch (getGameId()) {
		case GID_ITE:
			_resource = new Resource_RSC(this);
			break;
#ifdef ENABLE_IHNM
		case GID_IHNM:
			_resource = new Resource_RES(this);
			break;
#endif
#ifdef ENABLE_SAGA2
		case GID_DINO:
		case GID_FTA2:
			_resource = new Resource_HRS(this);
			break;
#endif
	}

	// Detect game and open resource files
	if (!initGame()) {
		GUIErrorMessage("Error loading game resources.");
		return Common::kUnknownError;
	}

	// Initialize engine modules
	// TODO: implement differences for SAGA2
	_sndRes = new SndRes(this);
	_events = new Events(this);

	if (!isSaga2()) {
		_font = new Font(this);
		_sprite = new Sprite(this);
		_script = new SAGA1Script(this);
	} else {
		_script = new SAGA2Script(this);
	}

	_anim = new Anim(this);
	_interface = new Interface(this); // requires script module
	_scene = new Scene(this);
	_actor = new Actor(this);
	_palanim = new PalAnim(this);

	if (getGameId() == GID_ITE) {
		_isoMap = new IsoMap(this);
		_puzzle = new Puzzle(this);
	}

	// System initialization

	_previousTicks = _system->getMillis();

	// Initialize graphics
	_gfx = new Gfx(this, _system, getDisplayInfo().width, getDisplayInfo().height);

	// Graphics driver should be initialized before console
	_console = new Console(this);

	// Graphics should be initialized before music
	_music = new Music(this, _mixer);
	_render = new Render(this, _system);
	if (!_render->initialized()) {
		return Common::kUnknownError;
	}

	// Initialize system specific sound
	_sound = new Sound(this, _mixer);

	if (!isSaga2()) {
		_interface->converseClear();
		_script->setVerb(_script->getVerbType(kVerbWalkTo));
	}

	_music->setVolume(_musicVolume, 1);

	if (!isSaga2()) {
		_gfx->initPalette();
	}

	if (_voiceFilesExist) {
		if (getGameId() == GID_IHNM) {
			if (!ConfMan.hasKey("voices")) {
				_voicesEnabled = true;
				ConfMan.setBool("voices", true);
			} else {
				_voicesEnabled = ConfMan.getBool("voices");
			}
		} else {
			_voicesEnabled = true;
		}
	}

	syncSoundSettings();

	int msec = 0;

	_previousTicks = _system->getMillis();

	if (ConfMan.hasKey("start_scene")) {
		_scene->changeScene(ConfMan.getInt("start_scene"), 0, kTransitionNoFade);
	} else if (ConfMan.hasKey("boot_param")) {
		if (getGameId() == GID_ITE)
			_interface->addToInventory(_actor->objIndexToId(0));	// Magic hat
		_scene->changeScene(ConfMan.getInt("boot_param"), 0, kTransitionNoFade);
	} else if (ConfMan.hasKey("save_slot")) {
		// Init the current chapter to 8 (character selection) for IHNM
		if (getGameId() == GID_IHNM)
			_scene->changeScene(-2, 0, kTransitionFade, 8);

		// First scene sets up palette
		_scene->changeScene(getStartSceneNumber(), 0, kTransitionNoFade);
		_events->handleEvents(0); // Process immediate events

		if (getGameId() == GID_ITE)
			_interface->setMode(kPanelMain);
		else
			_interface->setMode(kPanelChapterSelection);

		char *fileName = calcSaveFileName(ConfMan.getInt("save_slot"));
		load(fileName);
		syncSoundSettings();
	} else {
		_framesEsc = 0;
		_scene->startScene();
	}

	uint32 currentTicks;

	while (!shouldQuit()) {
		_console->onFrame();

		if (_render->getFlags() & RF_RENDERPAUSE) {
			// Freeze time while paused
			_previousTicks = _system->getMillis();
		} else {
			currentTicks = _system->getMillis();
			// Timer has rolled over after 49 days
			if (currentTicks < _previousTicks)
				msec = 0;
			else {
				msec = currentTicks - _previousTicks;
				_previousTicks = currentTicks;
			}
			if (msec > MAX_TIME_DELTA) {
				msec = MAX_TIME_DELTA;
			}

			// Since Puzzle and forced text are actorless, we do them here
			if ((getGameId() == GID_ITE && _puzzle->isActive()) || _actor->isForcedTextShown()) {
				_actor->handleSpeech(msec);
			} else if (!_scene->isInIntro()) {
				if (_interface->getMode() == kPanelMain ||
						_interface->getMode() == kPanelConverse ||
						_interface->getMode() == kPanelCutaway ||
						_interface->getMode() == kPanelNull ||
						_interface->getMode() == kPanelChapterSelection)
					_actor->direct(msec);
			}

			_events->handleEvents(msec);
			_script->executeThreads(msec);
		}
		// Per frame processing
		_render->drawScene();
		_system->delayMillis(10);
	}

	return Common::kNoError;
}
Пример #20
0
int main()
#endif
{
	int quit = 0;
	int timer = 0;

	srand(time(NULL));
	Context context = FIRSTMENU;
	SDL_Event event;
	SDL_Window *window = NULL;
	SDL_Surface *windowSurface = NULL;
	SDL_Renderer *windowRenderer = NULL;
	Menu *menu = NULL;
	Game *game = NULL;
	
	/* Init the window or exit if failure. */
	if(!init(&window))
		return EXIT_FAILURE;

	/* Make the window renderer and the window surface */
	windowRenderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_TARGETTEXTURE);
	if(windowRenderer == NULL)
		printf("%s \n", SDL_GetError());

	windowSurface = SDL_GetWindowSurface(window);

	/* Make all context of the game. */
	menu = initMenu(windowRenderer);
	game = initGame(windowRenderer);

	while(!quit)
	{
		/* event loop. */
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				quit = 1;

			else if(event.type == SDL_KEYDOWN)
			{
				const Uint8* keyPressed = SDL_GetKeyboardState(NULL);
				if(context == GAME)
				{
					/* Handle the translation of the blocks */
					if(event.key.keysym.scancode == SDL_SCANCODE_LEFT || event.key.keysym.scancode == SDL_SCANCODE_RIGHT || event.key.keysym.scancode == SDL_SCANCODE_DOWN)
					{
						if(event.key.keysym.scancode == SDL_SCANCODE_LEFT)
							moveCurrentBlock(game, LEFT);
						if(event.key.keysym.scancode == SDL_SCANCODE_RIGHT)
							moveCurrentBlock(game, RIGHT);
						if(event.key.keysym.scancode == SDL_SCANCODE_DOWN)
							moveCurrentBlock(game, DOWN);
					}

					/* Handle the rotation of the blocks */
					else if(event.key.keysym.sym == SDLK_w || event.key.keysym.sym == SDLK_x)
					{
						/* Check the direction the user want to move */
						Direction direction = NONE;
						if(keyPressed[SDL_SCANCODE_RIGHT])
							direction = RIGHT;
						else if(keyPressed[SDL_SCANCODE_LEFT])
							direction = LEFT;

						if(event.key.keysym.sym == SDLK_w)
						{
							rotateCurrentBlock(game, 1, direction);
						}
						else
							rotateCurrentBlock(game, -1, direction);
					}

					else if(event.key.keysym.scancode == SDL_SCANCODE_SPACE)
					{
						putDownCurrentBlock(game);
					}
				}
			}
		}

		SDL_RenderClear(windowRenderer);

		/* Call the correct context */
		if(context == FIRSTMENU)
			firstMenu(menu, windowRenderer, &context);
		else if(context == QUIT)
			quit = 1;
		else if(context == GAME)
			updateGame(game);

		SDL_RenderPresent(windowRenderer);
		fpsManager(&timer);
	}

	/* Clear the allocated memory */
	clearMenu(menu);
	clearGame(game);
	SDL_DestroyRenderer(windowRenderer);
	SDL_FreeSurface(windowSurface);
	SDL_DestroyWindow(window);
	clear();

	return 0;
}
Пример #21
0
int gameScreen(int lv0, int sc0){
	int i, inp;
	
	if( lv0 >= MAX_LEVEL || lv0 < 0 ){
		fprintf(stderr, "レベル指定が不正です\n");
		exit(1);
	}
	initGame(lv0, sc0);
	gdscr_initscr();
	
	gdscr_refresh();
	drawString(6, 40, "Press space key to start", FORMAT_CENTER);
	while( 1 ){
		inp = getch();
		if( inp == ' ' )break;
		if( inp == 'q' )break;
	}
	
	timeout(0);
	setLevel(LEVEL);
	while( !gbump_check() && inp != 'q' ){
	
		/*sleep処理*/
		usleep(DELAY);
	
		/*入力受付処理*/
		inp = getch();
		if( inp == ' ' ) gjump_flagSet();
		
		/*レベルアップ処理*/
		if( checkLevelUp() ){
			LEVEL++;
			setLevel(LEVEL);
		}
		
		/*画面更新処理*/
		gfield_shiftl();
		gobstacle_put(&FIELD[FIELD_WIDTH - 1]);
		gjump_jumpPlayer();
		SCORE++;
		gdscr_refresh();
	}
	
	/*終了処理*/
	setHighScore(SCORE);
	SCORE_HIGH = getHighScore();
	timeout(-1);
	freeMatrix(PLAYER_MATRIX);
	PLAYER_MATRIX = PLAYER_MATRIX_LOSE;
	
	/*終了画面描画*/
	gdscr_draw();
	drawString(5, 5, "GAME OVER.", FORMAT_LEFT);
	printCommand(22, 76, FORMAT_RIGHT, COMMAND_LIST, COMMAND_NUM);
	refresh();
	
	/*コマンド取得*/
	inp = getCommand(COMMAND_LIST, COMMAND_NUM);
	
	/*開放*/
	freeMatrix(PLAYER_MATRIX_LOSE);
	gobstacle_memFree();
	gdscr_endwin();
	
	/*メッセージ返却*/
	switch( inp ){
		case 'r':
			return COMMAND_RETRY;
		case 'm':
			return COMMAND_MENU;
		case 'q':
			return COMMAND_QUIT;
		default:
			return 9999;
	}
}
Пример #22
0
int CALLBACK WinMain(
					HINSTANCE hInstance1,
					HINSTANCE hPrevInstance,
					LPSTR     lpCmdLine,
					int       nCmdShow
					)
{
	windowWidth = 800;
	windowHeight = 600;
	camZoom = 2;
	hInstance = hInstance1;
	LPCTSTR className = "GraphicsGame";
	WNDCLASS wc = {};
	wc.style = CS_OWNDC|CS_VREDRAW|CS_HREDRAW;
	wc.lpfnWndProc = (WNDPROC)WindowProc;
	wc.hInstance = hInstance;
	wc.lpszClassName = className;
	wc.hCursor = NULL;

	if(!RegisterClass(&wc))
	{
		killWindow(className);
		MessageBox(NULL, "Couldnt Register Class", "Error", MB_OK);
		return 1;
	}

	int windowStatus = createGLWindow(hInstance, className);
	if(!windowStatus)
	{
		return 1;
	}

	

	double dx = 0;
	double dy = 0;
	double maxSpeed = 5;
	double accel = 0.1f;
	MSG message;
	game = (Game*)calloc(1, sizeof(Game));
	initGL();
	initGame(game);
	int counter = 0;
	LARGE_INTEGER cps;
	LARGE_INTEGER curCount;
	LARGE_INTEGER prevCount;
	LONGLONG countDifference;

	QueryPerformanceFrequency(&cps);
	double secsPassed = 0;
	QueryPerformanceCounter(&curCount);
	float pan = 0.2;
	float topPan = 1;
	float lowPan = 0.2;
	while(!game->done)
	{
		prevCount = curCount;
		QueryPerformanceCounter(&curCount);
		countDifference = curCount.QuadPart - prevCount.QuadPart;
		secsPassed = (long double)countDifference / (long double)cps.QuadPart;
		while(PeekMessage(&message, hWindow, 0, 0, PM_REMOVE))
		{
			if(message.message == WM_QUIT)
			{
				game->done = true;
			}
			TranslateMessage(&message);
			DispatchMessage(&message);
		}
		dx = 0;
		dy = 0;
		if(game->keys[VK_SHIFT])
		{
			pan = topPan;
		}
		else
		{
			pan = lowPan;
		}
		if(game->keys['W'])
		{
			camY+=pan;
		}
		if(game->keys['A'])
		{
			camX-=pan;
		}
		if(game->keys['S'])
		{
			camY-=pan;
		}
		if(game->keys['D'])
		{
			camX+=pan;
		}
		
		if(game->keys['Q'])
		{
			camZoom += 0.01;
			if(camZoom > 6) camZoom = 6;
			resize(windowWidth, windowHeight);
		}
		if(game->keys['E'])
		{
			camZoom -= 0.01;
			if(camZoom < 1) camZoom = 1;
			resize(windowWidth, windowHeight);
		}
		if(game->keys[VK_SPACE])
		{
			saveFile(game);
			
		}
		
		
		



		updateGame(game, dx, dy, secsPassed);
		
		drawScene(game);
		SwapBuffers(hDeviceContext);

	}
	free(game);
	killWindow(className);
	return 0;
}
Пример #23
0
/*******************************************************************************
* function playBattleship (void)
*
* This is the main function for the game, responsible for managing all
* other functions necessary for the game to work
*/
void playBattleship ( int numMissiles )
{
  srand( time( NULL ) ); // Randomizing radomic randomizer

  char board [391];
  char mask  [391];

  char previousMove[1024] = "-"; // Previous move (miss/hit on [coord])
  char nextMove[3]; // Coordinates typed by the user
  int  nextMoveCoordinates; // Numerical coordinates

  int validCoordinates = 0; // Controls if the coordinate is valid or not

  int missilesFired = 0;
  int missilesRemaining = numMissiles;
  int score = 0;

  // Filling the board with water and loading the ships
  // You can customize this with ships of different designs
  initGame ( board, mask );
  loadShips( board, "XXXXXXX" );
  loadShips( board, "XXXXXX" );
  loadShips( board, "XXXXX" );
  loadShips( board, "XXXX" );

  int c = 0;

  // Printing the board again for every move while the player still has
  // missiles and hasn't destroyed all the ships
  do
  {
    for ( c = 0; c < 80; c++ ) printf("\n"); // Clearing the screen

    // Drawing the board
    //drawGame (board, missilesFired, missilesRemaining, score, previousMove); // For debug only
    drawGame (mask, missilesFired, missilesRemaining, score, previousMove);

    // Asking for valid coordinates
    printf("\nEnter the target coordinates : ");
    do
    {
      validCoordinates = 0;

      scanf( "%s", nextMove );

      // Replacing non-valid coordinates with "?"
      if ( (nextMove[0] < '0' || nextMove[0] > '9') &&
           (nextMove[0] < 'A' || nextMove[0] > 'F') &&
           (nextMove[0] < 'a' || nextMove[0] > 'f') ) nextMove[0] = '?';
      if ( (nextMove[1] < 'A' || nextMove[1] > 'Z') &&
           (nextMove[1] < 'a' || nextMove[1] > 'z') ) nextMove[1] = '?';

      // Checking if the coordinates are valid
      if ( (nextMoveCoordinates = checkMove (nextMove)) == -1 )
      {
        printf("Sorry... '%c%c' is not a valid coordinate... Try again: ",
          nextMove[0], nextMove[1]);
      }
      else validCoordinates = 1;

      while ( getchar() != '\n' ); // Cleaning the buffer
    }
    while ( validCoordinates == 0 );

    // Coordinates received, updating the board
    updateData (board, mask, &missilesFired, &missilesRemaining, &score,
      previousMove, nextMove);
  }
  while ( missilesRemaining > 0 && score < 110 );

  for ( c = 0; c < 80; c++ ) printf("\n"); // Clearing the screen

  if ( score < 110 )
  {
    drawGame (board, missilesFired, missilesRemaining, score, previousMove);
    printf("\n\n+---------------<  Sorry, you lost the war ...  >---------------+\n\n");
  }
  else
  {
    drawGame (mask, missilesFired, missilesRemaining, score, previousMove);

    printf("\n\n+----------------<          HOORAY !!          >----------------+\n");
    printf("+-----------<   You sunk all the ships, YOU WON !   >-----------+\n\n");
  }

}
Пример #24
0
void init(){
	initWindow();
	initGame(GAME_SPEED_START);
	initTimer();
}
Пример #25
0
Common::Error SciEngine::run() {
	g_eventRec.registerRandomSource(_rng, "sci");

	// Assign default values to the config manager, in case settings are missing
	ConfMan.registerDefault("sci_originalsaveload", "false");
	ConfMan.registerDefault("native_fb01", "false");
	ConfMan.registerDefault("windows_cursors", "false");	// Windows cursors for KQ6 Windows

	_resMan = new ResourceManager();
	assert(_resMan);
	_resMan->addAppropriateSources();
	_resMan->init();

	// TODO: Add error handling. Check return values of addAppropriateSources
	// and init. We first have to *add* sensible return values, though ;).
/*
	if (!_resMan) {
		warning("No resources found, aborting");
		return Common::kNoGameDataFoundError;
	}
*/

	// Reset, so that error()s before SoundCommandParser is initialized wont cause a crash
	_soundCmd = NULL;

	// Add the after market GM patches for the specified game, if they exist
	_resMan->addNewGMPatch(_gameId);
	_gameObjectAddress = _resMan->findGameObject();
	_gameSuperClassAddress = NULL_REG;

	SegManager *segMan = new SegManager(_resMan);

	// Initialize the game screen
	_gfxScreen = new GfxScreen(_resMan);
	_gfxScreen->debugUnditherSetState(ConfMan.getBool("disable_dithering"));

	// Create debugger console. It requires GFX to be initialized
	_console = new Console(this);
	_kernel = new Kernel(_resMan, segMan);

	_features = new GameFeatures(segMan, _kernel);
	// Only SCI0, SCI01 and SCI1 EGA games used a parser
	_vocabulary = (getSciVersion() <= SCI_VERSION_1_EGA) ? new Vocabulary(_resMan, false) : NULL;
	// Also, XMAS1990 apparently had a parser too. Refer to http://forums.scummvm.org/viewtopic.php?t=9135
	if (getGameId() == GID_CHRISTMAS1990)
		_vocabulary = new Vocabulary(_resMan, false);
	_audio = new AudioPlayer(_resMan);
	_gamestate = new EngineState(segMan);
	_eventMan = new EventManager(_resMan->detectFontExtended());

	// The game needs to be initialized before the graphics system is initialized, as
	// the graphics code checks parts of the seg manager upon initialization (e.g. for
	// the presence of the fastCast object)
	if (!initGame()) { /* Initialize */
		warning("Game initialization failed: Aborting...");
		// TODO: Add an "init failed" error?
		return Common::kUnknownError;
	}

	// we try to find the super class address of the game object, we can't do that earlier
	const Object *gameObject = segMan->getObject(_gameObjectAddress);
	if (!gameObject) {
		warning("Could not get game object, aborting...");
		return Common::kUnknownError;
	}
	_gameSuperClassAddress = gameObject->getSuperClassSelector();

	script_adjust_opcode_formats();

	// Must be called after game_init(), as they use _features
	_kernel->loadKernelNames(_features);
	_soundCmd = new SoundCommandParser(_resMan, segMan, _kernel, _audio, _features->detectDoSoundType());

	syncSoundSettings();
	syncIngameAudioOptions();

	// Initialize all graphics related subsystems
	initGraphics();

	debug("Emulating SCI version %s\n", getSciVersionDesc(getSciVersion()));

	// Patch in our save/restore code, so that dialogs are replaced
	patchGameSaveRestore();
	setLauncherLanguage();

	// Check whether loading a savestate was requested
	int directSaveSlotLoading = ConfMan.getInt("save_slot");
	if (directSaveSlotLoading >= 0) {
		// call GameObject::play (like normally)
		initStackBaseWithSelector(SELECTOR(play));
		// We set this, so that the game automatically quit right after init
		_gamestate->variables[VAR_GLOBAL][4] = TRUE_REG;

		_gamestate->_executionStackPosChanged = false;
		run_vm(_gamestate);

		// As soon as we get control again, actually restore the game
		reg_t restoreArgv[2] = { NULL_REG, make_reg(0, directSaveSlotLoading) };	// special call (argv[0] is NULL)
		kRestoreGame(_gamestate, 2, restoreArgv);

		// this indirectly calls GameObject::init, which will setup menu, text font/color codes etc.
		//  without this games would be pretty badly broken
	}

	// Show any special warnings for buggy scripts with severe game bugs, 
	// which have been patched by Sierra
	if (getGameId() == GID_LONGBOW) {
		// Longbow 1.0 has a buggy script which prevents the game
		// from progressing during the Green Man riddle sequence.
		// A patch for this buggy script has been released by Sierra,
		// and is necessary to complete the game without issues.
		// The patched script is included in Longbow 1.1.
		// Refer to bug #3036609.
		Resource *buggyScript = _resMan->findResource(ResourceId(kResourceTypeScript, 180), 0);

		if (buggyScript && (buggyScript->size == 12354 || buggyScript->size == 12362)) {
			showScummVMDialog("A known buggy game script has been detected, which could "
			                  "prevent you from progressing later on in the game, during "
			                  "the sequence with the Green Man's riddles. Please, apply "
			                  "the latest patch for this game by Sierra to avoid possible "
			                  "problems");
		}
	}

	// Show a warning if the user has selected a General MIDI device, no GM patch exists
	// (i.e. patch 4) and the game is one of the known 8 SCI1 games that Sierra has provided
	// after market patches for in their "General MIDI Utility".
	if (_soundCmd->getMusicType() == MT_GM && !ConfMan.getBool("native_mt32")) {
		if (!_resMan->findResource(ResourceId(kResourceTypePatch, 4), 0)) {
			switch (getGameId()) {
			case GID_ECOQUEST:
			case GID_HOYLE3:
			case GID_LSL1:
			case GID_LSL5:
			case GID_LONGBOW:
			case GID_SQ1:
			case GID_SQ4:
			case GID_FAIRYTALES:
				showScummVMDialog("You have selected General MIDI as a sound device. Sierra "
				                  "has provided after-market support for General MIDI for this "
				                  "game in their \"General MIDI Utility\". Please, apply this "
				                  "patch in order to enjoy MIDI music with this game. Once you "
				                  "have obtained it, you can unpack all of the included *.PAT "
				                  "files in your ScummVM extras folder and ScummVM will add the "
				                  "appropriate patch automatically. Alternatively, you can follow "
				                  "the instructions in the READ.ME file included in the patch and "
				                  "rename the associated *.PAT file to 4.PAT and place it in the "
				                  "game folder. Without this patch, General MIDI music for this "
				                  "game will sound badly distorted.");
				break;
			default:
				break;
			}
		}
	}

	if (gameHasFanMadePatch()) {
		showScummVMDialog("Your game is patched with a fan made script patch. Such patches have "
		                  "been reported to cause issues, as they modify game scripts extensively. "
		                  "The issues that these patches fix do not occur in ScummVM, so you are "
		                  "advised to remove this patch from your game folder in order to avoid "
		                  "having unexpected errors and/or issues later on.");
	}

	runGame();

	ConfMan.flushToDisk();

	return Common::kNoError;
}
Пример #26
0
void Game::run() {
    initGame();
    registerCallbacks();
    glutMainLoop();
}
Пример #27
0
 Uno(int nbPlayers, bool ia){
   int nbDiscardPile=1;
   int nbDeck=1;
   initGame("Uno", nbPlayers, nbDeck, nbDiscardPile, ia);
 }
Пример #28
0
void MainWindow::on_player6button_clicked()
{
    ui->player1_char->setVisible(true);
    ui->player1_dollar->setVisible(true);
    ui->player1_label->setVisible(true);
    ui->player1_sign->setVisible(true);
    ui->label->setVisible(true);

    ui->player2_char->setVisible(true);
    ui->player2_dollar->setVisible(true);
    ui->player2_label->setVisible(true);
    ui->player2_sign->setVisible(true);
    ui->label_2->setVisible(true);

    ui->player3_char->setVisible(true);
    ui->player3_dollar->setVisible(true);
    ui->player3_label->setVisible(true);
    ui->player3_sign->setVisible(true);
    ui->label_3->setVisible(true);

    ui->player4_char->setVisible(true);
    ui->player4_dollar->setVisible(true);
    ui->player4_label->setVisible(true);
    ui->player4_sign->setVisible(true);
    ui->label_4->setVisible(true);

    ui->player5_char->setVisible(true);
    ui->player5_dollar->setVisible(true);
    ui->player5_label->setVisible(true);
    ui->player5_sign->setVisible(true);
    ui->label_5->setVisible(true);

    ui->player6_char->setVisible(true);
    ui->player6_dollar->setVisible(true);
    ui->player6_label->setVisible(true);
    ui->player6_sign->setVisible(true);
    ui->label_6->setVisible(true);

    ui->player1_char->move(550, 540);
    ui->player2_char->move(530, 530);
    ui->player3_char->move(550, 580);
    ui->player4_char->move(530, 560);
    ui->player5_char->move(570, 530);
    ui->player6_char->move(570, 560);

    ui->player1_dollar->setText("1500");
    ui->player2_dollar->setText("1500");
    ui->player3_dollar->setText("1500");
    ui->player4_dollar->setText("1500");
    ui->player5_dollar->setText("1500");
    ui->player6_dollar->setText("1500");

    ui->yesButton->setVisible(false);
    ui->noButton->setVisible(false);
    ui->boardspace_label->setVisible(false);
    ui->boardspace_price_label->setVisible(false);

    ui->dice1_label->setVisible(true);
    ui->dice2_label->setVisible(true);
    ui->label_8->setVisible(true);
    ui->diceButton->setVisible(true);

    ui->activeplayer_dollar->setVisible(true);
    ui->activeplayer_label->setVisible(true);
    ui->activeplayer_sign->setVisible(true);
    ui->activeplayer_label->setText("Player 1");
    ui->activeplayer_dollar->setText("1500");

    initGame(6);
}
Пример #29
0
void DkPongPort::moveBall() {


	QPoint newCenter = ball.center() + ballDir.getQPointF().toPoint();
	
	// collision detection
	if (ball.top() <= field.top() && ballDir.y < 0 || ball.bottom() >= field.bottom() && ballDir.y > 0) {
		ballDir.rotate(ballDir.angle()*2);
		qDebug() << "collision...";
	}
	// collision detection
	if (ball.left() <= field.left() || ball.right() >= field.right()) {
		//ballDir.rotate(-ballDir.angle()*2);
		initGame();
		qDebug() << "collision...";
	}

	double maxAngle = CV_PI*0.45;

	// player collition
	if ((player1.contains(ball.topLeft()) || player1.contains(ball.bottomLeft())) && ballDir.x < 0) {
		
		ballDir.rotate(-ballDir.angle()*2);
		double mod = (player1Pos != INT_MAX) ? (player1.center().y() - player1Pos)/(float)field.height() : 0;
		ballDir.y += mod*unit;

		//qDebug() << "ballDir: " << ballDir.angle();

		//if (ballDir.angle() < maxAngle) {

		//	qDebug() << "correcting angle: " << ballDir.angle();
		//	ballDir.rotate(-DkMath::normAngleRad(ballDir.angle())+maxAngle);
		//	qDebug() << "angle corrected: " << ballDir.angle();


		//}
		//else if (ballDir.angle() > CV_PI-maxAngle) {
		//	qDebug() << "correcting angle: " << ballDir.angle();
		//	ballDir.rotate(DkMath::normAngleRad(ballDir.angle())-(CV_PI-maxAngle));
		//	qDebug() << "angle corrected: " << ballDir.angle();
		//}
		
	}
	if ((player2.contains(ball.topRight()) || player2.contains(ball.bottomRight())) && ballDir.x > 0) {
		
		ballDir.rotate(-ballDir.angle()*2);
		
		double mod = (player2Pos != INT_MAX) ? (player2.center().y() - player2Pos)/(float)field.height() : 0;
		ballDir.y += mod*unit;
	}


	//if (abs(ballDir.x) < 1)
	//	ballDir.x = (ballDir.x < 0) ? -unit*0.25 : unit*0.25;

	double normAngle = DkMath::normAngleRad(ballDir.angle(), 0, CV_PI*0.5);
	
	//if (normAngle > maxAngle) {


	//	ballDir.rotate(ballDir.angle() - (normAngle-maxAngle));
	//	qDebug() << "I did correct the angle...";
	//}
		

	if (ballDir.norm() > maxBallSpeed) {
		ballDir.normalize();
		ballDir *= maxBallSpeed;
	}
	else if (ballDir.norm() < minBallSpeed) {
		ballDir.normalize();
		ballDir *= minBallSpeed;
	}

	//qDebug() << ballDir.angle();

	ball.moveCenter(ball.center() + ballDir.getQPointF().toPoint());

}
Пример #30
0
void Scene::onKeyPress(unsigned char key, int keyX, int keyY) {
    switch(key) {
        case '1':
            showAxis = showAxis == 0?1:0;
        break;
        case '2':
            game = game == 0?1:0;
            if (game) {
                initGame();
            }
        break;
        case '3':
            lighting = lighting == 0?1:0;
            printf("Lighting: %d\n", lighting);
            if (lighting) {
                glEnable(GL_LIGHTING);
            } else {
                glDisable(GL_LIGHTING);
            }
        break;
        case '4':
            skeleton = skeleton == 0?1:0;
        break;
        case '5':
            materialsMode = materialsMode == 0?1:0;
        break;
        case '6':
            smoofShading = smoofShading == 0?1:0;
            if (smoofShading) {
                glShadeModel(GL_SMOOTH);
            } else {
                glShadeModel(GL_FLAT);
            }
        break;
        case '7':
            modelsMode = modelsMode == 0?1:0;
        break;
        case 'q':
            r[0][1] = r[0][1] - angles[0];
        break;
        case 'w':
            r[0][1] += angles[0];
        break;
        case 'a':
            r[1][1] -= angles[1];
        break;
        case 's':
            r[1][1] += angles[1];
        break;
        case 'z':
            r[2][1] -= angles[2];
        break;
        case 'x':
            r[2][1] += angles[2];
        break;
        case KEY_ESCAPE:
            exit(0);
        break;
        case 'e':
            myX-=1;
        break;
        case 'r':
            myX+=1;
        break;
        case 'd':
            myY-=1;
        break;
        case 'f':
            myY+=1;
        break;
        case 'c':
            myZ-=1;
        break;
        case 'v':
            myZ+=1;
        break;
    }
    glutPostRedisplay();
}