Monday, 9 June 2025

c game

 ##########################################                                TIMBER                                   ##########################################################

#############################################################################################################################################################################



#include<sstream>

#include<SFML/Graphics.hpp>

#include <SFML/Audio.hpp>


using namespace sf;


//********Declarations for Branches

void updateBranches(int);


const int NUM_BRANCHES = 6;

enum class side{LEFT, RIGHT, NONE};

side branchPositions[NUM_BRANCHES];

Sprite Branches[NUM_BRANCHES];



int main(){


    //Create Video Mode Object

    VideoMode vm(1920,1080);

    //VideoMode vm=VideoMode::getDesktopMode();

    //Rendering window

    RenderWindow window(vm,"Timber!!!");


    Texture backgroundTexture;

    backgroundTexture.loadFromFile("graphics/background.png");


    Sprite backgroundSprite;

    backgroundSprite.setTexture(backgroundTexture);

    backgroundSprite.setPosition(0,0);


    Texture treeTexture;

    treeTexture.loadFromFile("graphics/tree.png");


    Sprite treeSprite;

    treeSprite.setTexture(treeTexture);

    treeSprite.setPosition(810,0);


    Texture beeTexture;

    beeTexture.loadFromFile("graphics/bee.png");


    Sprite beeSprite;

    beeSprite.setTexture(beeTexture);

    beeSprite.setPosition(2000,800);


    bool beeActive=false;

    float beeSpeed=0.0f;

    float beeHeight=0.0f;


    Texture cloudTexture;

    cloudTexture.loadFromFile("graphics/cloud.png");


    Sprite cloudSprite1;

    cloudSprite1.setTexture(cloudTexture);

    cloudSprite1.setPosition(0,0);


    bool cloudSpriteActive1=false;

    float cloudSpriteSpeed1=0.0f;

    float cloudSpriteHeight1=0.0f;



    Sprite cloudSprite2;

    cloudSprite2.setTexture(cloudTexture);

    cloudSprite2.setPosition(0,150);


    bool cloudSpriteActive2=false;

    float cloudSpriteSpeed2=0.0f;

    float cloudSpriteHeight2=0.0f;


    Sprite cloudSprite3;

    cloudSprite3.setTexture(cloudTexture);

    cloudSprite3.setPosition(0,300);


    bool cloudSpriteActive3=false;

    float cloudSpriteSpeed3=0.0f;

    float cloudSpriteHeight3=0.0f;


    Clock clock;

    float timeRemaining = 6.0f;

    bool paused = true;

    

    RectangleShape timeBar;

    float timeBarStartWidth=400.0f;

    float timeBarHeight = 80.0f;


    timeBar.setSize(Vector2f(timeBarStartWidth,timeBarHeight));

    timeBar.setFillColor(Color::Red);

    timeBar.setPosition(1920/2 - timeBarStartWidth/2.0, 980);

    float timeBarWidthPerSecond = timeBarStartWidth/timeRemaining;


    int score=0;

    Text scoreText;

    Font font;

    font.loadFromFile("fonts/KOMIKAP_.ttf");

    scoreText.setFont(font);

    scoreText.setCharacterSize(75);

    scoreText.setFillColor(Color::White);

    scoreText.setString("Score = 0");

    scoreText.setPosition(20,20);


    Text messageText;

    messageText.setFont(font);

    messageText.setFillColor(Color::White);

    messageText.setCharacterSize(100);

    messageText.setString("Press Enter to Start the Game");


    FloatRect textRect = messageText.getLocalBounds();

    messageText.setOrigin(textRect.left + textRect.width/2.0,textRect.top + textRect.height/2.0);

    messageText.setPosition(1920/2.0,1080/2.0);


    //********Create and add Branches

    Texture branchTexture;

    branchTexture.loadFromFile("graphics/branch.png");


    for(int i=0;i<NUM_BRANCHES;i++){

        

            Branches[i].setTexture(branchTexture);

            Branches[i].setPosition(-2000,-2000);

            Branches[i].setOrigin(220,20);

                    

    } 

      

       

    //***************Player

    Texture texturePlayer;

    texturePlayer.loadFromFile("graphics/player.png");

    Sprite spritePlayer;

    spritePlayer.setTexture(texturePlayer);

    spritePlayer.setPosition(580,720);



    //***************Side of the Player

    side sidePlayer=side::LEFT;



    //***************Grave stone

    Texture textureRIP;

    textureRIP.loadFromFile("graphics/rip.png");

    Sprite spriteRIP;

    spriteRIP.setTexture(textureRIP);

    spriteRIP.setPosition(600,860);



    //***************Axe

    Texture textureAxe;

    textureAxe.loadFromFile("graphics/axe.png");

    Sprite spriteAxe;

    spriteAxe.setTexture(textureAxe);

    spriteAxe.setPosition(700,830);



    //***************Line up the Axe with the Tree

    const int AXE_POSITION_LEFT = 700;

    const int AXE_POSITION_RIGHT = 1075;


    //***************Flying Log

    Texture textureLog;

    textureLog.loadFromFile("graphics/log.png");

    Sprite spriteLog;

    spriteLog.setTexture(textureLog);

    spriteLog.setPosition(810,720);


    //***************Other declarations for flying Log

    bool logActive=false;

    float logSpeedX=1000;

    float logSpeedY=-1500;


    //***************Player Input

    bool acceptInput=false;

    

    //******* Prepare the sound

    SoundBuffer chopBuffer;

    chopBuffer.loadFromFile("sound/chop.wav");

    SoundBuffer ootBuffer;

    ootBuffer.loadFromFile("sound/out_of_time.wav");

    SoundBuffer deathBuffer;

    deathBuffer.loadFromFile("sound/death.wav");


    Sound chopSound;

    chopSound.setBuffer(chopBuffer);

    Sound ootSound;

    ootSound.setBuffer(ootBuffer);

    Sound deathSound;

    deathSound.setBuffer(deathBuffer); 

    


    while(window.isOpen()){


        //***************Handle user input

        Event event;

        while(window.pollEvent(event)){

            if(event.type==Event::KeyReleased && !paused){

                acceptInput=true;

                spriteAxe.setPosition(2000,spriteAxe.getPosition().y);

            }

        }


        //Handle the Players input

        if(Keyboard::isKeyPressed(Keyboard::Escape)){

            window.close();

        }


        //start the game

        if(Keyboard::isKeyPressed(Keyboard::Return)){


            paused=false;

            //Reset time

            timeRemaining =6;

            //***************Reset score

            score=0;           

            

            //***************Make all branches disappear

            for(int i=0;i<NUM_BRANCHES;i++){

                branchPositions[i]=side::NONE;

            }


            //***************Make Grave Stone hidden

            spriteRIP.setPosition(3000,500);


            //***************Move the player into the position

            spritePlayer.setPosition(580,720);            

            

            //***************Make acceptInput true

            acceptInput=true;


        }


        //***************Wrap the player-controls right and left cursor keys

        //***************to make sure Game is accepting input properly

        if(acceptInput){

            //***************Handle Right Cursor Key

            if(Keyboard::isKeyPressed(Keyboard::Right)){

                //***************update score

                score++;


                //***************update time remaining

                timeRemaining+=(2/score)+.15;


                //***************set the player side to Right

                sidePlayer=side::RIGHT;


                //***************set the player position

                spritePlayer.setPosition(1200,720);


                //***************set the Axe position

                spriteAxe.setPosition(AXE_POSITION_RIGHT,spriteAxe.getPosition().y);


                //***************set the log position, log-Speed on X to fly on the left, logActive enabled

                spriteLog.setPosition(810,720);

                logSpeedX=-5000;

                logActive=true;              

                

                //***************update branches

                updateBranches(score);


                //***************acceptInput to false

                acceptInput=false;


                //***************play a chop sound

                chopSound.play();


            }


            //***************Handle Left Cursor Key

            if(Keyboard::isKeyPressed(Keyboard::Left)){


                //***************update score

                score++;

                //***************update time remaining

                timeRemaining+=(score/2.0)+.15;


                //***************set the player side to Left

                sidePlayer=side::LEFT;


                //***************set the player position

                spritePlayer.setPosition(580,720);


                //***************set the Axe position

                spriteAxe.setPosition(AXE_POSITION_LEFT,spriteAxe.getPosition().y);


                //***************set the log position, log-Speed on X to fly on the right, logActive enabled

                spriteLog.setPosition(810,720);

                logSpeedX=5000;

                logActive=true;              

                

                //***************update branches

                updateBranches(score);


                //***************acceptInput to false

                acceptInput=false;


                //***************play a chop sound

                chopSound.play();



            }


        }


        //Update the Scene


        if(!paused){

            //Update the scene to start


            Time dt=clock.restart();

            timeRemaining -=dt.asSeconds();


            timeBar.setSize(Vector2f(timeBarWidthPerSecond*timeRemaining, timeBarHeight));



            if(timeRemaining<=0.0f){

                paused=true;


                //***************Show "Out of Time!!!" message at the center of the window

                messageText.setString("Out of Time!!!");

                textRect=messageText.getLocalBounds();

                messageText.setOrigin(textRect.left+textRect.width/2.0,textRect.top+textRect.height/2.0);

                messageText.setPosition(window.getSize().x/2.0,window.getSize().y/2.0);

                

                

                //***************play "out of time" sound

                ootSound.play();



            }


            //Handling bee


            if(!beeActive){

                //Set the bee's speed, height and position

                srand((int)time(0)*10);

                beeSpeed=(rand()%200)+200;

            

                srand((int)time(0)*20);

                beeHeight=(rand()%500)+500;


                beeSprite.setPosition(2000,beeHeight);

                beeActive=true;


            }

            else{

                //Move the bee

                beeSprite.setPosition(beeSprite.getPosition().x - beeSpeed*dt.asSeconds(), beeSprite.getPosition().y);

                if(beeSprite.getPosition().x < -100){

                    beeActive=false;

                }


            }


            //Handling clouds


            // Cloud 1

            

            if(!cloudSpriteActive1){

                //Set the cloud's speed, height and position

                srand((int)time(0)*10);

                cloudSpriteSpeed1=rand()%200;

            

                srand((int)time(0)*10);

                cloudSpriteHeight1=rand()%150;


                cloudSprite1.setPosition(-200,cloudSpriteHeight1);

                cloudSpriteActive1=true;


            }

            else{

                //Move the cloud

                cloudSprite1.setPosition(cloudSprite1.getPosition().x + cloudSpriteSpeed1*dt.asSeconds(), cloudSprite1.getPosition().y);

                if(cloudSprite1.getPosition().x > 1920){

                    cloudSpriteActive1=false;

                }

            }



            //Cloud 2

        

        

            if(!cloudSpriteActive2){

                //Set the cloud's speed, height and position

                srand((int)time(0)*20);

                cloudSpriteSpeed2=rand()%200;

            

                srand((int)time(0)*20);

                cloudSpriteHeight2=rand()%300 - 150;


                cloudSprite1.setPosition(-200,cloudSpriteHeight2);

                cloudSpriteActive2=true;


            }

            else{

                //Move the cloud

                cloudSprite2.setPosition(cloudSprite2.getPosition().x + cloudSpriteSpeed2*dt.asSeconds(), cloudSprite2.getPosition().y);

                if(cloudSprite2.getPosition().x > 1920){

                    cloudSpriteActive2=false;

                }

            }    



            //Cloud 3


            if(!cloudSpriteActive3){

                //Set the cloud's speed, height and position

                srand((int)time(0)*30);

                cloudSpriteSpeed3=rand()%200;

            

                srand((int)time(0)*30);

                cloudSpriteHeight3=rand()%450 - 150;


                cloudSprite3.setPosition(-200,cloudSpriteHeight3);

                cloudSpriteActive3=true;


            }

            else{

                //Move the cloud

                cloudSprite3.setPosition(cloudSprite3.getPosition().x + cloudSpriteSpeed3*dt.asSeconds(), cloudSprite3.getPosition().y);

                if(cloudSprite3.getPosition().x > 1920){

                    cloudSpriteActive3=false;

                }    


            }


    //update score

            std :: stringstream ss;

            ss << "Score = " << score;

            scoreText.setString(ss.str());


            //update branches

            for(int i=0;i<NUM_BRANCHES;i++){

                float heightBranch = i*150;

                if(branchPositions[i]==side::LEFT){

                    Branches[i].setPosition(600,heightBranch);

                    Branches[i].setRotation(180); //flip;


                }

                else if(branchPositions[i]==side::RIGHT){

                    Branches[i].setPosition(1330,heightBranch);

                    Branches[i].setRotation(0); //no flip;

                }

                else{

                    Branches[i].setPosition(3000,heightBranch);

                    //Branches[i].setRotation(0); //no flip;

                }

            }


            //***************Handle a flying log

            if(logActive){

                spriteLog.setPosition(spriteLog.getPosition().x+(logSpeedX*dt.asSeconds()),spriteLog.getPosition().y+(logSpeedY*dt.asSeconds()));

                if(spriteLog.getPosition().x<-100 || spriteLog.getPosition().x>2000){

                    logActive=false;

                    spriteLog.setPosition(810,720);

                }

            }


            //***************Has the player been squished by a branch? Check and update

            if(branchPositions[5]==sidePlayer){

                //***************pause the game

                paused=true;


                //***************accepting no input

                acceptInput=false;               

                

                //***************hide the player

                spritePlayer.setPosition(2000,2000);


                //***************show the grave stone

                spriteRIP.setPosition(600,860);


                //***modify: disappear timebar

                timeBar.setPosition(2000,2000);


                //***************show "Game Over!!!" message

                messageText.setString("Game Over!!!");

                textRect=messageText.getLocalBounds();

                messageText.setOrigin(textRect.left+textRect.width/2.0,textRect.top+textRect.height/2.0);

                messageText.setPosition(window.getSize().x/2.0,window.getSize().y/2.0);


                //***************play sound of death

                deathSound.play();



            }


        } //End of if(!paused)

               


        //Clear window

        window.clear();

        //draw 

        window.draw(backgroundSprite);


        window.draw(cloudSprite1);

        window.draw(cloudSprite2);

        window.draw(cloudSprite3);

        for(int i=0;i<NUM_BRANCHES;i++){

            window.draw(Branches[i]);

        }

        window.draw(treeSprite);


        //***************draw player, axe, log and grave stone

        window.draw(spritePlayer);

        window.draw(spriteAxe);

        window.draw(spriteLog);

        window.draw(spriteRIP);        

        

        window.draw(beeSprite);


        window.draw(timeBar);


        window.draw(scoreText);

        

        if(paused)

           window.draw(messageText);           


        

           //display

        window.display();

        

    } //End of while loop



    return 0;

} //End of  main()


//*********definition of updateBranches(int)

void updateBranches(int seed){


    //shift branch position values to one place to vacant the position 0

    for(int i=NUM_BRANCHES-1;i>0;i--){

        branchPositions[i]=branchPositions[i-1];

    }

    //Spawn new branch position to 0th place

    srand(time(0) + seed);

    int r = rand()%5;

    switch(r){

        case 0:branchPositions[0]=side::LEFT;

        break;

        case 1:

        branchPositions[0]=side::RIGHT;

        break;

        default: branchPositions[0]=side::NONE;

    }

}


#########################################################                           pong                     #########################################################

######################################################################################################################################################################



****************   Ball.h  *********************************************************************************



#pragma once //pragmatic information to the compiler not to read/open 

//same header files after first time read

#include<SFML/Graphics.hpp>


using namespace sf;


class Ball

{

private:

    //Position

Vector2f m_Position;

//Shape

CircleShape m_Shape;

//Speed

float m_Speed=1000.0f;

//X Direction

float m_DirectionX=0.2f;

//Y Direction

float m_DirectionY=0.2f;

public:

//Constructor

Ball(float StartX, float StartY);

//getPosition()

FloatRect getPosition();


//getShape()

CircleShape getShape();

//getXVelocity()

float getXVelocity();

//reboundSides()

void reboundSides();

//reboundBatOrTop()

void reboundBatOrTop();


//reboundBottom()

void reboundBottom();


//update(Time)

void update(Time);


};


**********************      Ball.cpp      ****************************************************************************


#include "Ball.h"


//Definitions of all methods of Ball class are written below


//Constructor

Ball::Ball(float StartX, float StartY){

    m_Position.x=StartX;

    m_Position.y=StartY;

    m_Shape.setRadius(10.0);

    m_Shape.setPosition(m_Position);

}


//getPosition()

FloatRect Ball::getPosition(){

    return m_Shape.getGlobalBounds(); 

}

//getShape()

CircleShape Ball::getShape(){

    return m_Shape;

}

//getXVelocity()

float Ball::getXVelocity(){

    return m_DirectionX;

}

//reboundSides()

void Ball::reboundSides(){

    m_DirectionX=-m_DirectionX;

}

//reboundBatOrTop()

void Ball::reboundBatOrTop(){

    m_DirectionY=-m_DirectionY;

}


//reboundBottom()

void Ball::reboundBottom(){

    m_Position.x=500;

    m_Position.y=0;

    m_DirectionY=-m_DirectionY;

}


//update(Time)

void Ball::update(Time dt){

    m_Position.x+=m_DirectionX*m_Speed*dt.asSeconds();

    m_Position.y+=m_DirectionY*m_Speed*dt.asSeconds();

    m_Shape.setPosition(m_Position);

}



*************         Bat.h          *********************************************************************


#pragma once

#include<SFML/Graphics.hpp>


using namespace sf;


class Bat{

    Vector2f m_Position;

    RectangleShape m_Shape;

    float m_Speed=1000.0f;

    bool m_MovingRight=false;

    bool m_MovingLeft=false;


    public:

    Bat(float startX, float startY);

    FloatRect get_Position();

    RectangleShape get_Shape();

    void moveRight();

    void moveLeft();

    void stopRight();

    void stopLeft();

    void update(Time dt);

};



****************        Bat.cpp          ******************************************************************


#include"Bat.h"


using namespace sf;


//Bat class constructor

Bat::Bat(float startX, float startY){

    m_Position.x=startX;

    m_Position.y=startY;

    m_Shape.setSize(Vector2f(100.0,10.0));

    m_Shape.setPosition(m_Position);

}

FloatRect Bat::get_Position(){

    

    return m_Shape.getGlobalBounds();

}

RectangleShape Bat::get_Shape(){


    return m_Shape;


}

void Bat::moveRight(){


    m_MovingRight=true;


}

void Bat::moveLeft(){


    m_MovingLeft=true;


}

void Bat::stopRight(){


    m_MovingRight=false;


}

void Bat::stopLeft(){


    m_MovingLeft=false;


}

void Bat::update(Time dt){


    if(m_MovingLeft){

        m_Position.x -= m_Speed*dt.asSeconds();

        //extra code to confirm bat should not go outside of the left boundary

        if(m_Position.x<0){

            stopLeft();

        }


    }


    if(m_MovingRight){

        m_Position.x += m_Speed*dt.asSeconds();

        //extra code to confirm bat should not go outside of the right boundary

        if(m_Position.x>1920){

            stopRight();

        }

    }


    m_Shape.setPosition(m_Position);


}



*****************************     Pong.cpp        *******************************************************************************


#include "Bat.h"

#include "Ball.h"

#include<SFML/Graphics.hpp>

#include<sstream>


using namespace sf;


int main(){


    //Create VideoMode object

    VideoMode vm(1920.0,1080.0);


    //Create Window

    RenderWindow window(vm,"PONG!!!",Style::Fullscreen);


    //Create Bat and set position

    Bat bat(window.getSize().x/2.0,window.getSize().y-10);


    //Create Ball and set position

    Ball ball(window.getSize().x/2.0,0);    

    

    //Create hud (heads up display) for score and lives

    Text hud;

    Font font;

    font.loadFromFile("font/DS-DIGI.TTF");

    hud.setFont(font);

    hud.setCharacterSize(75.0);

    hud.setFillColor(Color::White);

    hud.setPosition(20.0,20.0);


    int score=0;

    int lives=3;


    //Manage time

    Clock clock;

    //bool acceptInput=false;


    while(window.isOpen()){


        //handle player input to close the window (event type closed)

        Event event;

        while(window.pollEvent(event)){

            if(event.type==Event::Closed)

               window.close();

            /*if(event.type==Event::KeyReleased)

              acceptInput=true;*/   

        }


        //handle quitting game

        if(Keyboard::isKeyPressed(Keyboard::Escape)){

            window.close();

        }



        //handle playing inputs (right and left cursor movement)

        //if(acceptInput){

            //right cursor

            if(Keyboard::isKeyPressed(Keyboard::Right))

            {

                //if bat touches right window-side stop moving right.

               if(bat.get_Position().left+bat.get_Position().width>window.getSize().x){

                 bat.stopRight();

                }

                else{   

                     //else move right

                    bat.moveRight();           

                }

                //acceptInput=false;

            }

            else{

              // stop right movement

              bat.stopRight();

              //acceptInput=true;

            }

            

            //Left cursor

            if(Keyboard::isKeyPressed(Keyboard::Left)){

                //if bat touches left window-side stop moving left.

                if(bat.get_Position().left<0){

                    bat.stopLeft();

                }

                else{    

                       //else move left

                        bat.moveLeft();

                }

                //acceptInput=false;    

            }

            else{

                  //stop left movement

                    bat.stopLeft();

                    //acceptInput=true;            

            }

        //}


        //update time

        Time dt=clock.restart();        


        //update bat

        bat.update(dt);        


        //update ball

        ball.update(dt);


        //Handle ball hits bottom side

        if(ball.getPosition().top>=window.getSize().y){

            

            lives--;

            if(lives<1){

                score=0;

                lives=3;

            }

            ball.reboundBottom();

        }


        //Handle ball hits top side

        if(ball.getPosition().top<=0){

            score++;

            ball.reboundBatOrTop();

        }


        //Handle ball hits sound boundaries

        if(ball.getPosition().left<0 || (ball.getPosition().left+ball.getPosition().width)>window.getSize().x){

            ball.reboundSides();

        }


        //Handle ball hits the bat

        if(ball.getPosition().intersects(bat.get_Position())){

            score++;

            ball.reboundBatOrTop();

            ball.update(dt);

            bat.update(dt);

        }


        //update score message

        std::stringstream ss;

        ss << "Score: " << score <<" Lives: " <<lives;

        hud.setString(ss.str());        

        

        //draw

        window.clear();

        

        //draw bat

        window.draw(bat.get_Shape());


        //draw ball

        window.draw(ball.getShape());

        

        //draw hud

        window.draw(hud);        

        

        window.display();

    }


    return 0;

}



#####################################################               ZombieArena                  ####################################################################

#####################################################################################################################################################################


*************************************    bullet.cpp      ******************************************************


#include <SFML/Graphics.hpp>

#include<cmath>

using namespace sf;


class Bullet

{

private:

Vector2f m_Position;

RectangleShape m_BulletShape;

bool m_InFlight = false;

float m_BulletSpeed = 1000;

float m_BulletDistanceX;

float m_BulletDistanceY;

float m_XTarget;

float m_YTarget;

float m_MaxX;

float m_MinX;

float m_MaxY;

float m_MinY;

public:

Bullet();

void stop();

bool isInFlight();

void shoot(float startX, float startY,float xTarget, float yTarget);

FloatRect getPosition();

RectangleShape getShape();

void update(float elapsedTime);


};

Bullet::Bullet()

{

m_BulletShape.setSize(sf::Vector2f(20, 20));

}

void Bullet::shoot(float startX, float startY,float targetX, float targetY)

{

m_InFlight = true;

m_Position.x = startX;

m_Position.y = startY;

float gradient = (startX - targetX) / (startY - targetY);


if (gradient < 0)

{

gradient *= -1;

}

m_BulletDistanceY=m_BulletSpeed/(1+gradient);

m_BulletDistanceX=m_BulletSpeed*(gradient/(1+gradient));

//float ratioXY = m_BulletSpeed / (1 + gradient);


// m_BulletDistanceY = m_BulletSpeed*(1/1+;m_BulletDistanceX = ratioXY * gradient;

if (targetX < startX)

{

m_BulletDistanceX *= -1;

}


if (targetY < startY)

{

m_BulletDistanceY *= -1;

}

/*float delX = targetX - startX;

float delY = targetY - startY;

float dist = sqrt(delX*delX + delY*delY);

m_BulletDistanceY = m_BulletSpeed*delY/dist;

m_BulletDistanceX = m_BulletSpeed*delX/dist; 

*/


// Finally, assign the results to the

// member variables

//m_XTarget = targetX;

//m_YTarget = targetY;


// Set a max range of 1000 pixels

float range = 1000;

m_MinX = startX - range;

m_MaxX = startX + range;

m_MinY = startY - range;

m_MaxY = startY + range;

// Position the bullet ready to be drawn

m_BulletShape.setPosition(m_Position);

}

void Bullet::stop()

{

m_InFlight = false;

}


bool Bullet::isInFlight()

{

return m_InFlight;

}


FloatRect Bullet::getPosition()

{

return m_BulletShape.getGlobalBounds();

}


RectangleShape Bullet::getShape()

{

return m_BulletShape;

}



void Bullet::update(float elapsedTime)

{

// Update the bullet position variables

m_Position.x += m_BulletDistanceX * elapsedTime;

m_Position.y += m_BulletDistanceY * elapsedTime;


// Move the bullet

m_BulletShape.setPosition(m_Position);


// Has the bullet gone out of range?

if (m_Position.x < m_MinX || m_Position.x > m_MaxX ||

m_Position.y < m_MinY || m_Position.y > m_MaxY)

{

m_InFlight = false;

}


}




*************************************                         pickup.cpp                           **********************************************


#include<SFML/Graphics.hpp>

using namespace sf;

class Pickup{

private:

const int HEALTH_START_VALUE=50;

const int AMMO_START_VALUE=12;

const int START_WAIT_TIME=10;

const int START_SECONDS_TO_LIVE=5;

Vector2f m_Position;

Texture m_Texture;

Sprite m_Sprite;

int m_Type; //1= health, 2-ammo

int m_Value;

IntRect m_Arena;

bool m_Spawned;

float m_SecondsSinceSpawn;

float m_SecondsSinceDeSpawn;

float m_SecondsToLive;

float m_SecondsToWait;

public:

Pickup(int type);

FloatRect getPosition();

Sprite getSprite();

void spawn();

bool isSpawned();

void update(float elapsedTime);

void setArena(IntRect arena);

void upgrade();

int gotIt();

};

Pickup::Pickup(int type){

m_Type=type;

if(m_Type==1){ // HEALTH

  m_Texture.loadFromFile("graphics/health_pickup.png");

  m_Sprite.setTexture(m_Texture);

  m_Value=HEALTH_START_VALUE;

}

else{

m_Texture.loadFromFile("graphics/ammo_pickup.png");

    m_Sprite.setTexture(m_Texture);

     m_Value=AMMO_START_VALUE;

}

m_Sprite.setOrigin(25,25);

m_SecondsToLive=START_SECONDS_TO_LIVE;

m_SecondsToWait=START_WAIT_TIME;

}

void Pickup::setArena(IntRect arena){

m_Arena.left=arena.left+50;

m_Arena.top=arena.top+50;

m_Arena.width=arena.width-50;

m_Arena.height=arena.height-50;

spawn();

}

FloatRect Pickup::getPosition(){

return m_Sprite.getGlobalBounds();

}

Sprite Pickup::getSprite(){

return m_Sprite;

}

bool Pickup::isSpawned(){

return m_Spawned;

}

void Pickup::spawn(){

srand((int)time(0)/m_Type);

m_Position.x=rand()%m_Arena.width; 

srand((int)time(0)*m_Type);

m_Position.y=rand()%m_Arena.height;

m_Sprite.setPosition(m_Position);

m_SecondsSinceSpawn=0;

m_Spawned=true;

}

void Pickup::update(float elapsedTime){

if(m_Spawned){

m_SecondsSinceSpawn=m_SecondsSinceSpawn+ elapsedTime;

}

else{

m_SecondsSinceDeSpawn=m_SecondsSinceDeSpawn+ elapsedTime;

}

if(m_SecondsSinceDeSpawn > m_SecondsToWait && !m_Spawned){

spawn();

}

if(m_SecondsSinceSpawn>m_SecondsToLive && m_Spawned){

m_Spawned=false;

m_SecondsSinceDeSpawn=0;

}

}

int Pickup::gotIt(){

m_Spawned=false;

m_SecondsSinceDeSpawn=0;

return m_Value;

}

void Pickup::upgrade(){

 if(m_Type==1){

  m_Value +=(HEALTH_START_VALUE*0.5);

 }

 else{

  m_Value +=(AMMO_START_VALUE*0.5);

 }

 m_SecondsToLive += START_SECONDS_TO_LIVE/10;

 m_SecondsToWait -=START_WAIT_TIME/10;

 }



******************************                            Player.cpp                     *********************************************************


#include<cmath>

#include <SFML/Graphics.hpp>

using namespace sf;

class Player

{

private:

const float START_SPEED = 200;

const float START_HEALTH = 100;


// Where is the player

Vector2f m_Position;


// Of course we will need a sprite

Sprite m_Sprite;


// And a texture

// !!Watch this space!!

Texture m_Texture;


// What is the screen resolution

Vector2f m_Resolution;


// What size is the current arena

IntRect m_Arena;


// How big is each tile of the arena

int m_TileSize;


// Which directions is the player currently moving in

bool m_UpPressed;

bool m_DownPressed;

bool m_LeftPressed;

bool m_RightPressed;


// How much health has the player got?

int m_Health;

// What is the maximum health the player can have

int m_MaxHealth;


// When was the player last hit

Time m_LastHit;


// Speed in pixels per second

float m_Speed;



// All our public functions will come next

public:


Player();


void spawn(IntRect arena, Vector2f resolution, int tileSize);


// Handle the player getting hit by a zombie

bool hit(Time timeHit);


// How long ago was the player last hit

Time getLastHitTime();


// Where is the player

FloatRect getPosition();


// Where is the center of the player

Vector2f getCenter();


// Which angle is the player facing

float getRotation();


// Send a copy of the sprite to main

Sprite getSprite();


// How much health has the player currently got?

int getHealth();


// The next four functions move the player

void moveLeft();


void moveRight();


void moveUp();


void moveDown();


// Stop the player moving in a specific direction

void stopLeft();


void stopRight();


void stopUp();


void stopDown();


// We will call this function once every frame

void update(float elapsedTime, Vector2i mousePosition);


// Give player a speed boost

void upgradeSpeed();


// Give the player some health

void upgradeHealth();


// Increase the maximum amount of health the player can have

void increaseHealthLevel(int amount);

void resetPlayerStats();



};




Player::Player()

{

m_Speed = START_SPEED;

m_Health = START_HEALTH;

m_MaxHealth = START_HEALTH;


// Associate a texture with the sprite

// !!Watch this space!!

m_Texture.loadFromFile("graphics/player.png");

m_Sprite.setTexture(m_Texture);


// Set the origin of the sprite to the centre, 

// for smooth rotation

m_Sprite.setOrigin(25, 25);

//m_Sprite.setPosition(1920/2.0f, 1080/2.0f);

}


void Player::spawn(IntRect arena, Vector2f resolution, int tileSize)

{

// Place the player in the middle of the arena

m_Position.x = arena.width / 2;

m_Position.y = arena.height / 2;


// Copy the details of the arena to the player's m_Arena

m_Arena.left = arena.left;

m_Arena.width = arena.width;

m_Arena.top = arena.top;

m_Arena.height = arena.height;


// Remember how big the tiles are in this arena

m_TileSize = tileSize;


// Strore the resolution for future use

m_Resolution.x = resolution.x;

m_Resolution.y = resolution.y;


}


Time Player::getLastHitTime()

{

return m_LastHit;

}


bool Player::hit(Time timeHit)

{

if (timeHit.asMilliseconds() - m_LastHit.asMilliseconds() > 200)// 2 tenths of second

{

m_LastHit = timeHit;

m_Health -= 1;

return true;

}

else

{

return false;

}


}


FloatRect Player::getPosition()

{

return m_Sprite.getGlobalBounds();

}


Vector2f Player::getCenter()

{

return m_Position;

}


float Player::getRotation()

{

return m_Sprite.getRotation();

}


Sprite Player::getSprite()

{

return m_Sprite;

}


int Player::getHealth()

{

return m_Health;

}


void Player::moveLeft()

{

m_LeftPressed = true;

}


void Player::moveRight()

{

m_RightPressed = true;

}


void Player::moveUp()

{

m_UpPressed = true;

}


void Player::moveDown()

{

m_DownPressed = true;

}


void Player::stopLeft()

{

m_LeftPressed = false;

}


void Player::stopRight()

{

m_RightPressed = false;

}


void Player::stopUp()

{

m_UpPressed = false;

}


void Player::stopDown()

{

m_DownPressed = false;

}


void Player::update(float elapsedTime, Vector2i mousePosition)

{


if (m_UpPressed)

{

m_Position.y -= m_Speed * elapsedTime;

}


if (m_DownPressed)

{

m_Position.y += m_Speed * elapsedTime;

}


if (m_RightPressed)

{

m_Position.x += m_Speed * elapsedTime;

}


if (m_LeftPressed)

{

m_Position.x -= m_Speed * elapsedTime;

}


m_Sprite.setPosition(m_Position);




// Keep the player in the arena

if (m_Position.x > m_Arena.width - m_TileSize)

{

m_Position.x = m_Arena.width - m_TileSize;

}


if (m_Position.x < m_Arena.left + m_TileSize)

{

m_Position.x = m_Arena.left + m_TileSize;

}


if (m_Position.y > m_Arena.height - m_TileSize)

{

m_Position.y = m_Arena.height - m_TileSize;

}


if (m_Position.y < m_Arena.top + m_TileSize)

{

m_Position.y = m_Arena.top + m_TileSize;

}


// Calculate the angle the player is facing

float angle = (atan2(mousePosition.y - m_Resolution.y / 2,

mousePosition.x - m_Resolution.x / 2)

* 180) / 3.141;


m_Sprite.setRotation(angle);

}


void Player::upgradeSpeed()

{

// 20% speed upgrade

m_Speed += (START_SPEED * .2);

}


void Player::upgradeHealth()

{

// 20% max health upgrade

m_MaxHealth += (START_HEALTH * .2);


}


void Player::increaseHealthLevel(int amount)

{

m_Health += amount;


// But not beyond the maximum

if (m_Health > m_MaxHealth)

{

m_Health = m_MaxHealth;

}

}

void Player::resetPlayerStats()

{

m_Speed = START_SPEED;

m_Health = START_HEALTH;

m_MaxHealth = START_HEALTH;

}


******************************************************      Zombie.cpp            ************************************************


#include<SFML/Graphics.hpp>

#include<cmath>


using namespace sf;


class Zombie{

private:

const float BLOATER_SPEED=20;

const float CHASER_SPEED=40;

const float CRAWLER_SPEED=10;

const float BLOATER_HEALTH=5;

const float CHASER_HEALTH=1;

const float CRAWLER_HEALTH=3;

Vector2f m_Position;

Sprite m_Sprite;

Texture m_Texture;

float m_Speed;

float m_Health;

bool m_Alive=false;

public:

FloatRect getPosition();

Sprite getSprite();

bool isAlive();

void spawn(float startX, float startY,int type,int seed);

void update(float elapsedTime,Vector2f playerLocation);

bool hit();

};

FloatRect Zombie::getPosition(){

return m_Sprite.getGlobalBounds();

}

Sprite Zombie::getSprite(){

return m_Sprite;

}

bool Zombie::isAlive(){

return m_Alive;

}

void Zombie::spawn(float startX, float startY,int type,int seed){

     m_Position.x=startX;

     m_Position.y=startY;

     //m_Sprite.setPosition(m_Position);

     m_Sprite.setOrigin(25,25);

     switch(type){

      case 0:

      m_Texture.loadFromFile("graphics/bloater.png");

      m_Sprite.setTexture(m_Texture);

      m_Speed=BLOATER_SPEED;

      m_Health=BLOATER_HEALTH;

      m_Alive=true;

      break;

     

      case 1:

      m_Texture.loadFromFile("graphics/chaser.png");

      m_Sprite.setTexture(m_Texture);

      m_Speed=CHASER_SPEED;

      m_Health=CHASER_HEALTH;

      m_Alive=true;

      break;

     

      case 2:

      m_Texture.loadFromFile("graphics/crawler.png");

      m_Sprite.setTexture(m_Texture);

      m_Speed=CRAWLER_SPEED;

      m_Health=CRAWLER_HEALTH;

      m_Alive=true;

      break;

     }

     srand((int)time(0)*seed);

     float modifier=(rand() % (101-70)+70);

     modifier=modifier/100;

     m_Speed=m_Speed*modifier;

     

     }

     void Zombie::update(float elapsedTime,Vector2f playerLocation){

     if(m_Alive){

      float playerX=playerLocation.x;

      float playerY=playerLocation.y;

      if(m_Position.x<playerX){

      m_Position.x=m_Position.x+m_Speed*elapsedTime;

      }

      if(m_Position.x>playerX){

      m_Position.x=m_Position.x-m_Speed*elapsedTime;

      }

      if(m_Position.y<playerY){

      m_Position.y=m_Position.y+m_Speed*elapsedTime;

      }

      if(m_Position.y>playerY){

      m_Position.y=m_Position.y-m_Speed*elapsedTime;

      }

      m_Sprite.setPosition(m_Position);

      float angle=(atan2(playerY-m_Position.y,playerX-m_Position.x)*180)/3.141;

      m_Sprite.setRotation(angle);

      }

     }

     bool Zombie::hit(){

      m_Health--;

      if(m_Health<0){

      m_Alive=false;

      m_Texture.loadFromFile("graphics/blood.png");

      m_Sprite.setTexture(m_Texture);

      return true;

      }

      return false;

     

     }



******************************************             ZombieAreana.cpp                     ******************************************************


#include <SFML/Graphics.hpp>

#include <iostream>

#include"Player.cpp"

#include"zombie.cpp"

#include"bullet.cpp"

#include"pickup.cpp"

#include<sstream>

using namespace sf;

int createBackground(VertexArray& rVA, IntRect arena);

Zombie* createHorde(int numZombies,IntRect arena);

int main()

{

int wave=0;

// The game will always be in one of four states

enum class State { PAUSED, LEVELING_UP, GAME_OVER, PLAYING };

// Start with the GAME_OVER state

State state = State::GAME_OVER;

// Get the screen resolution and create an SFML window

Vector2f resolution;

//resolution.x = VideoMode::getDesktopMode().width;

//resolution.y = VideoMode::getDesktopMode().height;

resolution.x = 1920;

    resolution.y = 1080;

std::cout<<resolution.x<<resolution.y;

RenderWindow window(VideoMode(resolution.x, resolution.y),

"Zombie Arena", Style::Fullscreen);

// Create a an SFML View for the main action

View mainView(sf::FloatRect(0, 0, resolution.x, resolution.y));

window.setView(mainView);

     int numZombies;

     int numZombiesAlive;

     Zombie *zombies=nullptr;

     

     Bullet bullets[100];

int currentBullet = 0;

int bulletsSpare = 24;

int bulletsInClip = 6;

int clipSize = 6;

float fireRate = 1;

Time lastPressed;

// Here is our clock for timing everything

Clock clock;

// How long has the PLAYING state been active

Time gameTimeTotal;

    

// Where is the mouse in relation to world coordinates

Vector2f mouseWorldPosition;

// Where is the mouse in relation to screen coordinates

Vector2i mouseScreenPosition;

window.setMouseCursorVisible(true);

Texture textureCrosshair;

textureCrosshair.loadFromFile("graphics/crosshair.png");

Sprite spriteCrosshair;

spriteCrosshair.setTexture(textureCrosshair);

spriteCrosshair.setOrigin(25, 25);

// Create an instance of the Player class

Player player;

// The boundaries of the arena

IntRect arena;

// Create the background

VertexArray background;

// Load the texture for our background vertex array

Texture textureBackground;

textureBackground.loadFromFile("graphics/background_sheet.png");

int score=0;

int hiScore=0;

Pickup healthPickup(1);

Pickup ammoPickup(2);

// For the home/game over screen

Sprite spriteGameOver;

Texture textureGameOver;

textureGameOver.loadFromFile("graphics/background.png");

spriteGameOver.setTexture(textureGameOver);

spriteGameOver.setPosition(0, 0);


// Create a view for the HUD

View hudView(sf::FloatRect(0, 0, resolution.x, resolution.y));


// Create a sprite for the ammo icon

Sprite spriteAmmoIcon;

Texture textureAmmoIcon;

textureAmmoIcon.loadFromFile("graphics/ammo_icon.png");

spriteAmmoIcon.setTexture(textureAmmoIcon);

spriteAmmoIcon.setPosition(20, 980);


// Load the font

Font font;

font.loadFromFile("fonts/zombiecontrol.ttf");


// Paused

Text pausedText;

pausedText.setFont(font);

pausedText.setCharacterSize(155);

pausedText.setFillColor(Color::White);

pausedText.setPosition(400, 400);

pausedText.setString("Press Enter \nto continue");


// Game Over

Text gameOverText;

gameOverText.setFont(font);

gameOverText.setCharacterSize(125);

gameOverText.setFillColor(Color::White);

gameOverText.setPosition(250, 850);

gameOverText.setString("Press Enter to play");


// Levelling up

Text levelUpText;

levelUpText.setFont(font);

levelUpText.setCharacterSize(80);

levelUpText.setFillColor(Color::White);

levelUpText.setPosition(150, 250);

std::stringstream levelUpStream;

levelUpStream <<

"1- Increased rate of fire" <<

"\n2- Increased clip size(next reload)" <<

"\n3- Increased max health" <<

"\n4- Increased run speed" <<

"\n5- More and better health pickups" <<

"\n6- More and better ammo pickups";

levelUpText.setString(levelUpStream.str());


// Ammo

Text ammoText;

ammoText.setFont(font);

ammoText.setCharacterSize(55);

ammoText.setFillColor(Color::White);

ammoText.setPosition(200, 980);


// Score

Text scoreText;

scoreText.setFont(font);

scoreText.setCharacterSize(55);

scoreText.setFillColor(Color::White);

scoreText.setPosition(20, 0);


// Hi Score

Text hiScoreText;

hiScoreText.setFont(font);

hiScoreText.setCharacterSize(55);

hiScoreText.setFillColor(Color::White);

hiScoreText.setPosition(1400, 0);

std::stringstream s;

s << "Hi Score:" << hiScore;

hiScoreText.setString(s.str());


// Zombies remaining

Text zombiesRemainingText;

zombiesRemainingText.setFont(font);

zombiesRemainingText.setCharacterSize(55);

zombiesRemainingText.setFillColor(Color::White);

zombiesRemainingText.setPosition(1500, 980);

zombiesRemainingText.setString("Zombies: 100");



Text waveNumberText;

waveNumberText.setFont(font);

waveNumberText.setCharacterSize(55);

waveNumberText.setFillColor(Color::White);

waveNumberText.setPosition(1250, 980);

waveNumberText.setString("Wave: 0");


// Health bar

RectangleShape healthBar;

healthBar.setFillColor(Color::Red);

healthBar.setPosition(450, 980);

// When did we last update the HUD?

int framesSinceLastHUDUpdate = 0;


// How often (in frames) should we update the HUD

int fpsMeasurementFrameInterval = 1000;

// The main game loop

while (window.isOpen())

{

Event event;

while (window.pollEvent(event))

{

if (event.type == Event::KeyPressed)

{

// Pause a game while playing

if (event.key.code == Keyboard::Return &&

state == State::PLAYING)

{

state = State::PAUSED;

}


// Restart while paused

else if (event.key.code == Keyboard::Return &&

state == State::PAUSED)

{

state = State::PLAYING;

// Reset the clock so there isn't a frame jump

clock.restart();

}


// Start a new game while in GAME_OVER state

else if (event.key.code == Keyboard::Return &&

state == State::GAME_OVER)

{

state = State::LEVELING_UP;

wave=0;

currentBullet = 0;

bulletsSpare = 24;

bulletsInClip = 6;

clipSize = 6;

fireRate = 1;

score=0;

player.resetPlayerStats();

}


if (state == State::PLAYING)

{

if (event.key.code == Keyboard::R)

{

if (bulletsSpare >= clipSize)

{

// Plenty of bullets. Reload.

bulletsInClip = clipSize;

bulletsSpare -= clipSize;

}

else if (bulletsSpare > 0)

{

// Only few bullets left

bulletsInClip = bulletsSpare;

bulletsSpare = 0;

}

else

{

// More here soon?!

}

}

}


}

}// End event polling



// Handle the player quitting

if (Keyboard::isKeyPressed(Keyboard::Escape))

{

window.close();

}


// Handle controls while playing

if (state == State::PLAYING)

{

// Handle the pressing and releasing of the WASD keys

if (Keyboard::isKeyPressed(Keyboard::W))

{

player.moveUp();

}

else

{

player.stopUp();

}


if (Keyboard::isKeyPressed(Keyboard::S))

{

player.moveDown();

}

else

{

player.stopDown();

}


if (Keyboard::isKeyPressed(Keyboard::A))

{

player.moveLeft();

}

else

{

player.stopLeft();

}


if (Keyboard::isKeyPressed(Keyboard::D))

{

player.moveRight();

}

else

{

player.stopRight();

}

// Fire a bullet

if (sf::Mouse::isButtonPressed(sf::Mouse::Left))

{


if (gameTimeTotal.asMilliseconds()

- lastPressed.asMilliseconds()

> 1000 / fireRate && bulletsInClip > 0)

{


// Pass the centre of the player 

// and the centre of the cross-hair

// to the shoot function

bullets[currentBullet].shoot(

player.getCenter().x, player.getCenter().y,

mouseWorldPosition.x, mouseWorldPosition.y);


currentBullet++;

if (currentBullet > 99)

{

currentBullet = 0;

}

lastPressed = gameTimeTotal;


bulletsInClip--;

}


}


}// End WASD while playing


// Handle the levelling up state

if (state == State::LEVELING_UP)

{

// Handle the player levelling up

if (event.key.code == Keyboard::Num1)

{

fireRate++;

state = State::PLAYING;

}


if (event.key.code == Keyboard::Num2)

{

clipSize+=clipSize;

state = State::PLAYING;

}


if (event.key.code == Keyboard::Num3)

{

player.upgradeHealth();

state = State::PLAYING;

}


if (event.key.code == Keyboard::Num4)

{

player.upgradeSpeed();

state = State::PLAYING;

}


if (event.key.code == Keyboard::Num5)

{

//healthPickup.upgrade();

state = State::PLAYING;

}


if (event.key.code == Keyboard::Num6)

{

//ammoPickup.upgrade();

state = State::PLAYING;

}


if (state == State::PLAYING)

{

// Prepare thelevel

// We will modify the next two lines later

wave++;

arena.width = wave*500;

arena.height = wave*500;

arena.left = 0;

arena.top = 0;


// Pass the vertex array by reference 

// to the createBackground function

int tileSize = createBackground(background, arena);


// Spawn the player in the middle of the arena

player.spawn(arena, resolution, tileSize);

numZombies=wave*2;

delete[]zombies;

zombies=createHorde(numZombies,arena);

numZombiesAlive=numZombies;

healthPickup.setArena(arena);

ammoPickup.setArena(arena);

// Reset the clock so there isn't a frame jump

clock.restart();

}

}// End levelling up


/*

****************

UPDATE THE FRAME

****************

*/

if (state == State::PLAYING)

{

// Update the delta time

Time dt = clock.restart();

// Update the total game time

gameTimeTotal += dt;

// Make a decimal fraction of 1 from the delta time

float dtAsSeconds = dt.asSeconds();


// Where is the mouse pointer

mouseScreenPosition = Mouse::getPosition();


// Convert mouse position to world coordinates of mainView

mouseWorldPosition = window.mapPixelToCoords(

Mouse::getPosition(), mainView);

           spriteCrosshair.setPosition(mouseWorldPosition);

   

// Update the player

player.update(dtAsSeconds, Mouse::getPosition());


// Make a note of the players new position

Vector2f playerPosition(player.getCenter());


// Make the view centre around the player

     mainView.setCenter(player.getCenter());

     for(int i=0;i<numZombies;i++){

      zombies[i].update(dtAsSeconds,playerPosition);

     }

     

     // Update any bullets that are in-flight

for (int i = 0; i < 100; i++)

{

if (bullets[i].isInFlight())

{

bullets[i].update(dtAsSeconds);

}

}

// Pickup updates

healthPickup.update(dtAsSeconds);

ammoPickup.update(dtAsSeconds);

//Collision

for (int i = 0; i < 100; i++)

{

for (int j = 0; j < numZombies; j++)

{

if (bullets[i].isInFlight() &&

zombies[j].isAlive())

{

if (bullets[i].getPosition().intersects

(zombies[j].getPosition()))

{

// Stop the bullet

bullets[i].stop();


// Register the hit and see if it was a kill

if (zombies[j].hit()) {

// Not just a hit but a kill too

score += 10;

if (score >= hiScore)

{

hiScore = score;

}


numZombiesAlive--;


// When all the zombies are dead (again)

if (numZombiesAlive == 0) {

state = State::LEVELING_UP;

}

}


}

}


}

}

for (int i = 0; i < numZombies; i++)

{

if (player.getPosition().intersects

(zombies[i].getPosition()) && zombies[i].isAlive())

{


if (player.hit(gameTimeTotal))

{

// More here later

}


if (player.getHealth() <= 0)

{

state = State::GAME_OVER;


}

}

}

if (player.getPosition().intersects

(healthPickup.getPosition()) && healthPickup.isSpawned())

{

player.increaseHealthLevel(healthPickup.gotIt());


}


// Has the player touched ammo pickup

if (player.getPosition().intersects

(ammoPickup.getPosition()) && ammoPickup.isSpawned())

{

bulletsSpare += ammoPickup.gotIt();


}

// size up the health bar

healthBar.setSize(Vector2f(player.getHealth() * 3, 70));

framesSinceLastHUDUpdate++;

// Calculate FPS every fpsMeasurementFrameInterval frames

if (framesSinceLastHUDUpdate > fpsMeasurementFrameInterval)

{


// Update game HUD text

std::stringstream ssAmmo;

std::stringstream ssScore;

std::stringstream ssHiScore;

std::stringstream ssWave;

std::stringstream ssZombiesAlive;


// Update the ammo text

ssAmmo << bulletsInClip << "/" << bulletsSpare;

ammoText.setString(ssAmmo.str());


// Update the score text

ssScore << "Score:" << score;

scoreText.setString(ssScore.str());


// Update the high score text

ssHiScore << "Hi Score:" << hiScore;

hiScoreText.setString(ssHiScore.str());


// Update the wave

ssWave << "Wave:" << wave;

waveNumberText.setString(ssWave.str());


// Update the high score text

ssZombiesAlive << "Zombies:" << numZombiesAlive;

zombiesRemainingText.setString(ssZombiesAlive.str());


framesSinceLastHUDUpdate = 0;

}


}// End updating the scene

        


/*

**************

Draw the scene

**************

*/


if (state == State::PLAYING)

{

window.clear();


// set the mainView to be displayed in the window

// And draw everything related to it

window.setView(mainView);


// Draw the background

//mainView.setCenter(Vector2f(arena.width/2, arena.height/2));

window.draw(background, &textureBackground);

for (int i = 0; i < 100; i++)

{

if (bullets[i].isInFlight())

{

window.draw(bullets[i].getShape());

}

}

// Draw the player

window.draw(player.getSprite());

for(int i=0; i<numZombies;i++){

window.draw(zombies[i].getSprite());

}

window.draw(spriteCrosshair);

// Draw pickup

if(ammoPickup.isSpawned()){

window.draw(ammoPickup.getSprite());

}

if(healthPickup.isSpawned()){

window.draw(healthPickup.getSprite());

}

window.setView(hudView);

window.draw(healthBar);

window.draw(spriteAmmoIcon);

window.draw(ammoText);

window.draw(scoreText);

window.draw(hiScoreText);

window.draw(waveNumberText);

window.draw(zombiesRemainingText);

}// end of draw while playing


if (state == State::LEVELING_UP)

{

window.draw(spriteGameOver);

window.draw(levelUpText);

}


if (state == State::PAUSED)

{

window.draw(pausedText);

}


if (state == State::GAME_OVER)

{

window.draw(spriteGameOver);

window.draw(gameOverText);

window.draw(scoreText);

window.draw(hiScoreText);

}


window.display();


}// End game loop


return 0;

}

int createBackground(VertexArray& rVA, IntRect arena)

{

// Anything we do to rVA we are actually doing to background (in the main function)


// How big is each tile/texture

const int TILE_SIZE = 50;

const int TILE_TYPES = 3;

const int VERTS_IN_QUAD = 4;


int worldWidth = arena.width / TILE_SIZE;

int worldHeight = arena.height / TILE_SIZE;


// What type of primitive are we using?

rVA.setPrimitiveType(Quads);


// Set the size of the vertex array

rVA.resize(worldWidth * worldHeight * VERTS_IN_QUAD);


// Start at the beginning of the vertex array

int currentVertex = 0;

for (int w = 0; w < worldWidth; w++){

for (int h = 0; h < worldHeight; h++){

// Position each vertex in the current quad

rVA[currentVertex + 0].position = Vector2f(w * TILE_SIZE, h * TILE_SIZE);

rVA[currentVertex + 1].position = Vector2f((w * TILE_SIZE) + TILE_SIZE, h * TILE_SIZE);

rVA[currentVertex + 2].position = Vector2f((w * TILE_SIZE) + TILE_SIZE, (h * TILE_SIZE) + TILE_SIZE);

rVA[currentVertex + 3].position = Vector2f((w * TILE_SIZE), (h * TILE_SIZE) + TILE_SIZE);


// Define the position in the Texture to draw for current quad

// Either mud, stone, grass or wall

if (h == 0 || h == worldHeight - 1 || w == 0 || w == worldWidth - 1)

{

// Use the wall texture

rVA[currentVertex + 0].texCoords = Vector2f(0, 0 + TILE_TYPES * TILE_SIZE);

rVA[currentVertex + 1].texCoords = Vector2f(TILE_SIZE, 0 + TILE_TYPES * TILE_SIZE);

rVA[currentVertex + 2].texCoords = Vector2f(TILE_SIZE, TILE_SIZE + TILE_TYPES * TILE_SIZE);

rVA[currentVertex + 3].texCoords = Vector2f(0, TILE_SIZE + TILE_TYPES * TILE_SIZE);

}

else

{

// Use a random floor texture

srand((int)time(0) + h * w - h);

int mOrG = (rand() % TILE_TYPES);

int verticalOffset = mOrG * TILE_SIZE;


rVA[currentVertex + 0].texCoords = Vector2f(0, 0 + verticalOffset);

rVA[currentVertex + 1].texCoords = Vector2f(TILE_SIZE, 0 + verticalOffset);

rVA[currentVertex + 2].texCoords = Vector2f(TILE_SIZE, TILE_SIZE + verticalOffset);

rVA[currentVertex + 3].texCoords = Vector2f(0, TILE_SIZE + verticalOffset);


}


// Position ready for the next for vertices

currentVertex = currentVertex + VERTS_IN_QUAD;

}

}


return TILE_SIZE;

}


Zombie* createHorde(int numZombies,IntRect arena){

Zombie* zombies=new Zombie[numZombies];

int maxX=arena.width-20;

int minX=arena.left+20;

int maxY=arena.height-20;

int minY=arena.top+20;

for(int i=0;i<numZombies;i++){

srand((int)time(0)*i);

int side=(rand()%4);

float x,y;

switch(side){

case 0:

x=minX;

y=(rand()%maxY)+minY;

break;

case 1:

x=maxX;

y=(rand()%maxY)+minY;

break;

case 2:

y=minY;

x=(rand()%maxX)+minX;

break;

case 3:

y=maxY;

x=(rand()%maxX)+minX;

break;

}

srand((int)time(0)*i*2);

int type=(rand()%3);

zombies[i].spawn(x,y,type,i);

}

return zombies;

}










































































No comments:

Post a Comment

c game

 ##########################################                                TIMBER                                   ########################...