Example #1
0
VirtScreen::VirtScreen(World * const world_, Player * const player_) :
		w(world_),
		player(player_)
{
	connect(w, SIGNAL(Notify(const QString &)),
		this, SLOT(Notify(const QString &)));
	connect(player, SIGNAL(Notify(const QString &)),
		this, SLOT(Notify(const QString &)));

	connect(w, SIGNAL(GetString(QString &)),
		this, SLOT(PassString(QString &)),
		Qt::DirectConnection);
	connect(player, SIGNAL(GetString(QString &)),
		this, SLOT(PassString(QString &)),
		Qt::DirectConnection);

	connect(player, SIGNAL(Updated()),
		this, SLOT(UpdatePlayer()),
		Qt::DirectConnection);
	connect(w, SIGNAL(ReConnect()),
		this, SLOT(ConnectWorld()),
		Qt::DirectConnection);
	connect(w, SIGNAL(UpdatedAll()),
		this, SLOT(UpdateAll()),
		Qt::DirectConnection);
	connect(w, SIGNAL(Moved(const int)),
		this, SLOT(Move(const int)),
		Qt::DirectConnection);
	ConnectWorld();
	connect(w, SIGNAL(UpdatesEnded()),
		this, SLOT(UpdatesEnd()),
		Qt::DirectConnection);
}
Example #2
0
void CoreApp::Update() {
    switch (state) {
        case MENU:
            
            break;
            
        case GAME:
            UpdatePlayer(player);
            enmTickCount += deltaTime;
            if( enmTickCount > enmTickWait ) {
                enmTickCount -= enmTickWait;
                
                for( Entity& thisEnemy : enemies ) {
                    UpdateEnemy(thisEnemy);
                }
                enmMoveDown = false;
                if( enmHitWall ) {
                    enmMoveDown = true;
                    enmCurrentDirection *= -1;
                    enmHitWall = false;
                }
            }
            UpdatePlayerBullet(playerBullet);
            UpdateEnemyBullet(enemyBullet);
            break;
            
        case GAMEOVER:
            
            break;
    }
    
    
}
Example #3
0
int main(int argc, char **argv)
{
    StreamPlayer *player;
    int i;

    /* Print out usage if no file was specified */
    if(argc < 2)
    {
        fprintf(stderr, "Usage: %s <filenames...>\n", argv[0]);
        return 1;
    }

    if(InitAL() != 0)
        return 1;

    if(alIsExtensionPresent("AL_SOFT_buffer_samples"))
    {
        printf("AL_SOFT_buffer_samples supported!\n");
        alBufferSamplesSOFT = alGetProcAddress("alBufferSamplesSOFT");
        alIsBufferFormatSupportedSOFT = alGetProcAddress("alIsBufferFormatSupportedSOFT");
    }
    else
        printf("AL_SOFT_buffer_samples not supported\n");

    player = NewPlayer();

    /* Play each file listed on the command line */
    for(i = 1;i < argc;i++)
    {
        if(!OpenPlayerFile(player, argv[i]))
            continue;

        printf("Playing %s (%s, %s, %dhz)\n", argv[i],
               TypeName(player->type), ChannelsName(player->channels),
               player->rate);
        fflush(stdout);

        if(!StartPlayer(player))
        {
            ClosePlayerFile(player);
            continue;
        }

        while(UpdatePlayer(player))
            Sleep(10);

        /* All done with this file. Close it and go to the next */
        ClosePlayerFile(player);
    }
    printf("Done.\n");

    /* All files done. Delete the player, and close OpenAL */
    DeletePlayer(player);
    player = NULL;

    CloseAL();

    return 0;
}
Example #4
0
/* Initializes the player. */
static void InitPlayer()
{
    player.world_x = getrandom() % WORLD_WIDTH;
    player.world_y = getrandom() % WORLD_HEIGHT;
    player.accel = 0;
    player.velocity = 0;
    player.angle = 0;
    UpdatePlayer(&player);
}
Example #5
0
void CLimitDungeonManager::Process()
{
	if(IsReady())
	{
        Run();
		PostponeSchedule();
		return;
	}

	RefreshScript();
	UpdatePlayer();
}
Example #6
0
/* Initializes the given player. */
static void InitPlayer(player_p p)
{
    p->world_x = getrandom() % WORLD_WIDTH;
    p->world_y = getrandom() % WORLD_HEIGHT;
    p->accel = 0;
    p->velocity = 0;
    p->angle = 0;
    p->charge = 0;
    p->firing = 0;
    p->shields = 100;
    UpdatePlayer(p);
}
void
PlayerDlg::OnApply(AWEvent* event)
{
	Player* player = Player::GetCurrentPlayer();
	if (player) {
		UpdatePlayer();
		Player::Save();
	}

	FlushKeys();
	manager->ShowMenuDlg();
}
void CPlayerLoop::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == m_FrameTimer.timerId()) //если сработал таймер кадров
    {

        if(!m_Log.is_open())
        {
            std::cerr << "Ошибка открытия файла журнала!!!" << std::endl << std::flush;
            m_FrameTimer.stop();
            return;
        }
        //читаем очередной блок из файла журнала
        //создаем объект - парсер файла жкрнала
        CLogParser logParser;

        //Читаем блок из входного потока, пока не встретится пустая строка, признак конца файла или ошибка в данных

        if(!ReadBlockFromStream(m_Log, &logParser) && !m_Log.eof())
        {
            if(logParser.IsError())
            {
                std::cerr << "Ошибка в CLogParser: " << logParser.GetErrorMessage().c_str() << std::endl << std::flush;
            }
            else
            {
                std::cerr << "Ошибка чтения файла!!!" << std::endl << std::flush;
            }

            m_FrameTimer.stop();
            return;
        }
        else
        {
            // отладочный вывод на консоль прочитанных из файла данных
            // ShowMapInText(logParser.GetFrame());

            if (m_Log.eof())
            {
                std::cerr << "Файл успешно прочитан!!!\n";
                m_FrameTimer.stop();
                return;
            }

            UpdatePlayer(logParser);
            ShowFrame();
        }
    }
}
// 更新
void USsPlayerComponent::TickComponent(float DeltaTime, enum ELevelTick /*TickType*/, FActorComponentTickFunction* /*ThisTickFunction*/)
{
#if WITH_EDITOR
	// SsProjectがReimportされたら、ActorComponentを再登録させる
	if(Player.GetSsProject().IsStale())
	{
		GetOwner()->ReregisterAllComponents();
		return;
	}
#endif

	if(bAutoUpdate)
	{
		UpdatePlayer(DeltaTime);
	}
}
Example #10
0
// Gameplay Screen Update logic
void UpdateGameplayScreen(void)
{
    
    if (IsKeyPressed('P')) 
    {
        pause = !pause;
        if (!pause) ResumeMusicStream();
        else PauseMusicStream();
    }
    
    if (!pause)
    {     
        if (!startGame && IsKeyPressed(KEY_SPACE)) 
        {
            startGame = TRUE;
            ResumeMusicStream();
        }
        // TODO: Update GAMEPLAY screen variables here!
        if (startGame)
        {
            UpdateMainCamera(&mainCamera);
            
            UpdateTrianglesPosition(mainCamera.position);
            UpdateTrianglesState();
            UpdatePlatformsPosition(mainCamera.position);
            UpdatePlatformsState();
            
            UpdatePlayer(&player);
        }
    }
    // Press enter to change to ENDING screen
    
    /*
    if (IsKeyPressed(KEY_ENTER) || !player.isAlive || mainCamera.position.x/CELL_SIZE>GRID_WIDTH+10)
    {
        finishScreen = 1;
    }
    */
    
    // WIN / LOSE Conditions
    if (!player.isAlive) GameplayEnd(1); // If player dies, reset gameplay screen
    else if (mainCamera.position.x/CELL_SIZE>GRID_WIDTH+20) GameplayEnd(2); // If player reaches the end level (+20 cells) game ends.   
    
    // MusicIsPlaying
    UpdateMusicStream();
}
void
PlayerDlg::OnSelectPlayer(AWEvent* event)
{
	if (!lst_roster) return;

	UpdatePlayer();

	int index = lst_roster->GetSelection();

	List<Player>& roster = Player::GetRoster();
	if (index >= 0 && index < roster.size()) {
		Player::SelectPlayer(roster.at(index));
	}

	ShowPlayer();

	apply->SetEnabled(roster.size() > 0);
}
Example #12
0
    void BacteroidsState::Update(const GameTime &gameTime)
    {
        static float spawn_rate = 0.1f;
        static float num_spawn = 1.0f;
        spawn_rate = std::log(10.0f + gameTime.GetTotalSeconds() * 0.1f) * 0.5f;
        num_spawn += spawn_rate * gameTime.GetDeltaSeconds();
        while (num_spawn >= 1.0f)
        {
            SpawnBacter();
            num_spawn -= 1.0f;
        }

        m_soundPlayer.UpdateTime(gameTime);

        UpdatePlayer(gameTime);

        DoCollisions();

        for (size_t_32 i = 0; i < m_objects.Size(); i++)
        {
            m_objects[i]->Update(gameTime, PLAY_AREA);
            // TODO: Spontaneous splitting is very much a hack I says. Fix pls. Solution CES?
            if (m_objects[i]->GetType() == Bacter::TYPE)
            {
                Bacter *bacter = (Bacter*)m_objects[i];
                if (bacter->WantsToSplit() && m_objects.CanObtainBacter())
                    SplitBacter(bacter);
            }
        }

        for (size_t_32 i = 0; i < m_objects.Size(); )
        {
            if (!m_objects[i]->IsAlive())
            {
                m_objects.Remove(i);
                continue;
            }
            i++;
        }

        m_damageFade.Update(gameTime.GetDeltaSeconds());
    }
Example #13
0
void GameManager::PlayGame() 
{
	while (!doExit) //Main Game Loop
	{	
		RunGameOverCheck();

		UpdateGameTimers();

		UpdatePlayerInput();

		UpdateEnemySpawner();

		UpdateEnemies();

		UpdatePlayer();

		UpdateBullets();

		RunCollisionCheck();

		Render(); //Render everyting
	}
	QuitGame();
}
Example #14
0
VirtScreen::VirtScreen(World * const world_, Player * const player_) :
        w(world_),
        player(player_),
        settings(home_path + "freg.ini", QSettings::IniFormat),
        previousCommand(settings.value("last_command", "moo").toString())
{
    connect(     w, SIGNAL(Notify(QString)), SLOT(Notify(QString)),
        Qt::DirectConnection);
    connect(player, SIGNAL(Notify(QString)), SLOT(Notify(QString)),
        Qt::DirectConnection);
    connect(player, SIGNAL(ShowFile(QString)), SLOT(DisplayFile(QString)));
    connect(player, SIGNAL(GetFocus(int *, int *, int *)),
        SLOT(ActionXyz(int *, int *, int *)), Qt::DirectConnection);

    connect(     w, SIGNAL(GetString(QString &)),
        SLOT(PassString(QString &)), Qt::DirectConnection);
    connect(player, SIGNAL(GetString(QString &)),
        SLOT(PassString(QString &)), Qt::DirectConnection);

    connect(player, SIGNAL(Updated()), SLOT(UpdatePlayer()),
        Qt::DirectConnection);
    connect(w, SIGNAL(UpdatedAll()), SLOT(UpdateAll()),
        Qt::DirectConnection);
    connect(w, SIGNAL(Moved(int)), SLOT(Move(int)),
        Qt::DirectConnection);
    connect(w, SIGNAL(Updated(int, int, int)), SLOT(Update(int, int, int)),
        Qt::DirectConnection);
    connect(w, SIGNAL(UpdatedAround(int, int, int, int)),
        SLOT(UpdateAround(int, int, int, int)),
        Qt::DirectConnection);
    connect(w, SIGNAL(UpdatesEnded()), SLOT(UpdatesEnd()),
        Qt::DirectConnection);

    connect(player, SIGNAL(Destroyed()), SLOT(DeathScreen()),
        Qt::DirectConnection );
}
Example #15
0
// Gameplay Screen Update logic
void UpdateLivingroomScreen(void)
{
    if (player.key)
    {       
        // Door: left
        if ((CheckCollisionPointRec(GetMousePosition(), doorLeft.bound)) || 
            (CheckCollisionRecs(player.bounds, doorLeft.bound))) doorLeft.selected = true; 
        else doorLeft.selected = false;
        
        if ((doorLeft.selected) && (CheckCollisionRecs(player.bounds, doorLeft.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorLeft.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorLeft.locked)
                {
                    doorLeft.frameRec.y = 0;
                    doorLeft.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 1;
            }
        }
        
        // Door: center
        if ((CheckCollisionPointRec(GetMousePosition(), doorCenter.bound)) || 
            (CheckCollisionRecs(player.bounds, doorCenter.bound))) doorCenter.selected = true; 
        else doorCenter.selected = false;
        
        if ((doorCenter.selected) && (CheckCollisionRecs(player.bounds, doorCenter.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorCenter.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorCenter.locked)
                {
                    doorCenter.frameRec.y = 0;
                    doorCenter.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 2;
            }
        }
    }
        
    if (msgState > 2)
    {
        UpdatePlayer();
	
		// Monsters logic
        UpdateMonster(&candle);
        UpdateMonster(&picture);
        UpdateMonster(&phone);
    }
	
    // Check player hover monsters to interact
    if (((CheckCollisionRecs(player.bounds, candle.bounds)) && !candle.active) ||
        ((CheckCollisionRecs(player.bounds, picture.bounds)) && !picture.active) ||
        ((CheckCollisionRecs(player.bounds, phone.bounds)) && !phone.active)) monsterHover = true;
    else monsterHover = false;
    
    // Monters logic: candle
    if ((CheckCollisionRecs(player.bounds, candle.bounds)) && !candle.active)
    {
        candle.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), candle.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 1;
        }
    }
    else candle.selected = false;
    
    // Monters logic: picture
    if ((CheckCollisionRecs(player.bounds, picture.bounds)) && !picture.active)
    {
        picture.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), picture.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 2;
        }
    }
    else picture.selected = false;
    
    // Monters logic: phone
    if ((CheckCollisionRecs(player.bounds, phone.bounds)) && !phone.active)
    {
        phone.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), phone.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 3;
        }
    }
    else phone.selected = false;
    
    if (searching)
    {
        framesCounter++;
        
        if (framesCounter > 180)
        {
            if (monsterCheck == 1)
            {
                if (candle.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                candle.active = true;
                candle.selected = false;
            }
            else if (monsterCheck == 2)
            {
                if (picture.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                picture.active = true;
                picture.selected = false;
            }
            else if (monsterCheck == 3)
            {
                if (phone.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                phone.active = true;
                phone.selected = false;
            }
  
            searching = false;
            framesCounter = 0;
        }
    }
    
    // Text animation
    framesCounter++;
    
    if ((framesCounter%2) == 0) lettersCounter++;

    if (msgState == 0)
    {
        if (lettersCounter <= (int)strlen(message)) strncpy(msgBuffer, message, lettersCounter);
        else
        {
            for (int i = 0; i < (int)strlen(msgBuffer); i++) msgBuffer[i] = '\0';

            lettersCounter = 0;
            msgState = 1;
        }
        
        if (IsKeyPressed(KEY_ENTER)) msgState = 1;
    }
    else if (msgState == 1)
    {
        msgCounter++;
        
        if ((IsKeyPressed(KEY_ENTER)) || (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)))
        {
            msgState = 2;
            msgCounter = 0;
        }
    }
    else if (msgState == 2)
    {
        msgCounter++;
        
        if (msgCounter > 180) msgState = 3;
    }
    else msgCounter++;
}
Example #16
0
static void PlayGame()
{
    Uint8 *keystate;
    int quit = 0;
    int turn;
    int prev_ticks = 0, cur_ticks = 0; /* for keeping track of timing */
    int awaiting_respawn = 0;

    /* framerate counter variables */
    int start_time, end_time;
    int frames_drawn = 0;

    /* respawn timer */
    int respawn_timer = -1;
	
    prev_ticks = SDL_GetTicks();
	
    start_time = time(NULL);

    /* Reset the score counters. */
    player.score = 0;
    opponent.score = 0;

    /* Start sound playback. */
    StartAudio();
    StartMusic();

    /* Start the music update thread. */
    music_update_thread = SDL_CreateThread(UpdateMusicThread, NULL);
    if (music_update_thread == NULL) {
	printf("Unable to start music update thread.\n");
    }

    /* Start the game! */
    while ((quit == 0) && network_ok) {

	/* Determine how many milliseconds have passed since
	   the last frame, and update our motion scaling. */
	prev_ticks = cur_ticks;
	cur_ticks = SDL_GetTicks();
	time_scale = (double)(cur_ticks-prev_ticks)/30.0;
				
	/* Update SDL's internal input state information. */
	SDL_PumpEvents();
		
	/* Grab a snapshot of the keyboard. */
	keystate = SDL_GetKeyState(NULL);

	/* Lock the mutex so we can access the player's data. */
	SDL_LockMutex(player_mutex);
		
	/* If this is a network game, take note of variables
	   set by the network thread. These are handled differently
	   for a scripted opponent. */
	if (opponent_type == OPP_NETWORK) {

	    /* Has the opponent respawned? */
	    if (network_opponent_respawn) {
		printf("Remote player has respawned.\n");
		opponent.shields = 100;
		network_opponent_respawn = 0;
		awaiting_respawn = 0;
	    }
		
	    /* Has the local player been hit? */
	    if (local_player_hit) {
		local_player_hit--;
		player.shields -= PHASER_DAMAGE;
		ShowPhaserHit(&player);
				/* No need to check for death, the
				   other computer will tell us. */
	    }
		}

	/* Update phasers. */
	player.firing -= time_scale;
	if (player.firing < 0) player.firing = 0;
	opponent.firing -= time_scale;
	if (opponent.firing < 0) opponent.firing = 0;
	ChargePhasers(&player);

	/* If the local player is destroyed, the respawn timer will
	   start counting. During this time the controls are disabled
	   and explosion sequence occurs. */
	if (respawn_timer >= 0) {
	    respawn_timer++;

	    if (respawn_timer >= ((double)RESPAWN_TIME / time_scale)) {
		respawn_timer = -1;
		InitPlayer(&player);

				/* Set the local_player_respawn flag so the
				   network thread will notify the opponent
				   of the respawn. */
		local_player_respawn = 1;

		SetStatusMessage("GOOD LUCK, WARRIOR!");
	    }
	}

	/* Respond to input and network events, but not if we're in a respawn. */
	if (respawn_timer == -1) {
	    if (keystate[SDLK_q] || keystate[SDLK_ESCAPE]) quit = 1;
			
	    /* Left and right arrow keys control turning. */
	    turn = 0;
	    if (keystate[SDLK_LEFT]) turn += 10;
	    if (keystate[SDLK_RIGHT]) turn -= 10;
			
	    /* Forward and back arrow keys activate thrusters. */
	    player.accel = 0;
	    if (keystate[SDLK_UP]) player.accel = PLAYER_FORWARD_THRUST;
	    if (keystate[SDLK_DOWN]) player.accel = PLAYER_REVERSE_THRUST;
			
	    /* Spacebar fires phasers. */
	    if (keystate[SDLK_SPACE]) {

		if (CanPlayerFire(&player)) {

		    FirePhasers(&player);

		    /* If it's a hit, either notify the opponent
		       or exact the damage. Create a satisfying particle
		       burst. */
		    if (!awaiting_respawn &&
			CheckPhaserHit(&player,&opponent)) {

			ShowPhaserHit(&opponent);
			DamageOpponent();

			/* If that killed the opponent, set the
			   "awaiting respawn" state, to prevent multiple
			   kills. */
			if (opponent.shields <= 0 &&
			    opponent_type == OPP_NETWORK)
			    awaiting_respawn = 1;
       		    }
		}
	    }
			
	    /* Turn. */
	    player.angle += turn * time_scale;
	    if (player.angle < 0) player.angle += 360;
	    if (player.angle >= 360) player.angle -= 360;

	    /* If this is a network game, the remote player will
	       tell us if we've died. Otherwise we have to check
	       for failed shields. */
	    if (((opponent_type == OPP_NETWORK) && local_player_dead) ||
		(player.shields <= 0))
	    {
		printf("Local player has been destroyed.\n");
		local_player_dead = 0;
				
		/* Kaboom! */
		KillPlayer();
				
		/* Respawn. */
		respawn_timer = 0;
	    }
	}

	/* If this is a player vs. computer game, give the computer a chance. */
	if (opponent_type == OPP_COMPUTER) {
	    if (RunGameScript() != 0) {
		fprintf(stderr, "Ending game due to script error.\n");
		quit = 1;
	    }
			
	    /* Check for phaser hits against the player. */
	    if (opponent.firing) {
		if (CheckPhaserHit(&opponent,&player)) {
					
		    ShowPhaserHit(&player);
		    player.shields -= PHASER_DAMAGE;

		    /* Did that destroy the player? */
		    if (respawn_timer < 0 && player.shields <= 0) {
			KillPlayer();
			respawn_timer = 0;
		    }
		}
	    }

	    ChargePhasers(&opponent);
	    UpdatePlayer(&opponent);
	}

	/* Update the player's position. */
	UpdatePlayer(&player);

	/* Update the status information. */
	SetPlayerStatusInfo(player.score, player.shields, player.charge);
	SetOpponentStatusInfo(opponent.score, opponent.shields);

	/* Make the camera follow the player (but impose limits). */
	camera_x = player.world_x - SCREEN_WIDTH/2;
	camera_y = player.world_y - SCREEN_HEIGHT/2;
		
	if (camera_x < 0) camera_x = 0;
	if (camera_x >= WORLD_WIDTH-SCREEN_WIDTH)
	    camera_x = WORLD_WIDTH-SCREEN_WIDTH-1;
	if (camera_y < 0) camera_y = 0;
	if (camera_y >= WORLD_HEIGHT-SCREEN_HEIGHT)
	    camera_y = WORLD_HEIGHT-SCREEN_HEIGHT-1;

	/* Update the particle system. */
	UpdateParticles();

	/* Keep OpenAL happy. */
	UpdateAudio(&player, &opponent);
				
	/* Redraw everything. */
	DrawBackground(screen, camera_x, camera_y);
	DrawParallax(screen, camera_x, camera_y);
	DrawParticles(screen, camera_x, camera_y);
	if (opponent.firing)
	    DrawPhaserBeam(&opponent, screen, camera_x, camera_y);
	if (player.firing)
	    DrawPhaserBeam(&player, screen, camera_x, camera_y);

	if (respawn_timer < 0)
	    DrawPlayer(&player);
	if (!awaiting_respawn)
	    DrawPlayer(&opponent);
	UpdateStatusDisplay(screen);
		
	/* Release the mutex so the networking system can get it.
	   It doesn't stay unlocked for very long, but the networking
	   system should still have plenty of time. */
	SDL_UnlockMutex(player_mutex);
	
	/* Flip the page. */
	SDL_Flip(screen);

	frames_drawn++;
    }

    end_time = time(NULL);
    if (start_time == end_time) end_time++;

    /* Display the average framerate. */
    printf("Drew %i frames in %i seconds, for a framerate of %.2f fps.\n",
	   frames_drawn,
	   end_time-start_time,
	   (float)frames_drawn/(float)(end_time-start_time));


    /* Terminate the music update thread. */
    if (music_update_thread != NULL) {
	SDL_KillThread(music_update_thread);
	music_update_thread = NULL;
    }
	
    /* Stop audio playback. */
    StopAudio();
    StopMusic();
}
Example #17
0
void Game::Update()
{
	display->Clear(0.1f, 0.1f, 0.1f, 1.0f);

	if (controller.isClosing())
	{
		timer->Pause();
		state = MENU;
		menu->SetState(MenuState::PAUSE);
	}

	timer->Update();
	totalTime = timer->GetTotalTime();
	elapsedTime = timer->GetElapsedTime();

	controller.Update(elapsedTime);
	while (SDL_PollEvent(&e))
		controller.HandleInput(e);

	switch (state)
	{
	case(GameState::MENU) :
		menu->Update(elapsedTime, totalTime);
		switch (menu->GetState())
		{
		case(MenuState::START) :
			Restart();
			break;
		case(MenuState::RESUME) :
			timer->Resume();
			state = GameState::RUNNING;
			break;
		case(MenuState::QUIT) :
			End();
			break;
		case(MenuState::RETRY) :
			Restart();
			break;
		}
		break;

	case(GameState::RUNNING) :
		UpdateBackground(elapsedTime, totalTime);

		UseBomb();
		Shoot();
		UpdateBomb(elapsedTime, totalTime);
		UpdatePlayerBullets(elapsedTime, totalTime);
		UpdatePlayer(elapsedTime, totalTime);
		if (player->IsHit())
			PlayerHit();
		
		enemyHandler->Update(elapsedTime, totalTime, &playerbullets, bomb);
		if (!enemyHandler->EnemiesLeft())
			Won();
		if (player->GetState() == GameObject::DEAD)
			Lost();
		UpdateOverlay(elapsedTime, totalTime);

		break;
	}

	display->Update();
}
Example #18
0
void RunGame()
{
  UpdatePlayer();
  UpdateAI();
  UpdateBall();
}
Example #19
0
File: game.c Project: mtl23/2DFINAL
/*notice the default arguments for main.  SDL expects main to look like that, so don't change it*/
int main(int argc, char *argv[])
{

 // SDL_Surface *temp = NULL;

  
  int done;// the player
  const Uint8 *keys;// the player

  /* This section starts by loading the BG as a surface and converting it to a texture This will have to change 
  if I can manage to scroll the trexture arond the player*/
 
SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_RESIZABLE, &mainWindow, &renderer);
SDL_SetWindowTitle(mainWindow, "Nitro Hotness");
 if( TTF_Init() == -1 )
    {
        return false;    
    }

  if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
    {
        return false;    
    }

InitSpriteSystem();
InitEntitySystem(entityMax);


map mymap = setWorld();
ObstacleList ol = newObstacleList();
mew = newPlayer();
Obstacle Doh = newObstacle(0);
Road_M Path = initRoad();
AI rival = new_AI();
GUI HUD = InitGUI();
mew.position=0;
done = 0;

//The music that will be played
   Mix_Music *music = NULL;


   Mix_Chunk *buzz = NULL;
    buzz = Mix_LoadWAV( "sfx/buzz.wav" );
	readSave(&mew);
	showTitle();
	showMain();
  oldTime = 0;
  currentTime = 0;
  mytime = 0;

do
 	{
		
  oldTime = 0;
  currentTime = 0;
  mytime = 0;
	  if( Mix_PlayingMusic() == 0 )
                    {
                        //Play the music
                        if( Mix_PlayMusic( level_music, -1 ) == -1 )
                        {
                            return 1;
                        } 
					}
	 SDL_Event e;
	 SDL_PollEvent( &e ); 
		if(&e)
					{
					//User requests quit
					if( e.type == SDL_QUIT )
					{
						done = 1;
					}
					//user presses enter to go to next menu
					
					//User presses a key
					else if( e.type == SDL_KEYDOWN )
					{
						//Select surfaces based on key press
						switch( e.key.keysym.sym )
						{
						
						case SDLK_LEFT:
				//		slog("left is down");	
						mew.playerX += 3;
						mew.accel = (mew.accel - .000001);
						break;

						case SDLK_RIGHT:
					//	slog("right is down");
						mew.playerX -= 3;
						mew.accel = (mew.accel - .000001);
						break;

						case SDLK_UP:
					//	slog("up is down");
						 mew.accel = (mew.accel + .00007);
						 Mix_PlayChannel( 1, buzz, 0 );
						 break;
						
						case SDLK_DOWN:
					//	slog("down is down");
						mew.accel = (mew.accel - .00008);
						break;
						}
					}

					else if( e.type == SDL_KEYUP )
					{
						//Select surfaces based on key press
						switch( e.key.keysym.sym )
						{	
						
						case SDLK_RETURN :
						if(mew.done ==1)
						{
							Mix_HaltMusic();
							if(GP == 1)
							{
							mew.done=0;
							lvl++;
							//slog("new level is %i",lvl);
							mew.position = 0;
							rival.position =0;
							setWorld();
							Results(mew.rank,lvl);
							}
						else if (GP == 0)
							{
							mew.done=0;
							mew.position = 0;
							rival.position =0;
							levelSelect();
							}
						
						}
						else
						{
						slog("too soon");
						}
						
						case SDLK_LEFT:
					//	slog("left is up");	
						e.type = SDLK_CLEAR;
						break;

						case SDLK_RIGHT:
					//	slog("right is up");
						e.type = SDLK_CLEAR;
						break;

						case SDLK_UP:
					//	slog("up is up");
						mew.accel = (mew.accel - .001);
						Mix_HaltChannel(1);
						e.type = SDLK_CLEAR;
						break;

						case SDLK_DOWN:
					//	slog("down is up");
						mew.accel = 0;
						e.type = SDLK_CLEAR;
						break;

						default:
					//slog("simple decel");	
						mew.accel = (mew.accel-0.00001);
						break;

						}
					}

		if(mew.position > rival.position)
		{
			mew.rank = 1 ;
		}
		else if( rival.position > mew.position )
		{
			mew.rank = 2 ;
		}
		SDL_RenderClear(renderer);
		DrawBG(BG1,BG2);
		roadUpdate(Path,mymap,mew);
		roadDraw(Path,mymap,&mew);
		roadFetch(Path,mymap,&mew);
		checkForObstacles(ol , &mew, Doh);
		update_AI(&rival, &mew);
		UpdatePlayer(&mew);
		DrawGui(HUD,mew);
		NextFrame();
		keys = SDL_GetKeyboardState(NULL);

	if(keys[SDL_SCANCODE_ESCAPE])
    {
        done = 1;
    }
	
}
  }while(!done);
      //Free the sound effects
   //Free the music
  Mix_FreeMusic( music );
  CloseEntitySystem();
  CloseSpriteSystem();
  exit(0);		/*technically this will end the program, but the compiler likes all functions that can return a value TO return a value*/ 
 return 0;
}
Example #20
0
// Gameplay Screen Update logic
void UpdateAisle01Screen(void)
{
    // Update doors bounds
    doorLeft.bound.x = doorLeft.position.x - scroll;
    doorCenter.bound.x = doorCenter.position.x - scroll;
    doorRight.bound.x = doorRight.position.x - scroll;

    if (player.key)
    {       
        // Door: left
        if ((CheckCollisionPointRec(GetMousePosition(), doorLeft.bound)) || 
            (CheckCollisionRecs(player.bounds, doorLeft.bound))) doorLeft.selected = true; 
        else doorLeft.selected = false;
        
        if ((doorLeft.selected) && (CheckCollisionRecs(player.bounds, doorLeft.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorLeft.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorLeft.locked)
                {
                    doorLeft.frameRec.y = 0;
                    doorLeft.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 1;
            }
        }
        
        // Door: center
        if ((CheckCollisionPointRec(GetMousePosition(), doorCenter.bound)) || 
            (CheckCollisionRecs(player.bounds, doorCenter.bound))) doorCenter.selected = true; 
        else doorCenter.selected = false;
        
        if ((doorCenter.selected) && (CheckCollisionRecs(player.bounds, doorCenter.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorCenter.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorCenter.locked)
                {
                    doorCenter.frameRec.y = 0;
                    doorCenter.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 2;
            }
        }
        
        // Door: right
        if ((CheckCollisionPointRec(GetMousePosition(), doorRight.bound)) || 
            (CheckCollisionRecs(player.bounds, doorRight.bound))) doorRight.selected = true; 
        else doorRight.selected = false;
        
        if ((doorRight.selected) && (CheckCollisionRecs(player.bounds, doorRight.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorRight.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorRight.locked)
                {
                    doorRight.frameRec.y = 0;
                    doorRight.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 3;
            }
        }
    }
    
    if (msgState > 2)
    {
        UpdatePlayer();
	
		// Monsters logic
        UpdateMonster(&lamp);
        UpdateMonster(&picture);
    }
    
    // Update monster bounds
    lamp.bounds.x = lamp.position.x + 20 - scroll;
    picture.bounds.x = picture.position.x + 44 - scroll;
	
    // Check player hover monsters to interact
    if (((CheckCollisionRecs(player.bounds, lamp.bounds)) && !lamp.active) ||
        ((CheckCollisionRecs(player.bounds, picture.bounds)) && !picture.active)) monsterHover = true;
    else monsterHover = false;
    
    // Monters logic: lamp
    if ((CheckCollisionRecs(player.bounds, lamp.bounds)) && !lamp.active)
    {
        lamp.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), lamp.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 1;
        }
    }
    else lamp.selected = false;
    
    // Monters logic: picture
    if ((CheckCollisionRecs(player.bounds, picture.bounds)) && !picture.active)
    {
        picture.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), picture.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 2;
        }
    }
    else picture.selected = false;
    
    if (searching)
    {
        framesCounter++;
        
        if (framesCounter > 180)
        {
            if (monsterCheck == 1)
            {
                if (lamp.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                lamp.active = true;
                lamp.selected = false;
            }
            else if (monsterCheck == 2)
            {
                if (picture.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                picture.active = true;
                picture.selected = false;
            }
  
            searching = false;
            framesCounter = 0;
        }
    }
    
    // Text animation
    framesCounter++;
    
    if ((framesCounter%2) == 0) lettersCounter++;

    if (msgState == 0)
    {
        if (lettersCounter <= (int)strlen(message)) strncpy(msgBuffer, message, lettersCounter);
        else
        {
            for (int i = 0; i < (int)strlen(msgBuffer); i++) msgBuffer[i] = '\0';

            lettersCounter = 0;
            msgState = 1;
        }
        
        if (IsKeyPressed(KEY_ENTER)) msgState = 1;
    }
    else if (msgState == 1)
    {
        msgCounter++;
        
        if ((IsKeyPressed(KEY_ENTER)) || (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)))
        {
            msgState = 2;
            msgCounter = 0;
        }
    }
    else if (msgState == 2)
    {
        msgCounter++;
        
        if (msgCounter > 180) msgState = 3;
    }
    else msgCounter++;
    
    if (player.position.x > 200)
    {
        scroll = player.position.x - 200;
        
        if (scroll > 620) scroll = 620;
    }
}
Example #21
0
int main(int argc,char *argv[])
{

	//FILE *fp;
	//char file[15];
	//strcpy(file,argv[1]);
	//strcat(file,".txt");

	//fp=fopen(file,"wt");

	//*stdout = *fp;

	//memset( &player,'-1' ,sizeof(player) );
	player.iUid = -1;

	for(int i = 0 ; i < MAX_USERS_CLI ; ++i )
	{
		players[i].iUid = -1;
		players[i].bOnline = false;
	}

	//----------------------for RWP--------------------------
	srand( (unsigned)time( NULL ) );
	player.iState = 0;
	//-------------------------------------------------------

	Initial();
	strcpy ( player.sUserName,argv[1]);
	int show = ( atoi(argv[3]) );

	WSADATA wsaData;
	if( SOCKET_ERROR == WSAStartup( WINSOCK_VERSION, &wsaData ) || wsaData.wVersion != WINSOCK_VERSION )
		return false;

	//------------------for user login to gs request zone ip----------------
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in addr;
	ZeroMemory( &addr, sizeof(addr) );

	addr.sin_family = AF_INET;
	addr.sin_port   = htons(atoi(gs_port));
	addr.sin_addr.S_un.S_addr   = inet_addr(gs_ip);

	connect( sockfd, (struct sockaddr *)&addr , sizeof(struct sockaddr));

	UserLogInToGS ultg;
	strcpy ( ultg.sUserName,player.sUserName);
	strcpy ( ultg.sPass,argv[2]);

	SendTCPPacket( sockfd, (char *)&ultg , sizeof(ultg) );

	char buf[MAX_PACKET_SIZE];
	ZeroMemory( &buf, sizeof(buf) );

	RecvTCPPacket( sockfd, (char *)&buf );

	int try_num = 0;
	while(try_num < 3)
	{
		MessageHeader * tMh = (MessageHeader*)buf;

		if(tMh->MsgID == MSG_USERREJECT)
		{
			UserReject *urm = (UserReject *)buf;
			switch(urm->rWhy)
			{
			case 	R_NOTEXIST:
				{
					printf("Wrong username!!!\n");
				}break;
			case	R_FULL:
				{
					printf("zone server FULL!!!\n");
				}break;
			case	R_WRONGPASS:
				{
					printf("Pass wrong!!!\n");
				}break;
			}

			printf("Retry ? (username pass)\n");
			scanf("%s %s\n",&ultg.sUserName,&ultg.sPass );

			SendTCPPacket( sockfd, (char *)&ultg , sizeof(ultg) );
		}else
		{
			UserZoneInfo *uzi = (UserZoneInfo *)buf;
			player.iUid = uzi->iUid;
			player.iZid = uzi->iZid;
			strcpy ( player.sIP, uzi->sZip );
			strcpy ( player.sPort , uzi->sZport );		

			printf("uid = %d get zone info ip %s,port %s\n",player.iUid,player.sIP,player.sPort);
			break;
		}

		ZeroMemory( &buf, sizeof(buf) );
		++try_num;
		RecvTCPPacket(sockfd, (char *)&buf);
	}
	closesocket(sockfd);

	//---------------get zone info and go to login mx and zone---------------
	printf("Manual control ? (y/n)\n (W,S,A,D direction,Q exit)\n");
	scanf("%c",&con);

	if(show)
	{
		if( NULL == CreateThread( NULL, 0, glut_Thread, player.sUserName, 0, NULL ))
			return -1;
	}

	if( SOCKET_ERROR == (sMXSocket = socket( AF_INET, SOCK_STREAM, 0 )))
	{
		printf("Socket Error !!!!\n");
		return false;
	}

	if( ConnectToMX( ) )
	{	
		fLastUpdate = 0.0f;

		int nready;
		struct timeval timeout;

		FD_ZERO(&rset);
		FD_ZERO(&temprset);
		FD_SET( sMXSocket, &rset);
		int maxfdp1 = sMXSocket + 1;

		//int time1 = GetTickCount();

		//int time2;

		//int attack_t = 50;

		while(true)
		{
			/*
			time2 = GetTickCount();

			if( ((time2 - time1)>1) && player.iUid == 1 && attack_t != 0 )
			{
				UserComToMX ucm;
				ucm.iUid_S = player.iUid;
				ucm.iUid_D = 10;
				ucm.cCom = C_ATTACK;
				ucm.iTime = time2;
				printf("attack uid=10!!\n");
				SendTCPPacket( sMXSocket, (char*)&ucm, sizeof(ucm) );
				--attack_t;
				time1 = time2;
			}
			*/
			if(con == 'n')
				UpdatePlayer();
			FD_ZERO(&temprset);
			temprset = rset;
			timeout.tv_sec = 0;
			timeout.tv_usec = 5000;

			if ( (nready = select(maxfdp1, &temprset, NULL, NULL, &timeout)) < 0)
			{
				break;

			}else if( nready == 0)
			{
				if(con == 'n')
					UpdatePlayer();
				continue;
			}

			if (FD_ISSET(sMXSocket, &temprset))
			{
				char buffer[MAX_PACKET_SIZE];
				ZeroMemory( buffer, sizeof(buffer) );
				RecvTCPPacket( sMXSocket , (char *)&buffer );

				ProcessPacket( (char *)&buffer );
			}
		}

	}

	closesocket( sMXSocket );
	WSACleanup();
	//fclose( fp );

	return 0;
}
Example #22
0
//updates the world one tick
void UpdateGame(void)
{
   int numbigasteroids = 0, nummedasteroids = 0;
   LIST * cur;
   LIST * next;
   static unsigned int fpsframes = 0;
   static unsigned int last_fps_time = 0;
   unsigned int t;
   char hiscore_name[HS_NAME_LENGTH];

   if(g_paused)
      return;

   UpdateStarfield(&g_starfield);

   for(cur = g_asteroid_list; cur; cur = cur->next)
   {
      if(((ASTEROID *)cur->d)->scale == 4.0f)
         numbigasteroids++;
      else if(((ASTEROID *)cur->d)->scale == 2.0f)
         nummedasteroids++;
   }

   t = 1500*numbigasteroids + 500*nummedasteroids + (int)(16384.0/pow((double)g_score, 0.3010299956639811952));
   if(g_ships
      && !g_time_to_reset
      && g_level > 2
      && !(rand() % t))
   {
      NewAlien(g_score >= 10000 ? (rand() % 3) : 1);
   }

   t = (g_ships + 1) * 1000;
   if(g_ships
      && g_ships < 11
      && !g_time_to_reset
      && !(rand() % t))
   {
      NewPowerup();
   }

   for(cur = g_asteroid_list; cur; cur = cur->next)
      UpdateAsteroid(cur->d);

   if(g_ships)
      UpdatePlayer(&g_player, g_keys);

   for(cur = g_alien_list; cur; cur = next)
   {
      next = cur->next;

      UpdateAlien(cur->d, (g_ships ? &g_player : NULL), g_asteroid_list);
      if(((ALIEN *)cur->d)->pos.x < 0.0f || ((ALIEN *)cur->d)->pos.x > 40.0f)
         RemoveNode(cur, &g_alien_list);
   }

   for(cur = g_shot_list; cur; cur = next)
   {
      next = cur->next;

      UpdateShot(cur->d);
      if(!(((SHOT *)cur->d)->life))
         RemoveNode(cur, &g_shot_list);
   }

   for(cur = g_explosion_list; cur; cur = next)
   {
      next = cur->next;

      UpdateExplosion(cur->d);
      if(!(((EXPLOSION *)cur->d)->life))
         RemoveNode(cur, &g_explosion_list);
   }

   for(cur = g_burst_list; cur; cur = next)
   {
      next = cur->next;

      UpdateBurst(cur->d);
      if(!(((BURST *)cur->d)->life))
         RemoveNode(cur, &g_burst_list);
   }

   for(cur = g_powerup_list; cur; cur = next)
   {
      next = cur->next;

      UpdatePowerup(cur->d);
      if(((POWERUP *)cur->d)->pos.x < 0.0f || ((POWERUP *)cur->d)->pos.x > 40.0f)
         RemoveNode(cur, &g_powerup_list);
   }

   Clipping();

   g_frame++; //next frame
   if(g_time_to_reset && !(--g_time_to_reset))
      NextLevel();

   if(!g_ships && g_hisct_delay && !(--g_hisct_delay) && IsScoreHi(&g_hisct, g_score) && GetHiScoreName(hiscore_name))
      AddHiScore(&g_hisct, hiscore_name, g_score, g_level);

   fpsframes++;
   t = glutGet(GLUT_ELAPSED_TIME);
   if(t >= last_fps_time + 1000)
   {
      g_fps = (float)fpsframes / (float)(t - last_fps_time) * 1000.0f;
      fpsframes = 0;
      last_fps_time = t;
   }

   glutPostRedisplay();
}
Example #23
0
// Gameplay Screen Update logic
void UpdateAtticScreen(void)
{
    if (player.key)
    {
        // Door: right
        if ((CheckCollisionPointRec(GetMousePosition(), doorRight.bound)) || 
            (CheckCollisionRecs(player.bounds, doorRight.bound))) doorRight.selected = true; 
        else doorRight.selected = false;
        
        if ((doorRight.selected) && (CheckCollisionRecs(player.bounds, doorRight.bound)))
        {
            if (((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && CheckCollisionPointRec(GetMousePosition(), doorRight.bound)) || (IsKeyPressed(KEY_SPACE)))
            {
                if (doorRight.locked)
                {
                    doorRight.frameRec.y = 0;
                    doorRight.locked = false;
                    PlaySound(sndDoor);
                }
                else finishScreen = 1;
            }
        }
    }
        
    if (msgState > 2)
    {
        UpdatePlayer();
	
		// Monsters logic
        UpdateMonster(&lamp);
        UpdateMonster(&arc);
    }
	
    // Check player hover monsters to interact
    if (((CheckCollisionRecs(player.bounds, lamp.bounds)) && !lamp.active) ||
        ((CheckCollisionRecs(player.bounds, arc.bounds)) && !arc.active)) monsterHover = true;
    else monsterHover = false;
    
    // Monters logic: lamp
    if ((CheckCollisionRecs(player.bounds, lamp.bounds)) && !lamp.active)
    {
        lamp.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), lamp.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 1;
        }
    }
    else lamp.selected = false;
    
    // Monters logic: arc
    if ((CheckCollisionRecs(player.bounds, arc.bounds)) && !arc.active)
    {
        arc.selected = true;
        
        if ((IsKeyPressed(KEY_SPACE)) || 
            ((IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) && (CheckCollisionPointRec(GetMousePosition(), arc.bounds))))
        {
            SearchKeyPlayer();
            searching = true;
            framesCounter = 0;
            
            monsterCheck = 2;
        }
    }
    else arc.selected = false;
    
    if (searching)
    {
        framesCounter++;
        
        if (framesCounter > 180)
        {
            if (monsterCheck == 1)
            {
                if (lamp.spooky)
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                lamp.active = true;
                lamp.selected = false;
            }
            else if (monsterCheck == 2)
            {
                if (arc.spooky) 
                {
                    ScarePlayer();
                    PlaySound(sndScream);
                }
                else FindKeyPlayer();
                
                arc.active = true;
                arc.selected = false;
            }
  
            searching = false;
            framesCounter = 0;
        }
    }
    
    // Text animation
    framesCounter++;
    
    if ((framesCounter%2) == 0) lettersCounter++;

    if (msgState == 0)
    {
        if (lettersCounter <= (int)strlen(message)) strncpy(msgBuffer, message, lettersCounter);
        else
        {
            for (int i = 0; i < (int)strlen(msgBuffer); i++) msgBuffer[i] = '\0';

            lettersCounter = 0;
            msgState = 1;
        }
        
        if (IsKeyPressed(KEY_ENTER)) msgState = 1;
    }
    else if (msgState == 1)
    {
        msgCounter++;
        
        if ((IsKeyPressed(KEY_ENTER)) || (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)))
        {
            msgState = 2;
            msgCounter = 0;
        }
    }
    else if (msgState == 2)
    {
        msgCounter++;
        
        if (msgCounter > 180) msgState = 3;
    }
    else msgCounter++;
    
    if (IsKeyPressed('M'))
    {
        finishScreen = 1;
    }
}
Example #24
0
void CFileScore::SaveScore(int ClientID, float Time, CCharacter *pChar)
{
	UpdatePlayer(ClientID, Time, pChar->m_CpCurrent);
}
Example #25
0
///=====================================================
/// 
///=====================================================
void Game::UpdatePlayingState(OpenGLRenderer* renderer){
	PROFILE_CATEGORY(Gameplay);
	if (s_theInputSystem->GetKeyWentDown(VK_ESCAPE)){ //go back to Quest
		SetState(Quest);
		m_titleRenderer.ClearText();
		m_titleRenderer.PrintText("Quests");

		DestroyCurrentGame(renderer);
	}
	else if (s_theInputSystem->GetKeyWentDown('M')){ //toggle map visibility
		m_forceMapVisible = !m_forceMapVisible;
	}
	else if (s_theInputSystem->IsKeyDown('P')){ //test pathfinding
		static IntVec2 goal;
		if (m_player->m_path.HasFinishedPath()){
			Tile randomTile = m_map->GetRandomTile();
			while (randomTile.GetTileType() != TileType::Air)
				randomTile = m_map->GetRandomTile();
			goal = randomTile.m_position;
		}
		m_player->PathfindToDestination(goal, true, false);
	}
	else if (m_messageBar.m_isWaitingForPlayer){
		if (s_theInputSystem->GetKeyWentDown(VK_SPACE)){ //read more messages in the message bar
			m_messageBar.m_isWaitingForPlayer = false;
			m_messageBar.m_text.clear();
		}
	}
	else if (m_savedGame){ //return to main menu after save game
		SetState(MainMenu);

		m_player->Die();
		DestroyCurrentGame(renderer);

		m_titleRenderer.ClearText();
		m_titleRenderer.PrintText("Dagger", RGBAchars::RED);

		m_menuRenderer.ClearText();
		m_menuRenderer.PrintText("N) New Game");
		m_menuRenderer.PrintText("L) Load Game");
		m_menuRenderer.PrintText("Q) Quit");
		m_menuRenderer.ToggleRenderFromCenter();

		m_bottomMessageRenderer.ClearText();

		m_savedGame = false;
	}
	else if (s_theInputSystem->GetCurrentCharacterDown() == 'S'){ //save game
		HandleDeadEntities(renderer);
		SaveGame();
	}
	///==========================================================================================================================================
	/// GAMEPLAY
	///==========================================================================================================================================
	else{
		if (Actor::s_actorsOnMap.size() == 1){ //only have a player... the following code would crash in that case
			UpdatePlayer(renderer);
			return;
		}

		//pre-compute what each AI plans to do, so the Group AI system can make adjustments before actually making moves
		Actors::const_iterator actorIter = Actor::s_actorsOnMap.cbegin();
		float maxSpeed = actorIter->first + 1.0f;
		if (!actorIter->second->IsPlayer()){
			for (; actorIter != Actor::s_actorsOnMap.cend(); ++actorIter){
				Actor* actor = actorIter->second;

				if (actor->IsPlayer()){
					break;
				}
				else{
					((NPC*)actor)->PlanNextThink();
				}
			}

			m_AISystem.PlanNextMove(*m_player);

			
			actorIter = Actor::s_actorsOnMap.cbegin();
		}

		//everyone moves
		for (; actorIter != Actor::s_actorsOnMap.cend() && actorIter->first < maxSpeed;){
			Actor* actor = actorIter->second;

			if (actor->IsPlayer()){
				bool didMove = UpdatePlayer(renderer);
				if (didMove){
					float turnOrder = actorIter->first;
					actorIter = Actor::s_actorsOnMap.erase(actorIter);
					Actor::s_actorsOnMap.emplace(++turnOrder, actor);
				}

				return;
			}
			else{
				actor->Think(true);

				float turnOrder = actorIter->first;
				actorIter = Actor::s_actorsOnMap.erase(actorIter);
				Actor::s_actorsOnMap.emplace(++turnOrder, actor);
			}
		}
	}
}
Example #26
0
void CFileScore::SaveScore(int ClientID, float Time, float CpTime[NUM_CHECKPOINTS])
{
	CConsole* pCon = (CConsole*)GameServer()->Console();
	if(!pCon->m_Cheated)
		UpdatePlayer(ClientID, Time, CpTime);
}
Example #27
0
static void PlayGame()
{
    Uint8 *keystate;
    int quit = 0;
    int turn;
    int prev_ticks = 0, cur_ticks = 0; /* for keeping track of timing */

    /* framerate counter variables */
    int start_time, end_time;
    int frames_drawn = 0;
	
    /* Start audio playback. */
    StartAudio();
    StartMusic();

    /* Start the music update thread. */
    music_update_thread = SDL_CreateThread(UpdateMusicThread, NULL);
    if (music_update_thread == NULL) {
	printf("Unable to start music update thread.\n");
    }

    prev_ticks = SDL_GetTicks();
    start_time = time(NULL);
	
    while (quit == 0) {
		
	/* Determine how many milliseconds have passed since
	   the last frame, and update our motion scaling. */
		
	prev_ticks = cur_ticks;
	cur_ticks = SDL_GetTicks();
	time_scale = (double)(cur_ticks-prev_ticks)/30.0;
				
	/* Update SDL's internal input state information. */
	SDL_PumpEvents();
		
	/* Grab a snapshot of the keyboard. */
	keystate = SDL_GetKeyState(NULL);
		
	/* Respond to input. */
	if (keystate[SDLK_q] || keystate[SDLK_ESCAPE]) quit = 1;
		
	/* Left and right arrow keys control turning. */
	turn = 0;
	if (keystate[SDLK_LEFT]) turn += 15;
	if (keystate[SDLK_RIGHT]) turn -= 15;
		
	/* Forward and back arrow keys activate thrusters. */
	player.accel = 0;
	if (keystate[SDLK_UP]) player.accel = PLAYER_FORWARD_THRUST;
	if (keystate[SDLK_DOWN]) player.accel = PLAYER_REVERSE_THRUST;
		
	/* Spacebar slows the ship down. */
	if (keystate[SDLK_SPACE]) {
	    player.velocity *= 0.8;
	}
		
	/* Just an amusing way to test the particle system. */
	if (keystate[SDLK_e]) {
	    CreateParticleExplosion(
		player.world_x, player.world_y, 255, 255, 255, 10, 300);
	    CreateParticleExplosion(
		player.world_x, player.world_y, 255, 0, 0, 5, 100);
	    CreateParticleExplosion(
		player.world_x, player.world_y, 255, 255, 0, 2, 50);
	}
		
	/* Allow a turn of four degrees per frame. */
	player.angle += turn * time_scale;
	if (player.angle < 0) player.angle += 360;
	if (player.angle >= 360) player.angle -= 360;

	/* Update the player's position. */
	UpdatePlayer(&player);
	UpdatePlayer(&opponent);

	/* Make the camera follow the player (but impose limits). */
	camera_x = player.world_x - SCREEN_WIDTH/2;
	camera_y = player.world_y - SCREEN_HEIGHT/2;
		
	if (camera_x < 0) camera_x = 0;
	if (camera_x >= WORLD_WIDTH-SCREEN_WIDTH)
	    camera_x = WORLD_WIDTH-SCREEN_WIDTH-1;
	if (camera_y < 0) camera_y = 0;
	if (camera_y >= WORLD_HEIGHT-SCREEN_HEIGHT)
	    camera_y = WORLD_HEIGHT-SCREEN_HEIGHT-1;

	/* Update the particle system. */
	UpdateParticles();
				
	/* Keep OpenAL happy. */
	UpdateAudio(&player, &opponent);
	       
	/* Redraw everything. */
	DrawBackground(screen, camera_x, camera_y);
	DrawParallax(screen, camera_x, camera_y);
	DrawParticles(screen, camera_x, camera_y);
	DrawPlayer(&player);
	DrawPlayer(&opponent);
	
	/* Flip the page. */
	SDL_Flip(screen);

	frames_drawn++;

    }

    end_time = time(NULL);
    if (start_time == end_time) end_time++;

    /* Display the average framerate. */
    printf("Drew %i frames in %i seconds, for a framerate of %.2f fps.\n",
	   frames_drawn,
	   end_time-start_time,
	   (float)frames_drawn/(float)(end_time-start_time));

    /* Terminate the music update thread. */
    if (music_update_thread != NULL) {
	SDL_KillThread(music_update_thread);
	music_update_thread = NULL;
    }
	
    /* Stop audio playback. */
    StopAudio();
    StopMusic();

}
Example #28
0
INT CGpApp::FrameMove()
{
	INT hr =0;

	// Input Update
	hr = m_pInput->Update();

	if (LC_FAILED(hr))
		return LC_EFAIL;


	LCXVECTOR3	vcMtsPos = m_pInput->MtsPosition();
	//LC_STATE	nMtsState= m_pInput->MtsState();
	const BYTE*	pKey = m_pInput->KeyMap();
	const BYTE*	pMts = m_pInput->MtsMap();

	// Home Key
	if(pKey[LCIK_ESCAPE])
		return LC_EFAIL;


	if(8>m_nSkip)
	{
		++m_nSkip;
		return 0;
	}


	SystemControl();

	if (PLAYER_STATUS_DEAD != m_PlayerStatus)
		UpdatePlayer();

	UpdatePlayerMissiles();
	UpdateEnemies();
	UpdateEnemyMissiles();

	CollisionPlayerMissilesAndEnemies();
	CollisionPlayerAndEnemies();
	CollisionEnemyMissilesAndPlayer();
	ScrollBackground();

	ShieldPulse();


	if(0>=m_Player.nAlive)
		return LC_EFAIL;


	
	if(m_bShowSt)
	{
		char sbuf[128]={0};
		DOUBLE fFPS		   = m_TimeFPS;
		DOUBLE fElasedTime = m_TimeElps;

		sprintf(sbuf, "갈릭: m: %.f %.f %d, %.f(%.1f)F"
				, vcMtsPos.x, vcMtsPos.y, pMts[0], fFPS, fElasedTime);

		m_pFont->String(sbuf);
	}

	return LC_OK;
}
Example #29
0
/*******************************************************************************
関数名:	void UpdateGame(void)
引数:	なし
戻り値:	なし
説明:	ゲームの更新関数
*******************************************************************************/
void UpdateGame(void)
{
	//初期値
	g_fTimeSpeed = 0.01f;

	GAME_STEP stepNow = GetGameStep();
	switch(stepNow)
	{
		case STEP_PLAY:

			UpdatePlayer();
			UpdateCamera();
			UpdateGun();
			
			UpdatePlayerBullet(g_fTimeSpeed);
			UpdateEnemy( g_fTimeSpeed);
			UpdateEnemyBullet( g_fTimeSpeed);

			//UpdateBillBoard();
			UpdateParticle( g_fTimeSpeed);
			UpdateStageManager( g_fTimeSpeed);

			//UpdateModel();
			UpdateGunSight();
			UpdateItemBullet();
			UpdateClock( g_fTimeSpeed);
			UpdateTime( g_fTimeSpeed);

			if(GetKeyboardTrigger(DIK_P) )
			{
				SetGameStep(STEP_PAUSE);
				SetMessage(MSG_PAUSE);
			}
			break;
		case STEP_SHOOT:
			
			ChangeTimeSpeed( 1.0f);
			
			UpdateEnemy( g_fTimeSpeed);
			//UpdatePlayer();
			UpdatePlayerBullet( g_fTimeSpeed);
			//UpdateEnemyBullet( g_fTimeSpeed);
			UpdateClock( g_fTimeSpeed);
			UpdateTime( g_fTimeSpeed);

			g_nCounterShoot++;
			if( g_nCounterShoot > 15)
			{
				g_nCounterShoot = 0;
				SetGameStep(STEP_PLAY);
			}
			break;
		case STEP_PAUSE:
			StopSound();
			if(GetKeyboardTrigger(DIK_P) )
			{
				SetGameStep(STEP_PLAY);
				ClearMessage(MSG_PAUSE);
			}
			break;
		case STEP_DIE:
			ChangeTimeSpeed( 1.0f);

			UpdateEnemy( g_fTimeSpeed);
			UpdateEnemyBullet( g_fTimeSpeed);
			UpdatePlayerBullet( g_fTimeSpeed);
			UpdateParticle( g_fTimeSpeed);

			g_nCounterFrame++;
			if( g_nCounterFrame > 90)
			{
				g_nCounterFrame = 0;
				if( GetPlayer()->nLife <= 0)
				{
					FadeOutToNext(MODE_RESULT);
				}
				else
				{
					FadeOutToNext(STEP_RESET);
					SetGameStep(STEP_NOTHING);
				}
				
			}

			break;
		case STEP_RESET:
			InitStageManager( false, GetPlayer()->nLife);
			SetGameStep(STEP_PLAY);	
			break;
		case STEP_CLEAR:
			StopSound(SOUND_LABEL_SE_RUN);
			SetMessage(MSG_STAGECLEAR);

			g_nCounterFrame++;
			if( g_nCounterFrame > 90)
			{
				g_nCounterFrame = 0;

				switch(GetStageMode())
				{
				case STAGE0:
					FadeOutToNext(STAGE1);
					break;
				case STAGE1:
					FadeOutToNext(STAGE2);
					break;
				case STAGE2:
					FadeOutToNext(STAGE3);
					break;
				case STAGE3:
					FadeOutToNext(MODE_RESULT);
					g_bGameClear = true;
					break;
				}
				
				SetGameStep(STEP_NOTHING);
			}
			break;
		case STEP_NOTHING:
			//just let time go, and do nothing
			break;
	}	

	//UI update
	UpdateNumBullet();

	//Debug update
	UpdateMeshDome();

	if(GetKeyboardTrigger(DIK_RETURN) )
	{	
		FadeOutToNext(MODE_RESULT);
	}
	if(GetKeyboardTrigger(DIK_F3))
	{	
		PlaySound( SOUND_LABEL_SE_CLEAR);
		SetGameStep(STEP_CLEAR);
	}
	if(GetKeyboardTrigger(DIK_F2))
	{
		PlaySound(SOUND_LABEL_SE_SWITCH);
		SwitchDebug();
	}
}