Ejemplo n.º 1
0
void GameLayer::Update(float dt)
{
	UpdateHero(dt);
	UpdateEnemy(dt);
	UpdateBullet(dt);
	ProductEnemy(dt);
}
Ejemplo n.º 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;
    }
    
    
}
//------------------------------------------------------------------------------
// Purpose :
// Input   :
// Output  :
//------------------------------------------------------------------------------
void CBaseHelicopter::Hunt( void )
{
	UpdateEnemy();

	UpdateTrackNavigation( );

	UpdateDesiredPosition();

	UpdateFacingDirection();

	Flight();

	UpdatePlayerDopplerShift( );

	FireWeapons();
}
Ejemplo n.º 4
0
/****************************************************************************
 * ClientWndProc                                                            *
 *  - Typical PM client window procedure.  (see below)                      *
 *  - Standard client window I/O                                            *
 ****************************************************************************/
MRESULT EXPENTRY ClientWndProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
	   RECTL  rcl;
	   SWP	  swp;
	   HPS	  hpsPaint;

    static HPS	  hps;                      /* Permanent HPS                */
    static INT    cx, cy;		    /* Client window dimensions     */
    static BOOL   bSlowUpdateNow = FALSE;   /* Update toggle for asteroids  *
                                             *   and enemy which are slow.  */
    static POINTL ptlCenter;		    /* Center of client window      */

    switch (msg) {
      /* Recieved from WinCreateStdWindow */
      case WM_CREATE:
	/* Get permanent PS for entire window */
	hps = WinGetPS(hwnd);

	/* Load private Asteroid fonts from ASTEROID.DLL */
	if (GpiLoadFonts(hab, "ASTEROID") != GPI_OK) {
            WinReleasePS(hps);
	    WinAlarm(HWND_DESKTOP, WA_WARNING);
	    WinMessageBox(HWND_DESKTOP,NULLHANDLE,
		"Please put ASTEROID.DLL in a directory in your LIBPATH.",
		"Error reading ASTEROID.DLL",
		0,MB_ICONHAND|MB_OK|MB_APPLMODAL);
	    WinPostMsg(hwnd,WM_QUIT,(MPARAM) 0L,(MPARAM) 0L);
	    return (MRESULT) TRUE;
	    }

        /* Register/create logical fonts for use */
	InitFonts(hps);

	/* Display About dialoge box */
	WinDlgBox(HWND_DESKTOP, hwnd, (PFNWP)AboutDlgProc, NULLHANDLE,
		  IDD_ABOUT, NULL);

	return 0;

      /* Recieved during attract mode when user starts game */
      case WM_STARTGAME:
        /* Determine the number of players */
	cPlayers = (INT)LONGFROMMP(mp1);

        /* Initialize each player */
	for (Player=0;Player<cPlayers;Player++) {
	    Level[Player] = 1;
	    Ships[Player] = prfProfile.iSHIPS;
	    DeletePhotons();
	    InitAsteroids();
	    InitEnemy();
	    }

        /* Start with player 1 */
	Player = 0;
	iGameMode = GAME_MODE_NEXT;
	iGameModeCnt = GAME_PAUSE_TIME-1;

	/* Hide the pointer if mouse controls are enabled */
	ShowMouse(FALSE);
        
        /* Paint everything */
	WinSendMsg(hwnd, WM_PAINT, MPVOID, MPVOID);

	return 0;

      /* Recieved at startup and at the completion of a game */
      case WM_INITGAME:
        /* Make mouse visible if we hid it before */
        ShowMouse(TRUE);
        
	/* Fix menu to reflect attract mode */
	EnableMenuItem(hwndMenu, IDM_START, TRUE);
	EnableMenuItem(hwndMenu, IDM_STOP, FALSE);

	/* Initialize player and enemy data structures */
	cPlayers = 0;
	Level[0] = 1;
	for (Player=0;Player<2;Player++) {
	    Score[Player] = 0L;
	    Ships[Player] = 0;
	    DeletePhotons();
	    }
	Player = 0;

	/* Initialize asteroids (and enemy) for attract mode */
	InitAsteroids();
	InitEnemy();

        /* Depending on whether ASTEROID was just started or a game just  *
         *   completed display the "High Score" or "Press 1 or 2" screen. */
	if (SHORT1FROMMP(mp1) == 0) {
	    iGameMode = GAME_MODE_INIT1;
	    iGameModeCnt = GAME_INIT_TIME;
	    }
	else {
	    iGameMode = GAME_MODE_INIT2;
	    iGameModeCnt = GAME_INIT_TIME;
	    }

        /* Paint everything */
	WinSendMsg(hwnd, WM_PAINT, MPVOID, MPVOID);
	return 0;

      /* Usually recieved from the system, sometime forced by the program to *
       *   ensure the screen is not corrupt.                                 */
      case WM_PAINT:
	/* Clear entire window to insure no "droppings" */
	WinQueryWindowRect(hwnd,&rcl);
        WinFillRect(hps, &rcl, CLR_BLACK);
	WinInvalidateRect(hwnd, &rcl, FALSE);

	/* Get the update region and paint it black */
	hpsPaint = WinBeginPaint(hwnd, (HPS)NULL, &rcl);
	WinFillRect(hpsPaint, &rcl, CLR_BLACK);
	WinEndPaint(hpsPaint);

        /* Only in normal play mode should we draw the ship */
	if ((iGameMode == GAME_MODE_PLAY) &&
	    (iShipMode[Player] != EXPLOSION) &&
	    (iShipMode[Player] != HYPERSPACE))
	    DrawShip(hps, cx, cy, DRAW_INIT);
	else if ((iGameMode == GAME_MODE_PLAY) &&
		 (iShipMode[Player] == EXPLOSION))
	    ExplodeShip(hps, cx, cy);

        /* Draw the enemy if it is on the screen */
	if (iEnemyMode[Player] != NONE)
	    if (iEnemyMode[Player] != EXPLOSION)
		DrawEnemy(hps, cx, cy,DRAW_INIT);
	    else
		ExplodeEnemy(hps, cx, cy);

        /* Draw photons and asteroids in all modes but the "Enter your *
         *   initials" mode, otherwise draw that screen.               */
	if (iGameMode != GAME_MODE_HIGH) {
	    DrawPhotons(hps, cx, cy, DRAW_INIT);
	    DrawAsteroids(hps, cx, cy, DRAW_INIT);
	    }
	else
	    DrawHighScore(hps, cx, cy, DRAW_INIT);

        /* Always draw the score */
	DrawScore(hps, cx, cy, DRAW_INIT);

	return 0;

      /* Left mouse button down.  This simulates the move/track function *
       *   in the system menu.                                           */
      case WM_BUTTON1DOWN:
        if (prfProfile.bMOUSECONTROL &&
            iGameMode != GAME_MODE_INIT1 &&
            iGameMode != GAME_MODE_INIT2 &&
            !TogglePause(CHECK)) {
	    UPDATE_FIRE(iShipMode[Player], TRUE);
            return (MRESULT)TRUE;
        }
	return WinSendMsg(hwndFrame, WM_TRACKFRAME,
			 (MPARAM) (SHORT1FROMMP(mp2) | TF_MOVE), MPVOID);

      case WM_BUTTON1UP:
        if (prfProfile.bMOUSECONTROL) {
	    UPDATE_FIRE(iShipMode[Player], FALSE);
            return (MRESULT)TRUE;
        }
        return 0;
        
      /* Left mouse button double clicked.  Toggle frame control display. */
      case WM_BUTTON1DBLCLK:
        if (!prfProfile.bMOUSECONTROL ||
            iGameMode == GAME_MODE_INIT1 ||
            iGameMode == GAME_MODE_INIT2 ||
            TogglePause(CHECK)) {
            if (prfProfile.bCONTROLS = !prfProfile.bCONTROLS)
	    	ShowFrameControls();
            else
	    	HideFrameControls();
        }
	return 0;

      case WM_BUTTON2DOWN:
        if (prfProfile.bMOUSECONTROL) {
	    UPDATE_SHIELD(iShipMode[Player], iShipShieldCnt[Player]);
            return (MRESULT)TRUE;
        }
        return 0;
        
      case WM_BUTTON2CLICK:
        if (prfProfile.bMOUSECONTROL) {
            UPDATE_HYPERSPACE(iShipMode[Player], iShipModeCnt[Player]);
            return (MRESULT)TRUE;
        }
        return 0;
        
      /* Right mouse button double clicked.  Display the about dialog box. */
      case WM_BUTTON2DBLCLK:
        if (!prfProfile.bMOUSECONTROL ||
            iGameMode == GAME_MODE_INIT1 ||
            iGameMode == GAME_MODE_INIT2 ||
            TogglePause(CHECK)) {
            WinDlgBox(HWND_DESKTOP, hwndClient, (PFNWP)AboutDlgProc,
            	      NULLHANDLE, IDD_ABOUT, NULL);
        }
	return 0;

      /* User typed a key.  Most of this is self explanatory. */
      case WM_CHAR:
	ProcessChar((CHAR) (CHARMSG(&msg)->vkey-1),
		    CHARMSG(&msg)->fs & KC_VIRTUALKEY,
		    (CHAR) (CHARMSG(&msg)->chr),
		    (BOOL) !(CHARMSG(&msg)->fs & KC_KEYUP));
	return 0;

      /* User entered a command via the menu bar. */
      case WM_COMMAND:
	DoCommand(hwnd, msg, mp1, mp2);
	return 0;

      /* Suspend/un-suspend game depending on focus */
      case WM_SETFOCUS:
	if ((BOOL) SHORT1FROMMP(mp2))
	    TogglePause(SUSPEND_OFF);
	else if (!prfProfile.bBACKGRND)
	    TogglePause(SUSPEND_ON);
	return 0;

      /* Keep track of the client window size.  Profile information is not *
       *   updated here because there are better places (i.e. at exit)     */
      case WM_SIZE:
	cx = (INT)SHORT1FROMMP(mp2);
	cy = (INT)SHORT2FROMMP(mp2);

      /* Keep track of client window position.  Also updates profile info. */
      case WM_MOVE:
	WinQueryWindowPos(hwndFrame,&swp);
	if (!(swp.fl & SWP_MAXIMIZE) && !(swp.fl & SWP_MINIMIZE)) {
	    prfProfile.x  = swp.x;prfProfile.y   = swp.y;
	    prfProfile.cx = swp.cx;prfProfile.cy = swp.cy;
	    }

	if (swp.fl & SWP_MINIMIZE)
	    if (!prfProfile.bBACKGRND) {
		/* Set icon */
		WinSendMsg(hwndFrame, WM_SETICON,
		    (MPARAM) WinLoadPointer(HWND_DESKTOP, NULLHANDLE,
					    ID_RESOURCE), MPVOID);

		TogglePause(SUSPEND_ON);
		}
	    else
		WinSendMsg(hwndFrame, WM_SETICON, MPVOID, MPVOID);
	else
	    TogglePause(SUSPEND_OFF);

	ptlCenter.x = swp.cx / 2;
        ptlCenter.y = swp.cy / 2;
        WinMapWindowPoints(hwndClient, HWND_DESKTOP, &ptlCenter, 1L);

	return 0;

      /* Recieved approximately 31 times a second.  This is the longest and *
       *   ugliest of the messages, partly because there are so many cases  *
       *   to keep track of, partly because it must be highly optimized.    */
      case WM_TIMER:
        if (prfProfile.bMOUSECONTROL &&
            iGameMode != GAME_MODE_INIT1 &&
            iGameMode != GAME_MODE_INIT2) {                   POINTL ptl;
            static BOOL   bUp, bLeft, bRight;

            WinQueryPointerPos(HWND_DESKTOP, &ptl);
            if (bUp || (ptl.y - ptlCenter.y > 0))
	       	UPDATE_THRUST(iShipMode[Player],
            		      bUp = (ptl.y - ptlCenter.y > 0));
            if (bLeft || (ptlCenter.x - ptl.x > 0))
                UPDATE_LEFT(iShipMode[Player],
                	    bLeft = (ptlCenter.x - ptl.x > 0));
            if (bRight || (ptlCenter.x - ptl.x < 0))
                UPDATE_RIGHT(iShipMode[Player],
                 	     bRight = (ptlCenter.x - ptl.x < 0));
            WinSetPointerPos(HWND_DESKTOP, ptlCenter.x, ptlCenter.y);
        }
        
        /* Determine the current game mode */
	switch (iGameMode) {

          /* Either initialization/attract mode screen. */
	  case GAME_MODE_INIT1: case GAME_MODE_INIT2:
            /* Switch screens when count expires */
	    if (--iGameModeCnt == 0) {
		if (iGameMode == GAME_MODE_INIT1)
		    iGameMode = GAME_MODE_INIT2;
		else
		    iGameMode = GAME_MODE_INIT1;
		iGameModeCnt = GAME_INIT_TIME;

                /* Score must be redrawn because the attract mode screens *
                 *   draw the score differently.                          */
		DrawScore(hps, cx, cy, DRAW_REINIT);
		}

            /* Update photons, asteroids, enemy, and score */
	    UpdatePhotons(hps, cx, cy);
	    if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		UpdateAsteroids(hps, cx, cy);
		UpdateEnemy(hps, cx, cy);
		DrawScore(hps, cx, cy, DRAW_REFRESH);
		}
	    break;

          /* Completion of one player's turn or new game */
	  case GAME_MODE_NEXT:
            /* Initially, erase and redraw everything for new player */
	    if (iGameModeCnt-- == GAME_PAUSE_TIME) {
		if ((cPlayers == MAXPLAYERS) &&
                    (Ships[(Player+1) % MAXPLAYERS])) {
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);
		    DrawPhotons(hps, cx, cy, DRAW_ERASE);
		    Player = (Player+1) % MAXPLAYERS;
		    }
		DrawScore(hps, cx, cy, DRAW_REINIT);
		DrawAsteroids(hps, cx, cy, DRAW_INIT);
		}
            /* During countdown update score and asteroids */
	    else if (iGameModeCnt > 0) {
		if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		    UpdateAsteroids(hps, cx, cy);
		    }
		}
            /* At end of countdown start the player */
	    else {
		InitShip();
		InitEnemy();
		iGameMode = GAME_MODE_PLAY;
		DrawScore(hps, cx, cy, DRAW_REINIT);
		}
	    break;

          /* Normal play mode */
	  case GAME_MODE_PLAY:
            /* Update ship, photons, asteroids, enemy, and score */
	    UpdateShip(hps, cx, cy);
	    UpdatePhotons(hps, cx, cy);
	    if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		UpdateAsteroids(hps, cx, cy);
		UpdateEnemy(hps, cx, cy);
                /* Erase old and draw new scores if there is a change*/
		if (bChangeScore) {
		    bChangeScore = FALSE;
		    DrawScore(hps, cx, cy, DRAW_REINIT);
		    }
                /* Else just refresh the score */
		else
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		}
	    break;

          /* Game over mode.  This is the longest and ugliest case because  *
           *   conditions are highly dependent on the number of players,    *
           *   multiplayer game status, and the number and order of high    *
           *   scores.                                                      */
	  case GAME_MODE_OVER:
            /* Initially, just update the score and number of ships */
	    if (iGameModeCnt-- == GAME_PAUSE_TIME)
		DrawScore(hps, cx, cy, DRAW_REINIT);

            /* During countdown refresh the score and update the asteroids */
	    else if (iGameModeCnt > 0) {
		if (uiSpeed == SPEED_OS2 || (bSlowUpdateNow = !bSlowUpdateNow)) {
		    DrawScore(hps, cx, cy, DRAW_REFRESH);
		    UpdateAsteroids(hps, cx, cy);
		    }
		}

            /* At the end of the countdown, if there are any other players, *
             *   continue with them.                                        */
	    else {
                /* Countinue on with any remaining players. */
		if ((cPlayers == MAXPLAYERS) &&
                    (Ships[(Player+1) % MAXPLAYERS])) {
                    /* Erase all of the old asteroids. */
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);

                    /* Setup everything for the next player */
		    Player = (Player+1) % MAXPLAYERS;
		    InitShip();
		    InitEnemy();
		    iGameMode = GAME_MODE_PLAY;
		    DrawAsteroids(hps, cx, cy, DRAW_INIT);
		    DrawScore(hps, cx, cy, DRAW_REINIT);
		    }

                /* Check for new high scores and update table as necessary. */
		else {
                    /* Erase all of the old asteroids. */
		    DrawAsteroids(hps, cx, cy, DRAW_ERASE);


                /* The following if/else block is admittedly a kludge, it is *
                 *   simple and it does work, however.  Ideally it should    *
                 *   sort the high scores and update the high score table in *
                 *   descending order.                                       */

                    /* If player 1 scored higher than player 2 then check *
                     *   player 1 first for a high score.                 */
       		    if (Score[0] > Score[1])
			for (Player=0;Player<cPlayers;Player++)
                            /* If the player's score is > than the lowest, *
                             *   update the high score table.              */
			    if (Score[Player] > prfProfile.lSCORES[9]) {
				UpdateHighScores();
				iGameMode = GAME_MODE_HIGH;
				}
                            /* Otherwise, make sure he is not asked for his *
                             *   initials.                                  */
			    else
				Score[Player] = 0;

                    /* Otherwise, check player 2 first */
		    else
			for (Player=cPlayers;Player>=0;Player--)
                            /* If the player's score is > than the lowest, *
                             *   update the high score table.              */
			    if (Score[Player] > prfProfile.lSCORES[9]) {
				UpdateHighScores();
				iGameMode = GAME_MODE_HIGH;
				}
                            /* Otherwise, make sure he is not asked for his *
                             *   initials.                                  */
			    else
				Score[Player] = 0L;

                    /* If there was no high score, go into attract mode */
		    if (iGameMode != GAME_MODE_HIGH)
			WinSendMsg(hwnd,WM_INITGAME,MPFROMSHORT(1),(MPARAM) 0L);
                    /* Else, check for player 1's initials first then 2's   *
                     * This is not faithful, in the arcade game the player  *
                     *   with the higher score always goes first.           */
		    else {
			if (Score[0] > 0L)
			    Player = 0;
			else
			    Player = 1;
			DrawScore(hps, cx, cy, DRAW_REINIT);
			DrawHighScore(hps, cx, cy, DRAW_INIT);
			}
		    }
		}
	    break;

          /* Mode which prompts players to enter their initials */
	  case GAME_MODE_HIGH:
            /* If the player's position is > 0 then refresh the screen */
	    if (Score[Player] > 0L)
		DrawHighScore(hps, cx, cy, DRAW_REFRESH);
            /* Else, the current player is done go to the next */
	    else if ((cPlayers == MAXPLAYERS) && (Player == 0) &&
		     (Score[1] > 0L)) {
		Player++;
		DrawHighScore(hps, cx, cy, DRAW_REINIT);
		}
            /* If there are no more high scores then go into attract mode */
	    else
		WinSendMsg(hwnd, WM_INITGAME, MPFROMSHORT(1), MPVOID);
	    break;
	  }
	return 0;

      /* Used by help manager */
      case HM_QUERY_KEYS_HELP:
	 return((MRESULT)IDH_CLIENTKEYS);

      /* Recieved always from the system or in the case of an initialization*
       *   error.  Both messages will normally save the profile information.*
       * Ideally the profile section should be moved to a subroutine and the*
       *   the following should be broken into two distinct cases.	    */
      case WM_SAVEAPPLICATION:
      case WM_DESTROY:
	/* If the fonts were not found bApplicationOk will be false, in     *
	 *   that case the window profile information should not be updated.*/
	if (TRUE) {
	    /* Copy window position and size info into profile structure */
	    WinQueryWindowPos(hwndFrame, &swp);
	    if (swp.fl & SWP_MAXIMIZE)
		prfProfile.ulMINMAX = SWP_MAXIMIZE;
	    else if (swp.fl & SWP_MINIMIZE)
		prfProfile.ulMINMAX = SWP_MINIMIZE;
	    else {
		prfProfile.ulMINMAX = 0;
		prfProfile.x  = swp.x;prfProfile.y   = swp.y;
		prfProfile.cx = swp.cx;prfProfile.cy = swp.cy;
		}

	    /* Write profile information */
	    PrfWriteProfileData(HINI_USERPROFILE, szClientClass, "Data",
		&prfProfile, sizeof(PROFILEREC));
	    }

        /* If the application is terminating release the fonts and the hps. */
        if (msg == WM_DESTROY) {
	    /* Make sure mouse is visible if we hid it before */
            ShowMouse(TRUE);
            
	    /* Release font identifiers and DLL resource module */
	    GpiSetCharSet(hps, LCID_DEFAULT);
	    GpiDeleteSetId(hps, LCID_LARGE);
	    GpiDeleteSetId(hps, LCID_SMALL);
	    GpiUnloadFonts(hab, "ASTEROID");

	    /* Release the "permanent" presentation space */
	    WinReleasePS(hps);
            }
	return 0;

      }
    return WinDefWindowProc(hwnd, msg, mp1, mp2);
}
Ejemplo n.º 5
0
void Model_Level4::UpdateGame(double dt, bool* myKeys)
{
	//cout << triggerObject[7]->getPosition() << endl;
	if (stopGame == false)
	{
		// Sound - ambience
		sfx_man->play_ambience();

		//Update enemy
		UpdateEnemy(dt);

		/* Update player */
		player->Update(dt, myKeys);
		
		//Update the traps
		UpdateTraps(dt, myKeys);

		/* check collision with object */
		//start: Set up collision bound before checking with the others
		player->StartCollisionCheck();

		/* check collision with map */
		for (int i = 0; i < level_map->size(); i++)
		{
			if ((*level_map)[i]->getMapType() == Map::COLLISIONMAP)
			{
				if ((*level_map)[i]->CheckCollisionWith(player)) //check collision with player
				{
					
				}
			}
		}

		//Collision check with triggers
		for (int i = 0; i < 2; i++)
		{
			if (doors[i]->getActive())
			{
				if (player->CollisionCheck(doors[i]))
				{
					if (i == 0 && firstKey == true)
					{
						doors[i]->setActive(false);
						sfx_man->play_unlock();
					}
					else if (i == 1 && secondKey == true)
					{
						doors[i]->setActive(false);
						sfx_man->play_unlock();
					}
				}
			}
		}

		//Item pickup
		for (int i = 0; i < itemList.size(); ++i)
		{
			if (player->pickUp(itemList[i], myKeys))	//if successfully pick up
			{
				//if item is key
				//cout << itemList[i]->getItemID() << endl;
				if (itemList[i]->getItemID() == Item::NOTE)
				{
					puzzleManager->goToNextPart();
				}
			}
		}

		/*** Change to next level ***/
		mapTimer += dt;
		if (player->CollisionCheck(staircases[0]))
		{
			if (mapTimer > 5)
			{
				goNextLevel = true;
				mapTimer = 0;
			}
		}
		if (player->CollisionCheck(staircases[1]))
		{
			if (mapTimer > 5)
			{
				goPreviousLevel = true;
				mapTimer = 0;
			}
		}

		/* see if click at trigger area to get hidden key and message */
		if (keyPressedTimer >= delayTime)
		{
			if (myKeys[KEY_E])
			{
				keyPressedTimer = 0.0;
				keyActiveArea[0].QuickAABBDetection(player->getCollideBound(), true);
				keyActiveArea[1].QuickAABBDetection(player->getCollideBound(), true);
			}
		}

		/* if activated: get key and puzzle */
		if (keyActiveArea[0].getActivated() && firstKey == false)
		{
			firstKey = true;
			keys[0]->setActive(true);
			player->getInventory()->addItem(keys[0]);	//note 
			puzzleManager->goToNextPart();
		}
		if (keyActiveArea[1].getActivated() && secondKey == false)
		{
			secondKey = true;
			keys[1]->setActive(true);
			player->getInventory()->addItem(keys[1]);	//note 
			puzzleManager->goToNextPart();
		}
		
		player->useItem(myKeys);
		player->dropItem(dt, item, myKeys);

		/* Update target */
		camera.target = camera.position;
		camera.target.z -= 10;

		/* Press space to go back main menu */
		if (myKeys[KEY_SPACE] && keyPressedTimer >= delayTime)
		{
			keyPressedTimer = 0.0;
			//stateManager->ChangeState(stateManager->MAIN_MENU);
		}

		player->getCollideBound()->Reset();

		/* Collision response */
		player->CollisionResponse();	//translate to new pos if collides

		/* Key Q to open puzzle */
		static bool ButtonQState = false;
		if (!ButtonQState && myKeys[KEY_Q])
		{
			ButtonQState = true;
			std::cout << "QBUTTON DOWN" << std::endl;
			puzzleOpen = true;
		}
		else if (ButtonQState && !(myKeys[KEY_Q]))
		{
			ButtonQState = false;
			std::cout << "QBUTTON UP" << std::endl;
			puzzleOpen = false;
		}

		/* GO TO NEXT LEVEL (PRESS B FOR NOW) */
		//Key B to move to next map (RP)
		static bool ButtonBState = false;
		if (!ButtonBState && myKeys[KEY_B])
		{
			ButtonBState = true;
			goNextLevel = true;	//go to next level
			std::cout << "BBUTTON DOWN" << std::endl;
			//stateManager->ChangeState(StateManager::MAIN_MENU);
			//mapManager->ChangeNextMap();
			//puzzleManager->goToNextPart();
		}
		else if (ButtonBState && !(myKeys[KEY_B]))
		{
			ButtonBState = false;
			std::cout << "BBUTTON UP" << std::endl;
		}

		//Bring up the screen if the player dies ( restart or go back to main menu)
		if (player->getHealth() == 0)
		{
			stopGame = true;
		}
	}
}
bool ServerApp::Loop()
{
	static float timeSinceStart = 0.f;
	double currentTime = RakNet::GetTime(); // Current time by raknet
	double dt = (currentTime - prevTime) * 0.001f; // dt is the time difference between last frame and this frame
	prevTime = currentTime; // After calculating dt, set current time to previous time for next calculation later on

	timeSinceStart += dt;

	// Enemy spawning
	static const float ENEMY_SPAWN_INTERVAL = 2.f;
	static int enemy_spawn_count = 1;
	static float spawnEnemyTimer = ENEMY_SPAWN_INTERVAL;
	enemy_spawn_count = (timeSinceStart * 0.1f) + 1;
	if (clientList.size() > 0)
	{
		if (spawnEnemyTimer < ENEMY_SPAWN_INTERVAL)
		{
			spawnEnemyTimer += dt;
		}
		else
		{
			for (int i = 0; i < enemy_spawn_count; ++i)
			{
				SpawnEnemy();
			}
			spawnEnemyTimer = 0.f;
		}

		UpdateEnemy(dt);
	}

	static const int SYNCS_PER_SEC = 5;
	static const float TIME_PER_SYNC = 1 / SYNCS_PER_SEC;
	static float enemySyncTimer = TIME_PER_SYNC;
	if (enemySyncTimer < TIME_PER_SYNC)
	{
		enemySyncTimer += dt;
	}
	else
	{
		SendEnemy();
		enemySyncTimer = 0.f;
	}


	if (Packet* packet = rakpeer_->Receive())
	{
		RakNet::BitStream bs(packet->data, packet->length, false);
		
		unsigned char msgid = 0;
		RakNetTime timestamp = 0;

		bs.Read(msgid);

		if (msgid == ID_TIMESTAMP)
		{
			bs.Read(timestamp);
			bs.Read(msgid);
		}

		switch (msgid)
		{
		case ID_SET_SCREEN_TO_SERVER: // Set screen position
			{
				std::cout << "Received screen size" << std::endl;
				bs.Read(s_screen_width);
				bs.Read(s_screen_height);
			}
			break;
		case ID_NEW_INCOMING_CONNECTION:
			{
				if (clientList.size() >= 2)
				{
					RejectPlayer(packet->systemAddress);
				}
				else
				{
					SendWelcomePackage(packet->systemAddress);
				}
			}
			break;

		case ID_DISCONNECTION_NOTIFICATION:
		case ID_CONNECTION_LOST:
			SendDisconnectionNotification(packet->systemAddress);
			break;

		case ID_INITIALPOS:
			{
				float x_, y_;
				int type_;
				std::cout << "ProcessInitialPosition" << std::endl;
				bs.Read( x_ );
				bs.Read( y_ );
				bs.Read( type_ );
				ProcessInitialPosition( packet->systemAddress, x_, y_, type_);
			}
			break;

		case ID_MOVEMENT:
			{
				float x, y;
				unsigned int shipid;
				bs.Read(shipid);
				bs.Read(x);
				bs.Read(y);
				UpdatePosition( packet->systemAddress, x, y );

				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;

		case ID_COLLIDE:
			{
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;

		// Lab 13 Task 14 : new cases on server side to handle missiles
		case ID_NEWMISSILE:
			{
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;
		case ID_UPDATEMISSILE:
			{
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;
		case ID_INJURE_ENEMY:
			{
				int id, hp;
				bs.Read(id);
				ServerEnemy* e = FindEnemyByID(id);
				if (e && e->active)
				{
					bs.Read(hp);
					e->hp = hp;
				}

				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;
		case ID_DESTROY_ENEMY:
			{
				int id;
				bs.Read(id);
				ServerEnemy* e = FindEnemyByID(id);
				if (e->active)
				{
					ResetEnemy(id);
					bs.ResetReadPointer();
					rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
				}
			}
			break;
			// Server does not interfere with shooting
		case ID_SHOOT:
		case ID_UPDATE_PROJECTILE:
			{
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, true);
			}
			break;
		case ID_DESTROY_PROJECTILE:
			{
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;
		case ID_UPDATE_SCORE:
			{
				int score, id;
				bs.Read(id);
				bs.Read(score);
				ClientMap::iterator it = clients_.find(packet->systemAddress);
				if (it == clients_.end())
					break;

				it->second.score = score;
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE, 0, packet->systemAddress, true);
			}
			break;
		case ID_CHAT_SEND:
			{
				char cMsg[256];
				bs.Read(cMsg);
				chatList.push(cMsg);
				bs.ResetReadPointer();
				rakpeer_->Send(&bs, HIGH_PRIORITY, RELIABLE_ORDERED, 0, packet->systemAddress, true);
			}
			break;

		default:
			std::cout << "Unhandled Message Identifier: " << (int)msgid << std::endl;
		}

		rakpeer_->DeallocatePacket(packet);
	}

	if (base_hp <= 0)
	{
		return true;
	}
	return false;
}
Ejemplo n.º 7
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();
	}
}