/* ================================================================== // This is winmain, the main entry point for Windows applications ================================================================== */ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { // Initialize the window if ( !initWindow( hInstance ) ) return false; // called after creating the window if ( !d3dMgr->initD3DManager(wndHandle) ) return false; if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice())) return false; // Grab the frequency of the high def timer __int64 freq = 0; // measured in counts per second; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); float sPC = 1.0f / (float)freq; // number of seconds per count __int64 currentTime = 0; // current time measured in counts per second; __int64 previousTime = 0; // previous time measured in counts per second; float numFrames = 0.0f; // Used to hold the number of frames float timeElapsed = 0.0f; // cumulative elapsed time GetClientRect(wndHandle,&clientBounds); float fpsRate = 1.0f/25.0f; //variables to hold the monkey, banana and new banana positions D3DXVECTOR3 monkeyPos; D3DXVECTOR3 BananaPos; D3DXVECTOR3 NewPos; //string to hold the score and display on screen sprintf_s( gScoreStr, 50, "Score : %d", gScore); //=========================================================== // load texture for the bananas //=========================================================== for (int txture = 0; txture < 1; txture++) { BananaTextures[txture] = new cD3DXTexture(d3dMgr->getTheD3DDevice(), BananaTxtres[txture]); } //create a texture for the explosion txtExp->createTexture(d3dMgr->getTheD3DDevice(),"Images\\explosion.png"); //create a texture for the monkey cD3DXTexture* txtMonkey = new cD3DXTexture(); txtMonkey->createTexture(d3dMgr->getTheD3DDevice(),"Images\\theMonkey.png"); txtMonkey->setTextureInfo("Images\\theMonkey.png");//set the texture information ie. height, width theMonkey.setTranslation(D3DXVECTOR2(0.0f, 0.0f));//set the translation of the monkey theMonkey.setTexture(txtMonkey);//apply the texture to the monkey theMonkey.update();//update the monkey sprite /* initialize random seed: */ srand ( (unsigned int)time(NULL) ); //integer to hold the number of bananas int numBananas = 1; for(int loop = 0; loop < numBananas; loop++)//for each banana set the position, direction, speed and texture { BananaPos = D3DXVECTOR3((float)clientBounds.right/(2),(float)clientBounds.top-100,0); aBanana.push_back(new cBanana()); aBanana[loop]->setSpritePos(BananaPos); aBanana[loop]->setTranslation(D3DXVECTOR2(0.0f,speed)); aBanana[loop]->setTexture(BananaTextures[loop]); } LPDIRECT3DSURFACE9 TitleSurface;//the title surface LPDIRECT3DSURFACE9 GameSurface; //the main game background LPDIRECT3DSURFACE9 GameOverSurface; // the game over surface LPDIRECT3DSURFACE9 theBackbuffer = NULL; // This will hold the back buffer MSG msg; ZeroMemory( &msg, sizeof( msg ) ); // Create the background surface TitleSurface = d3dMgr->getD3DSurfaceFromFile("Images\\TitleScreen.png"); GameSurface = d3dMgr->getD3DSurfaceFromFile("Images\\GameBackground.png"); GameOverSurface = d3dMgr->getD3DSurfaceFromFile("Images\\GameOverSurface.png"); // load custom font cD3DXFont* balloonFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "SNAP_"); //rectangle to hold the score during gameplay RECT textPos; SetRect(&textPos, 50, 10, 400, 100); //rectangle to hold the score on the gameover screen RECT textPos2; SetRect(&textPos2, 250, 250, 600, 400); QueryPerformanceCounter((LARGE_INTEGER*)&previousTime); while( msg.message!=WM_QUIT ) { // Check the message queue if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { // Game code goes here QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); float dt = (currentTime - previousTime)*sPC; // Accumulate how much time has passed. timeElapsed += dt; if(timeElapsed > fpsRate) { //start rendering d3dMgr->beginRender(); if(mouseClicks==0)//if mouseClicks is equal to zero { theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(TitleSurface, theBackbuffer);//apply the title surface d3dMgr->releaseTheBackbuffer(theBackbuffer); gameOver=false;//set gameOver to false gScore = 0;//set gScore to zero sprintf_s( gScoreStr, 50, "Score : %d", gScore);//set the score string with zero } else { if(bananaSquash == 3)//if bananaSquash is equal to three { gameOver = true;//set gameOver to mouseClicks = -1;// set mouseClicks to negative one bananaSquash = 0;//set bananaSquash to zero speed = 50.0f;//set the speed to 50 } else { if(gameOver == true)//if gameOver is true { theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(GameOverSurface, theBackbuffer);//apply the game over surface d3dMgr->releaseTheBackbuffer(theBackbuffer); sprintf_s( gScoreStr, 50, "You Scored : %d", gScore);//update the score balloonFont->printText(gScoreStr,textPos2);//print the score on the gameOver surface } else { vector<cBanana*>::iterator iterBanana = aBanana.begin(); while(iterBanana != aBanana.end()) { (*iterBanana)->update(timeElapsed); // update banana BananaPos = (*iterBanana)->getSpritePos();//get the position of the banana if((*iterBanana)->collidedWith((*iterBanana)->getBoundingRect(), theMonkey.getBoundingRect())) //check if monkey and banana have collided { OutputDebugString("Collision!!");//if they have collided output collision iterBanana = aBanana.erase(iterBanana);//delete banana gScore++;//increment the score sprintf_s( gScoreStr, 50, "Score : %d", gScore);//update the score string speed = speed+3;//add three to the speed gMonkeySound.playSound(L"Sounds\\monkeySound2.wav",false);//play monkey sound effect } else { if (BananaPos.y >(clientBounds.bottom-60 ))//if the banana hits the floor { expPos = (*iterBanana)->getSpritePos();//get the banana position gExplode.push_back(new cExplosion(expPos,txtExp)); //play explosion animation at same position as banana gExplodeSound.playSound(L"Sounds\\explosion.wav",false);//play explosion sound iterBanana = aBanana.erase(iterBanana);//delete the banana OutputDebugString("Collision!!");//output collision bananaSquash++;//increment bananaSquash } else { ++iterBanana;// increment the iterator OutputDebugString("ITERBanana");//display ITERbanana } } } int vSize=aBanana.size();//integer to hold the size of aBanana BananaPos = aBanana[vSize-1]->getSpritePos();//variable to hold the position of the banana if(BananaPos.y>(clientBounds.bottom-300))//check if the banana has fallen past about 3 quarters of the way down the screen { int xPos = (rand() % 600 + 1);//integer variable to hold a random number for the new bananas x-position NewPos = D3DXVECTOR3((float)xPos,(float)clientBounds.top-100,0);//variable to hold new bananas starting position aBanana.push_back(new cBanana());//create a new banana vSize=aBanana.size();//get the size of aBanana aBanana[vSize-1]->setSpritePos(NewPos);//set the position for the new banana aBanana[vSize-1]->setTranslation(D3DXVECTOR2(0.0f,speed));//set the speed and direction of the new banana aBanana[vSize-1]->setTexture(BananaTextures[0]);//apply a texture to the new banana } monkeyPos = D3DXVECTOR3(monkeyTrans.x,monkeyTrans.y,0);//variable to hold the position of the monkey theMonkey.setSpritePos(monkeyPos);//set the position of the monkey theMonkey.update();//update the monkey sprite theBackbuffer = d3dMgr->getTheBackBuffer();//retrieve the backbuffer d3dMgr->updateTheSurface(GameSurface, theBackbuffer);//apply the game surface d3dMgr->releaseTheBackbuffer(theBackbuffer);//release the backbuffer d3dxSRMgr->beginDraw();//start drawing the window d3dxSRMgr->setTheTransform(theMonkey.getSpriteTransformMatrix());//set the position of the monkey sprite d3dxSRMgr->drawSprite(theMonkey.getTexture(),NULL,NULL,NULL,0xFFFFFFFF);// draw the monkey vector<cBanana*>::iterator iterB = aBanana.begin(); for(iterB = aBanana.begin(); iterB != aBanana.end(); ++iterB)//for each banana in aBanana { d3dxSRMgr->setTheTransform((*iterB)->getSpriteTransformMatrix()); //set the position of the banana d3dxSRMgr->drawSprite((*iterB)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF);//draw the banana } list<cExplosion*>::iterator iter = gExplode.begin();//set the iterator to begin while(iter != gExplode.end())//while the iterator is not set to end { if((*iter)->isActive() == false)//if the iterator is not active { iter = gExplode.erase(iter);//delete the explosion } else { (*iter)->update(timeElapsed); d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix()); //set the position for the explosion d3dxSRMgr->drawSprite((*iter)->getTexture(),&((*iter)->getSourceRect()),NULL,NULL,0xFFFFFFFF);//draw the explosion ++iter;//increment iter } } balloonFont->printText(gScoreStr,textPos);//print the score } } d3dxSRMgr->endDraw();//finish drawing } d3dMgr->endRender();//finish rendering OutputDebugString("timeElapsed > fpsRate"); timeElapsed = 0.0f;//set timeElapsed to zero } previousTime = currentTime; /* StringCchPrintf(szTempOutput, 30, TEXT("dt=%f\n"), dt); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("timeElapsed=%f\n"), timeElapsed); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("previousTime=%u\n"), previousTime); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("fpsRate=%f\n"), fpsRate); OutputDebugString(szTempOutput); */ } } d3dxSRMgr->cleanUp(); d3dMgr->clean(); return (int) msg.wParam; }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // Check any available messages from the queue switch (message) { case WM_KEYDOWN: { if (wParam == VK_LEFT) { playerTrans.x -= 5.0f; return 0; } if (wParam == VK_RIGHT) { playerTrans.x += 5.0f; return 0; } if (wParam == VK_UP) { playerTrans.y -= 5.0f; return 0; } if (wParam == VK_DOWN) { playerTrans.y +=5.0f; return 0; } return 0; } case WM_LBUTTONDOWN: { POINT mouseXY; mouseXY.x = LOWORD(lParam); mouseXY.y = HIWORD(lParam); expPos = D3DXVECTOR3((float)mouseXY.x,(float)mouseXY.y, 0.0f); iter = aBalloon.begin(); while (iter != aBalloon.end() && !gHit) { if ( (*iter)->insideRect((*iter)->getBoundingRect(),mouseXY)) { OutputDebugString("Hit!\n"); gHit = true; expPos = (*iter)->getSpritePos(); gExplode.push_back(new cExplosion(expPos,balloonTextures[3])); gExplodeSound.playSound(L"Sounds\\explosion.wav",false); iter = aBalloon.erase(iter); gBalloonsBurst++; sprintf_s( gBalloonsBurstStr, 50, "Zombies Killed : %d", gBalloonsBurst); } else { ++iter; } } gHit = false; return 0; } case WM_CLOSE: { // Exit the Game PostQuitMessage(0); return 0; } case WM_DESTROY: { PostQuitMessage(0); return 0; } } // Always return the message to the default window // procedure for further processing return DefWindowProc(hWnd, message, wParam, lParam); }
/* ================================================================== * LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, * LPARAM lParam) * The window procedure ================================================================== */ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // Check any available messages from the queue //This part of the code is activated by user inputs. switch (message) { //Used when a key is pressed case WM_KEYDOWN: { //When the level is active if(Menu==false){ //if the escape key is pressed if (wParam ==VK_ESCAPE) { //Deletes all the remaining bats. iterBat = aBat.begin(); while (iterBat != aBat.end()) { iterBat = aBat.erase(iterBat); } iter = aPlatform.begin(); //Deletes all of the platforms. while (iter != aPlatform.end()) { iter = aPlatform.erase(iter); } //Deletes the knight. list<cKnight*>::iterator bite = gKnight.begin(); bite = gKnight.erase(bite); //adds a button and changes the background. D3DXVECTOR3 PlatformPosing = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0); aPlatform.push_back(new cPlatform(PlatformPosing,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png")); backgroundName="Images\\Background.png"; aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); Menu=true; finish=true; return 0; } // if the left key is pressed if (wParam == VK_LEFT) { //Gives all of the platforms a velocity to the right. for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { if ((*iter)->getTranslation().x<10.0f) { (*iter)->setTranslation(D3DXVECTOR2(20.0f ,0.0f)); } } //Gives all the remaining bats a velocity to the right. for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat) { if ((*iterBat)->getTranslation().x<10.0f) { (*iterBat)->setTranslation(D3DXVECTOR2(20.0f ,0.0f)); } } } // if the right key is pressed if (wParam == VK_RIGHT) { //Gives all of the platforms a velocity to the left. for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { if ((*iter)->getTranslation().x>-10.0f) { (*iter)->setTranslation(D3DXVECTOR2(-20.0f ,0.0f)); } } //Gives all the remaining bats a velocity to the left. for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat) { if ((*iterBat)->getTranslation().x>-10.0f) { (*iterBat)->setTranslation(D3DXVECTOR2(-20.0f ,0.0f)); } } } //if the up key is pressed and the knight is not falling if (wParam == VK_UP && !falling) { //Moves the knight up. knightTrans.y -= 50.0f; } } return 0; } //when the level is active. if (Menu==false){ //when a key is released case WM_KEYUP: { //if the left key is lifted if (wParam ==VK_LEFT) { //Stops the platforms. for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { (*iter)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); } //Stops the bats. for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat) { (*iterBat)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); } } //if the right key is lifted if (wParam == VK_RIGHT) { //Stops the platforms. for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { (*iter)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); } //Stops the bats. for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat) { (*iterBat)->setTranslation(D3DXVECTOR2(0.0f ,0.0f)); } } //if the up key is lifted makes falling true. if (wParam == VK_UP){falling=true;} return 0; } } //when the left mouse button is clicked. case WM_LBUTTONDOWN: { POINT mousexy; //The point that the mouse clicked is recorded mousexy.x = LOWORD(lParam); mousexy.y = HIWORD(lParam); //if menu is true and the point is within a defined area. if (Menu==true&&mousexy.x>(clientBounds.right/2-100)&&mousexy.x<(clientBounds.right/2+100)&&mousexy.y>(clientBounds.bottom/2-50)&&mousexy.y<(clientBounds.bottom/2+50)) { if(finish==false) { //Deletes the button. iter = aPlatform.begin(); while (iter != aPlatform.end()) { iter = aPlatform.erase(iter); } //Applies the game background. backgroundName="Images\\SkyBackgroundSmall.png"; aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); Menu=false; start=true; return 0; } if(finish==true) { //places a button. D3DXVECTOR3 PlatformPoser = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0); aPlatform.push_back(new cPlatform(PlatformPoser,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png")); //Sets the background to the menu screen. backgroundName="Images\\eulogyPlus.png"; aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); sprintf_s( gMenu, 50, "Play"); sprintf_s( gScore, 100, ""); finish=false; return 0; } } if (Menu==false) { iterBat = aBat.begin(); while (iterBat != aBat.end()) { //if the point is on a bat if ( (*iterBat)->insideRect((*iterBat)->getBoundingRect(),mousexy)) { //Deletes the bat. iterBat = aBat.erase(iterBat); //make an explosion at the point clicked expPos = D3DXVECTOR3((float)mousexy.x-25,(float)mousexy.y-23, 0.0f); gExplode.push_back(new cExplosion(expPos,d3dMgr->getTheD3DDevice(),"Images\\explosionblood.png")); //Plays a splat sound effect. gExplodeSound.playSound(L"Sounds\\Splat.wav",false); scor+=10; iterBat = aBat.end(); } else { ++iterBat; } } } return 0; } //if the application has been closed. case WM_CLOSE: { // Posts close message PostQuitMessage(0); return 0; } //f the application has been destroyed. case WM_DESTROY: { // Posts close message PostQuitMessage(0); return 0; } } // Always return the message to the default window // procedure for further processing return DefWindowProc(hWnd, message, wParam, lParam); }
/* ================================================================== // This is winmain, the main entry point for Windows applications ================================================================== */ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { // Initialize the window if ( !initWindow( hInstance ) ) return false; // called after creating the window if ( !d3dMgr->initD3DManager(wndHandle) ) return false; if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice())) return false; //declare variables to measure the time between frames. // Grab the frequency of the high def timer __int64 freq = 0; // measured in counts per second; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); float sPC = 1.0f / (float)freq; // number of seconds per count __int64 currentTime = 0; // current time measured in counts per second; __int64 previousTime = 0; // previous time measured in counts per second; float numFrames = 0.0f; // Used to hold the number of frames float timeElapsed = 0.0f; // cumulative elapsed time GetClientRect(wndHandle,&clientBounds); float fpsRate = 1000.0f/25.0f; /* initialize random seed: */ srand ( (unsigned int)time(NULL) ); scor=0; //Makes an instance of cD3DFont cD3DXFont* KnightFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "Bats&Dragons-Abaddon"); //These two rectangles will hold the text. RECT textPos; SetRect(&textPos, (clientBounds.right/2-30), (clientBounds.bottom/2), 800, 800); RECT buttonPos; SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800); D3DXVECTOR3 PlatformPos; D3DXVECTOR3 BatPos; /* generate random number of Platforms */ int numPlatforms = (50); int numBat = (24); D3DXVECTOR3 knightPos; POINT pknightPos; cXAudio gStartSound; gStartSound.playSound(L"Sounds\\BarbossaIsHungry.wav",false); PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0); aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png")); LPDIRECT3DSURFACE9 theBackbuffer = NULL; // This will hold the back buffer SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800); MSG msg; ZeroMemory( &msg, sizeof( msg ) ); // Create the background surface aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); while( msg.message!=WM_QUIT ) { // Check the message queue if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { //Run once per frame until the application closes. //if the menu is active if (Menu==true && finish==false) { SetRect(&buttonPos, (clientBounds.right/2-20), (clientBounds.bottom/2-20), 800, 800); sprintf_s( gScore, 100, ""); sprintf_s( gMenu, 100, "Start"); } //if the level is active if (Menu==false) { sprintf_s( gScore, 50, ""); sprintf_s( gMenu, 50, ""); } //if starting is true if (start==true) { start=false; scor=0; Health=30; reset the time frame. currentTime = 0; // current time measured in counts per second; previousTime = 0; // previous time measured in counts per second; numFrames = 0.0f; // Used to hold the number of frames timeElapsed = 0.0f; // cumulative elapsed time PlatformTrans = D3DXVECTOR2(300,300); BatTrans = D3DXVECTOR2(300,300); knightTrans = D3DXVECTOR2(250,230); //Create a knight sprite. knightPos = D3DXVECTOR3((float)clientBounds.left/2-200,clientBounds.bottom-360,0); gKnight.push_back(new cKnight(knightPos,d3dMgr->getTheD3DDevice(),"Images\\KnightBodytwo.png",1,11)); //Create all the platforms. for(int loop = 0; loop < numPlatforms; loop++) { PlatformPos = D3DXVECTOR3(clientBounds.right/2-200+(loop*400),(float)clientBounds.bottom-100,0); aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\Platform.png")); aPlatform[loop]->setTranslation(D3DXVECTOR2(0.0f,0.0f)); } //Create all the bats. for(int loop = 0; loop < numBat; loop++) { BatPos = D3DXVECTOR3(clientBounds.right/2+((loop+1)*800),(float)clientBounds.bottom-300,0); aBat.push_back(new cBat(BatPos,d3dMgr->getTheD3DDevice(),"Images\\BatFlipped.png")); aBat[loop]->setTranslation(D3DXVECTOR2(0.0f,0.0f)); } } //if the finish screen is active if (Menu==true && finish==true) { SetRect(&buttonPos, (clientBounds.right/2-45), (clientBounds.bottom/2-20), 800, 800); sprintf_s( gScore, 100, "Your total score was: %d",scor); sprintf_s( gMenu, 50, "Re-Play"); } //Loop through all the remaining bats iterBat = aBat.begin(); while(iterBat != aBat.end()) { // update Bat list<cKnight*>::iterator bite = gKnight.begin(); //if the current bat is touching the knight. if ((*iterBat)->collidedWith((*iterBat)->getBoundingRect(),(*bite)->getBoundingRect())) { Health-=10; expPos = D3DXVECTOR3((*iterBat)->getSpritePos2D().x+105.0f,(*iterBat)->getSpritePos2D().y+95.0f,0.0f); gExplode.push_back(new cExplosion(expPos,d3dMgr->getTheD3DDevice(),"Images\\explosionblood.png")); gExplodeSound.playSound(L"Sounds\\Splat.wav",false); iterBat = aBat.erase(iterBat); if (Health < 1) { //Deletes all the remaining bats. iterBat = aBat.begin(); while (iterBat != aBat.end()) { iterBat = aBat.erase(iterBat); } //Deletes all the platforms iter = aPlatform.begin(); while (iter != aPlatform.end()) { iter = aPlatform.erase(iter); } //Deletes .the Knight list<cKnight*>::iterator bite = gKnight.begin(); bite = gKnight.erase(bite); //Places a button. PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0); aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png")); //Sets the background to the finish screen. backgroundName="Images\\Background.png"; aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); Menu=true; finish=true; iterBat = aBat.end(); } } if (iterBat!=aBat.end()){++iterBat;} } for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { (*iter)->update(); //loops through the platforms updating them. } QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); dt = (currentTime - previousTime)*sPC; // Accumulate how much time has passed. timeElapsed = dt+timeElapsed; if(timeElapsed > fpsRate) { d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(aSurface, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); d3dxSRMgr->beginDraw(); for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) { //run for every platform. d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*iter)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF); } list<cKnight*>::iterator bite = gKnight.begin(); int frog=0; float gravity=0; //work out how far the knight should fall. while(bite!=gKnight.end()){ (*bite)->setSpritePos(knightPos); (*bite)->update(dt); d3dxSRMgr->setTheTransform((*bite)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*bite)->getTexture(),&((*bite)->getSourceRect()),NULL,NULL,0xFFFFFFFF); ++bite; //Creates two ints pointOne and pointTwo these will store the start and end point of each platform. int pointOne=0; int pointTwo=0; float jump=100; iter = aPlatform.begin(); //finds the x coordinate of the first platform float center = (*iter)->getSpritePos2D().x; pknightPos.x = knightTrans.x; pknightPos.y = knightTrans.y; for(iter = aPlatform.begin(); iter != aPlatform.end(); ++iter) //run for each platform. { int king=center+(frog*400); //Work out the limits of the platforms pointOne=king-50; pointTwo=(king+232)-25; frog++; if (250>pointOne&&250<pointTwo) { gravity=315; } } if (knightPos.y<(clientBounds.top+jump)){falling=true;} if (knightPos.y<(clientBounds.bottom-gravity)){knightTrans.y += 30;}else{falling=false;} knightPos = D3DXVECTOR3(knightTrans.x,knightTrans.y,0); if(knightPos.y>clientBounds.bottom) { iterBat = aBat.begin(); while (iterBat != aBat.end()) { iterBat = aBat.erase(iterBat); } iter = aPlatform.begin(); while (iter != aPlatform.end()) { iter = aPlatform.erase(iter); } list<cKnight*>::iterator bite = gKnight.begin(); bite = gKnight.erase(bite); PlatformPos = D3DXVECTOR3(clientBounds.right/2-60,(float)clientBounds.bottom/2-25,0); aPlatform.push_back(new cPlatform(PlatformPos,d3dMgr->getTheD3DDevice(),"Images\\ButtonInactive.png")); backgroundName="Images\\Background.png"; aSurface = d3dMgr->getD3DSurfaceFromFile(backgroundName); Menu=true; finish=true; } bite=gKnight.end(); } for(iterBat = aBat.begin(); iterBat != aBat.end(); ++iterBat) { D3DXVECTOR2 show =(*iterBat)->getTranslation(); (*iterBat)->update(dt); knightPos = D3DXVECTOR3(knightTrans.x,knightTrans.y,0); d3dxSRMgr->setTheTransform((*iterBat)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*iterBat)->getTexture(),&((*iterBat)->getSourceRect()),NULL,NULL,0xFFFFFFFF); } list<cExplosion*>::iterator iter = gExplode.begin(); while(iter != gExplode.end()) { if((*iter)->isActive() == false) { iter = gExplode.erase(iter); } else { (*iter)->update(dt); d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*iter)->getTexture(),&((*iter)->getSourceRect()),NULL,NULL,0xFFFFFFFF); ++iter; } } previousTime = currentTime; d3dxSRMgr->endDraw(); KnightFont->printText(gScore,textPos); KnightFont->printText(gMenu,buttonPos); } d3dMgr->endRender(); } } d3dxSRMgr->cleanUp(); d3dMgr->clean(); return (int) msg.wParam; }
/* ================================================================== // This is winmain, the main entry point for Windows applications ================================================================== */ int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { // Initialize the window if ( !initWindow( hInstance ) ) return false; // called after creating the window if ( !d3dMgr->initD3DManager(wndHandle) ) return false; if ( !d3dxSRMgr->initD3DXSpriteMgr(d3dMgr->getTheD3DDevice())) return false; //=============================================================== // FRAME/TIMING //=============================================================== // Grab the frequency of the high def timer __int64 freq = 0; // measured in counts per second; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); float sPC = 1.0f / (float)freq; // number of seconds per count __int64 currentTime = 0; // current time measured in counts per second; __int64 previousTime = 0; // previous time measured in counts per second; float numFrames = 0.0f; // Used to hold the number of frames float timeElapsed = 0.0f; // cumulative elapsed time float fpsRate = 1.0f/25.0f; //============================================================== // SCREEN //============================================================== GetClientRect(wndHandle,&clientBounds); LPDIRECT3DSURFACE9 theBackbuffer = NULL; // This will hold the back buffer LPDIRECT3DSURFACE9 aSurface = d3dMgr->getD3DSurfaceFromFile("Images\\Back.png"); LPDIRECT3DSURFACE9 menuScreen = d3dMgr->getD3DSurfaceFromFile("Images\\MENU_1.png"); LPDIRECT3DSURFACE9 menuScreen1= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_START.png"); LPDIRECT3DSURFACE9 menuScreen2= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_SCORES.png"); LPDIRECT3DSURFACE9 menuScreen3= d3dMgr->getD3DSurfaceFromFile("Images\\MENU_QUIT.png"); LPDIRECT3DSURFACE9 highScoreScreen = d3dMgr->getD3DSurfaceFromFile("Images\\HIGHSCORES.png"); LPDIRECT3DSURFACE9 newHighScoreScreen = d3dMgr->getD3DSurfaceFromFile("Images\\NEWHIGHSCORE.png"); LPDIRECT3DSURFACE9 levelComplete = d3dMgr->getD3DSurfaceFromFile("Images\\LEVEL_COMPLETE.png"); LPDIRECT3DSURFACE9 controls = d3dMgr->getD3DSurfaceFromFile("Images\\CONTROLS.png"); //============================================================== // PLAYER //============================================================== Player1 = new cXboxController(1); //Crate controller instance for player 1 SetRect(&titlePos, 330, 300, 500, 400); //Set position for level title D3DXVECTOR3 shipPos = D3DXVECTOR3(100,100,0); //Ship starting position theShip = cPlayer(shipPos,d3dMgr->getTheD3DDevice()); //Create cPlayer instance //==================================================stage stage1 = cStage(); //Create stage instance sprintf_s( gScoreStr, 50, "Score: %d", score); //Update score display //============================================background //backPos = D3DXVECTOR3(0,0,0); //background1 = cBackground(clientBounds, backPos, d3dMgr->getTheD3DDevice()); //===================================================font cD3DXFont* scoreFont = new cD3DXFont(d3dMgr->getTheD3DDevice(),hInstance, "staravenue"); //Create score font SetRect(&textPos, 50, 10, 400, 100); //set position for score display MSG msg; ZeroMemory( &msg, sizeof( msg ) ); while( msg.message!=WM_QUIT ) { // Check the message queue if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { //=============================TIMING QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); float dt = (currentTime - previousTime)*sPC; // Accumulate how much time has passed. timeElapsed += dt; numFrames++; if(timeElapsed > fpsRate && numFrames>1) { //================================================================================= // XBOX CONTROLS //================================================================================= if(Player1->IsConnected()) //Test for controller conection { //=========================== // A BUTTON //=========================== if(Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A) { //=================GAME PLAY if(!menu && !hScore && !newHScore && !lvComp){ //Counter to limit fire rate if (fireCounter == 10) { //PLAY FIRE SOUND menuChange.playSound(L"Sounds\\LASER.wav",false); //Add new shot to vector theShip.fire(gShots, d3dMgr->getTheD3DDevice()); fireCounter = 0; } fireCounter++; } //==================Main menu if(menu) { //Counter to limit menu scroll if(fireCounter == 10){ //Play menu selection soundfx menuChange.playSound(L"Sounds\\menuChoice.wav",false); if(menu && menuOpt == 1) { //Load game scene stage1.startLevel(); menu= false; } else if(menu && menuOpt == 2) { //Load highscore scene menu = false; hScore = true; } else if(menu && menuOpt == 3) { //Exit game exit(0); } fireCounter++; } } if(lvComp) { //Counter to limit menu scroll if(fireCounter == 10){ lvComp = false; //Check for new highscore if(highScores->checkScore(score)) { //If new highscore load name entry scene newHScore=true; } else{ //if not load main menu menu = true; } } fireCounter++; } if(newHScore) { //Limit scroll if(fireCounter == 10){ //Update highscores with entered name and current score highScores->UpdateScore(name,score); newHScore = false; hScore = true; //Load highscore table } fireCounter++; } if(controls) { //Load main menu controls = false; menu = true; } fireCounter++; } else{ fireCounter =10; } //================================ // B BUTTON //================================ if(Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_B){ if(hScore) { //Load main menu hScore = false; menu = true; } } //================================ // LEFT STICK RIGHT //================================ if(Player1->GetState().Gamepad.sThumbLX>10000) { if(!menu && !hScore && !newHScore && !lvComp){ //Check screen collision if( theShip.getSpritePos2D().x < clientBounds.right - 60){ theShip.moveRight(); } } //Limit menu scroll if(menuCounterRight == MENU_SCROLL) { if(newHScore) { //Scroll Letter position for name enter if(sName==3) { sName = 1; } else { sName++; } } } menuCounterRight++; } else { menuCounterRight = MENU_SCROLL; } //================================ // LEFT STICK LEFT //================================ if(Player1->GetState().Gamepad.sThumbLX<-10000) { if(!menu && !hScore && !newHScore && !lvComp){ //Check screen collision if(theShip.getSpritePos2D().x > clientBounds.left + 60) { theShip.moveLeft(); } } if(menuCounterLeft == MENU_SCROLL) { if(newHScore) { //Scroll Letter position for name enter if(sName==1) { sName = 3; } else { sName--; } } } menuCounterLeft++; } else{ menuCounterLeft = MENU_SCROLL; } //================================ // LEFT STICK UP //================================ if(Player1->GetState().Gamepad.sThumbLY>10000) { if(!menu && !hScore && !newHScore && !lvComp) { //Check screen collision if(theShip.getSpritePos2D().y > clientBounds.top + 60) { theShip.moveUp(); } } if(menu) { if(menuCounterUp == MENU_SCROLL) { //Play menu selection sound fx menuChange.playSound(L"Sounds\\MenuChange.wav",false); //Change menu index if(menuOpt==1) { menuOpt = 3; } else{ menuOpt--; } menuCounterUp =0; } menuCounterUp++; } if(newHScore) { if(menuCounterUp == MENU_SCROLL) { //Scroll through letters on name entry switch(sName) { case 1: if(nameI == 25) nameI=0; else nameI++; break; case 2: if(nameJ == 25) nameJ=0; else nameJ++; break; case 3: if(nameK == 25) nameK=0; else nameK++; break; } } menuCounterUp++; } } else { menuCounterUp = MENU_SCROLL; } //================================ // LEFT STICK DOWN //================================ if(Player1->GetState().Gamepad.sThumbLY<-10000) { if(!menu && !hScore && !newHScore && !lvComp){ //Check screen collision if(theShip.getSpritePos2D().y < clientBounds.bottom - 60){ theShip.moveDown();} } if(menu) { if(menuCounterDown == MENU_SCROLL){ menuChange.playSound(L"Sounds\\MenuChange.wav",false); if(menuOpt==3) { menuOpt = 1; } else{ menuOpt++; } menuCounterDown = 0; } menuCounterDown++; } if(newHScore){ if(menuCounterDown == MENU_SCROLL) { //Scroll through letters on name entry switch(sName){ case 1: if(nameI == 0) nameI=25; else nameI--; break; case 2: if(nameJ == 0) nameJ=25; else nameJ--; break; case 3: if(nameK == 0) nameK=25; else nameK--; break; } } menuCounterDown++; } } else{ menuCounterDown = MENU_SCROLL; } } //================================================================================= // GAME PLAY //================================================================================= if(!menu && !hScore && !newHScore && !lvComp &&!controls) { if(!theShip.isActive()) { //counter to stall level end deathCounter++; } if(deathCounter == 20) { stageMusic.stopSound(); //Stop stage music lvComp = true; //Load level complete scene } //========================================================stage title if(titleCounter<100) { //Counter for timed events if(titleCounter==5) { stageMusic.playSound(L"Sounds\\Moon.wav",false); //Start stage music } sprintf_s( gStageTitle, 25, "Stage One"); //Display stage title titleCounter++; } else { showTitle = false; //========================================start stage if (stage1.isActive()){ stage1.Update(eShips, clientBounds, d3dMgr->getTheD3DDevice()); //Run enemy scripting } else{ //Load level complete scene lvComp = true; } } theShip.update(); //Update players movement //====================================================Background background1.update(); // background2.update(); //======================================================================== // COLLISIONS //======================================================================= list<cEnemy*>::iterator index; vector<cShot*>::iterator iter; //Loop through enemy ships for(index = eShips.begin(); index != eShips.end(); ++index) { //Loop through shots for(iter = gShots.begin(); iter!=gShots.end(); ++iter) { //If enemy ship is shot if((*iter)->collidedWith((*iter)->getBoundingRect(),(*index)->getBoundingRect()) && (*iter)->getShooter() == 0) { score++; //update score sprintf_s( gScoreStr, 50, "Score: %d", score); (*iter)->setActive(false); //Remove shot (*index)->setActive(false); //Remover enemy ship OutputDebugString("Collision!!"); } //If player is shot if((*iter)->collidedWith((*iter)->getBoundingRect(),theShip.getBoundingRect()) && (*iter)->getShooter() == 1) { //PLAYER DEATH (*iter)->setActive(false); //Remove shot theShip.Death(); //Kill player OutputDebugString("Death"); } //If shot leaves screen bounds if((*iter)->getSpritePos2D().x < clientBounds.left || (*iter)->getSpritePos2D().x > clientBounds.right) { (*iter)->setActive(false); //Remove shot } } //If enemy ship leaves screen bounds if((*index)->getSpritePos().x < 30 || (*index)->getSpritePos().y > clientBounds.bottom+300 || (*index)->getSpritePos().y < clientBounds.top-300) { (*index)->setActive(false); //Remove enemy ship } } d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(aSurface, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); d3dxSRMgr->beginDraw(); // d3dxSRMgr->setTheTransform(background1.getSpriteTransformMatrix()); // d3dxSRMgr->drawSprite(background1.getTexture(),&background1.getRect(),NULL,NULL,0xFFFFFFFF); //=====================================================ship //If player is alive update and draw if(theShip.isActive()){ d3dxSRMgr->setTheTransform(theShip.getSpriteTransformMatrix()); d3dxSRMgr->drawSprite(theShip.getTexture(),NULL,NULL,NULL,0xFFFFFFFF); } //========================================================================Updates //Delete inactive shots and enemy ships iter = gShots.begin(); index = eShips.begin(); while(iter != gShots.end()) { if((*iter)->isActive() == false) { iter = gShots.erase(iter); } else { //If active update and draw (*iter)->update(); d3dxSRMgr->setTheTransform((*iter)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*iter)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF); iter++; } } while(index != eShips.end()) { if((*index)->isActive() == false) { index = eShips.erase(index); } else { (*index)->update(d3dMgr->getTheD3DDevice(),gShots); d3dxSRMgr->setTheTransform((*index)->getSpriteTransformMatrix()); d3dxSRMgr->drawSprite((*index)->getTexture(),NULL,NULL,NULL,0xFFFFFFFF); index++; } } d3dxSRMgr->endDraw(); scoreFont->printText(gScoreStr,textPos); //Display stage title if(showTitle) scoreFont->printText(gStageTitle,titlePos); d3dMgr->endRender(); OutputDebugString("timeElapsed > fpsRate"); timeElapsed = 0.0f; } //================================================================================================ // MAIN MENU //================================================================================================ else if(menu) { //Display specific screen based on menu index switch(menuOpt){ case 1: menuScreen = menuScreen1; break; case 2: menuScreen = menuScreen2; break; case 3: menuScreen = menuScreen3; break; default: menuScreen = menuScreen; break;} //=============================== // RESET FOR NEW GAME //=============================== score = 0; sprintf_s( gScoreStr, 50, "Score: %d", score); theShip.setSpritePos2D(D3DXVECTOR3(100,100,0)); showTitle = true; titleCounter = 0; theShip.Respawn(); //=============================== //menuScreen1 = d3dMgr->getD3DSurfaceFromFile("Images\\MENU_1.png"); d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(menuScreen, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); d3dMgr->endRender(); } //================================================================================================ // HIGH SCORE TABLE //================================================================================================ else if(hScore) { //Set location for Score display RECT scorePos; SetRect(&scorePos, 50, 10, 700, 500); d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(highScoreScreen, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); highScores->openfile(); //Load highscores from file highScores->getHighScores(scoreTable); //Load into scoreTable for display scoreFont->printText(scoreTable,scorePos); //Display scores d3dMgr->endRender(); } //================================================================================================ // NEW HIGH SCORE //================================================================================================ else if(newHScore) { //Update current name highScores->enterName(name, nameI, nameJ, nameK); //Set name psoition RECT scorePos; SetRect(&scorePos, 330, 300, 450, 400); d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(newHighScoreScreen, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); //Display current name scoreFont->printText(name,scorePos); d3dMgr->endRender(); } //================================================================================================ // LEVEL COMPLETE //================================================================================================ else if(lvComp) { //Update score string sprintf_s( gScoreStr, 50, "%d", score); RECT scorePos; SetRect(&scorePos, 330, 300, 450, 400); d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(levelComplete, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); scoreFont->printText(gScoreStr,scorePos); //Display Score d3dMgr->endRender(); } else if(controls){ d3dMgr->beginRender(); theBackbuffer = d3dMgr->getTheBackBuffer(); d3dMgr->updateTheSurface(controls, theBackbuffer); d3dMgr->releaseTheBackbuffer(theBackbuffer); d3dMgr->endRender(); } } //menu previousTime = currentTime; //================================== StringCchPrintf(szTempOutput, 30, TEXT("dt=%f\n"), dt); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("timeElapsed=%f\n"), timeElapsed); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("previousTime=%u\n"), previousTime); OutputDebugString(szTempOutput); StringCchPrintf(szTempOutput, 30, TEXT("fpsRate=%f\n"), fpsRate); OutputDebugString(szTempOutput); //==================================== } } d3dxSRMgr->cleanUp(); d3dMgr->clean(); return (int) msg.wParam; }
/* ================================================================== * LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, * LPARAM lParam) * The window procedure ================================================================== */ LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // Check any available messages from the queue switch (message) { case WM_KEYDOWN: { if (wParam == 'A') { //Screen edge collision if(theShip.getSpritePos2D().x < clientBounds.left + 60) { break; } //Change name index if(newHScore) { if(sName==1) { sName = 3; } else { sName--; } } theShip.moveLeft(); return 0; } if (wParam == 'D') { //Change name index if(newHScore) { if(sName==3) { sName = 1; } else { sName++; } } theShip.moveRight(); return 0; } if (wParam == 'W') { if(newHScore){ //Change letter index switch(sName){ case 1: if(nameI == 25) nameI=0; else nameI++; break; case 2: if(nameJ == 25) nameJ=0; else nameJ++; break; case 3: if(nameK == 25) nameK=0; else nameK++; break; } } //Play menu sound fx menuChange.playSound(L"Sounds\\menuChange.wav",false); //change menu index if(menuOpt==1) { menuOpt = 3; } else{ menuOpt--; } theShip.moveUp(); return 0; } if (wParam == 'S') { if(newHScore){ //Change letter index switch(sName){ case 1: if(nameI == 0) nameI=25; else nameI--; break; case 2: if(nameJ == 0) nameJ=25; else nameJ--; break; case 3: if(nameK == 0) nameK=25; else nameK--; break; } } //menu selection sound menuChange.playSound(L"Sounds\\menuChange.wav",false); //Menu index if(menuOpt==3) { menuOpt = 1; } else{ menuOpt++; } theShip.moveDown(); return 0; } if (wParam == VK_SPACE) { if(!menu) { //Add single shot to shot collection theShip.fire(gShots, d3dMgr->getTheD3DDevice()); } //Play menu confirmation sound fx //Change scene using menu index else if(menu && menuOpt == 1) { menuChange.playSound(L"Sounds\\menuChoice.wav",false); menu= false; } else if(menu && menuOpt == 2) { menuChange.playSound(L"Sounds\\menuChoice.wav",false); menu = false; newHScore = true; } else if(menu && menuOpt == 3) { menuChange.playSound(L"Sounds\\menuChoice.wav",false); exit(0); } return 0; } // StringCchPrintf(szTempOutput, STRSAFE_MAX_CCH, TEXT("Mouse: lLastX=%d lLastY=%d\r\n"), LOWORD(lParam), HIWORD(lParam)); OutputDebugString(szTempOutput); return 0; } case WM_CLOSE: { // Exit the Game PostQuitMessage(0); return 0; } case WM_DESTROY: { PostQuitMessage(0); return 0; } } // Always return the message to the default window // procedure for further processing return DefWindowProc(hWnd, message, wParam, lParam); }