Page 1 of 2 12 LastLast
Results 1 to 20 of 23
Like Tree1Likes

Thread: code for timing which is every levels have different degree of difficulty.

  1. #1
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default code for timing which is every levels have different degree of difficulty.

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;

    /**
    * The main hook of our game. This class with both act as a manager
    * for the display and central mediator for the game logic.
    *
    * Display management will consist of a loop that cycles round all
    * entities in the game asking them to move and then drawing them
    * in the appropriate place. With the help of an inner class it
    * will also allow the player to control the main ship.
    *
    * As a mediator it will be informed when entities within our game
    * detect events (e.g. alient killed, played died) and will take
    * appropriate game actions.
    *
    * @author Kevin Glass
    */
    /************************************************** *****

    * Class name:Game
    * Inheritance:
    * Attributes:gameRunning,moveSpeed,lastFire,firingIn terval,alienCount,message,waitingForKeyPress,leftP ressed,rightPressed,firePressed,logicRequiredThisL oop
    * Methods:private void startGame()
    * private void initEntities()
    * public void updateLogic()
    * public void removeEntity(Entity entity)
    * public void notifyDeath()
    * public void notifyWin()
    * public void notifyAlienKilled()
    * public void tryToFire()
    * public void gameLoop()
    * public static void main(String argv[])
    * Functionality: This class with both act as a manager for the display and central mediator for the game logic.
    * Visibility: display overall game
    * From requirement number :

    ************************************************** *****/
    public class Game extends Canvas {
    /** The stragey that allows us to use accelerate page flipping */
    private BufferStrategy strategy;
    /** True if the game is currently "running", i.e. the game loop is looping */
    private boolean gameRunning = true;
    /** The list of all the entities that exist in our game */
    private ArrayList entities = new ArrayList();
    /** The list of entities that need to be removed from the game this loop */
    private ArrayList removeList = new ArrayList();
    /** The entity representing the player */
    private Entity ship;
    /** The speed at which the player's ship should move (pixels/sec) */
    private double moveSpeed = 300;
    /** The time at which last fired a shot */
    private long lastFire = 0;
    /** The interval between our players shot (ms) */
    private long firingInterval = 500;
    /** The number of aliens left on the screen */
    private int alienCount;
    private int countAlienKilled = 0;
    /** The message to display which waiting for a key press */
    private String message = "";
    private String scoreStr = ""; //Edit
    /** True if we're holding up game play until a key has been pressed */
    private boolean waitingForKeyPress = true;
    /** True if the left cursor key is currently pressed */
    private boolean leftPressed = false;
    /** True if the right cursor key is currently pressed */
    private boolean rightPressed = false;
    /** True if we are firing */
    private boolean firePressed = false;
    /** True if game logic needs to be applied this loop, normally as a result of a game event */
    private boolean logicRequiredThisLoop = false;


    private int level = 0; //Edit
    private int score = 0; //Edit
    /**
    * Construct our game and set it running.
    */
    public Game() {
    String inputStr = JOptionPane.showInputDialog("Enter level to start (eg: 1):");
    level = Integer.parseInt(inputStr);
    // create a frame to contain our game

    JFrame container = new JFrame("Space Invaders 2013");

    // get hold the content of the frame and set up the resolution of the game

    JPanel panel = (JPanel) container.getContentPane();
    panel.setPreferredSize(new Dimension(800,600));
    panel.setLayout(null);

    // setup our canvas size and put it into the content of the frame

    setBounds(0,0,800,600);
    panel.add(this);

    // Tell AWT not to bother repainting our canvas since we're
    // going to do that our self in accelerated mode

    setIgnoreRepaint(true);

    // finally make the window visible

    container.pack();
    container.setResizable(false);
    container.setVisible(true);

    // add a listener to respond to the user closing the window. If they
    // do we'd like to exit the game

    container.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    }
    });

    // add a key input system (defined below) to our canvas
    // so we can respond to key pressed

    addKeyListener(new KeyInputHandler());

    // request the focus so key events come to us

    requestFocus();

    // create the buffering strategy which will allow AWT
    // to manage our accelerated graphics

    createBufferStrategy(2);
    strategy = getBufferStrategy();

    // initialise the entities in our game so there's something
    // to see at startup

    initEntities();
    }

    /**
    * Start a fresh game, this should clear out any old data and
    * create a new set.
    */
    /************************************************** *****

    * Method name:private void startGame()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Start a fresh game, this should clear out any old data and create a new set.
    * Visibility:new game
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    private void startGame() {
    // clear out any existing entities and intialise a new set


    entities.clear();
    initEntities();

    // blank out any keyboard settings we might currently have

    leftPressed = false;
    rightPressed = false;
    firePressed = false;
    }

    /**
    * Initialise the starting state of the entities (ship and aliens). Each
    * entitiy will be added to the overall list of entities in the game.
    */
    /************************************************** *****

    * Method name:private void initEntities()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Initialise the starting state of the entities (ship and aliens).
    * Each entitiy will be added to the overall list of entities in the game.
    * Visibility:
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    private void initEntities() {
    // create the player ship and place it roughly in the center of the screen

    ship = new ShipEntity(this,"fullScreens/ship.gif",370,550);
    entities.add(ship);

    // create a block of aliens (5 rows, by 12 aliens, spaced evenly)

    alienCount = 0;
    for (int row=0;row<level;row++) {
    for (int x=0;x<12;x++) {
    Entity alien = new AlienEntity(this,"fullScreens/alien.gif",100+(x*50),(50)+row*30);
    entities.add(alien);
    alienCount++;
    }
    }
    }

    /**
    * Notification from a game entity that the logic of the game
    * should be run at the next opportunity (normally as a result of some
    * game event)
    */
    /************************************************** *****

    * Method name: public void updateLogic()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification from a game entity that the logic of the game
    * should be run at the next opportunity (normally as a result of some game event)
    * Visibility:
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void updateLogic() {
    logicRequiredThisLoop = true;
    }

    /**
    * Remove an entity from the game. The entity removed will
    * no longer move or be drawn.
    *
    * @param entity The entity that should be removed
    */
    /************************************************** *****

    * Method name:public void removeEntity(Entity entity)
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Remove an entity from the game
    * Visibility:The entity removed will no longer move or be drawn.
    * @param:entity The entity that should be removed
    * @return:
    * From requirement number
    ************************************************** *****/
    public void removeEntity(Entity entity) {
    removeList.add(entity);
    }

    /**
    * Notification that the player has died.
    */
    /************************************************** *****

    * Method name:public void notifyDeath()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification that the player has died
    * Visibility:player has died
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void notifyDeath() {
    message = "Oh no! They got you, try again?";
    waitingForKeyPress = true;
    }

    /**
    * Notification that the player has won since all the aliens
    * are dead.
    */
    /************************************************** *****

    * Method name:public void notifyWin()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification that the player has won since all the aliens are dead.
    * Visibility:all the aliens are dead and players win
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void notifyWin() {
    score = (countAlienKilled) * 10; //Edited
    scoreStr = "Score: "+score; //Edited
    message = "Well done! You Win!";
    waitingForKeyPress = true;
    }

    /**
    * Notification that an alien has been killed
    */
    /************************************************** *****

    * Method name:public void notifyAlienKilled()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality: Notification that an alien has been killed
    * Visibility: allien has been killed
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void notifyAlienKilled() {
    // reduce the alient count, if there are none left, the player has won!

    alienCount--;
    countAlienKilled++;

    if (alienCount == 0) {
    notifyWin();
    }

    // if there are still some aliens left then they all need to get faster, so
    // speed up all the existing aliens

    for (int i=0;i<entities.size();i++) {
    Entity entity = (Entity) entities.get(i);

    if (entity instanceof AlienEntity) {
    // speed up by 2%

    entity.setHorizontalMovement(entity.getHorizontalM ovement() * 1.02);
    }
    }
    }

    /**
    * Attempt to fire a shot from the player. Its called "try"
    * since we must first check that the player can fire at this
    * point, i.e. has he/she waited long enough between shots
    */
    /************************************************** *****

    * Method name:public void tryToFire()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Attempt to fire a shot from the player
    * Visibility:to fire a shot
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void tryToFire() {
    // check that we have waiting long enough to fire

    if (System.currentTimeMillis() - lastFire < firingInterval) {
    return;
    }

    // if we waited long enough, create the shot entity, and record the time.

    lastFire = System.currentTimeMillis();
    ShotEntity shot = new ShotEntity(this,"fullScreens/shot.gif",ship.getLocationRow()+10,ship.getLocatio nColumn()-30);
    entities.add(shot);
    }

    /**
    * The main game loop. This loop is running during all game
    * play as is responsible for the following activities:
    * <p>
    * - Working out the speed of the game loop to update moves
    * - Moving the game entities
    * - Drawing the screen contents (entities, text)
    * - Updating game events
    * - Checking Input
    * <p>
    */

    /************************************************** *****

    * Method name:public void gameLoop()
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality: This loop is running during all game
    * play as is responsible for
    * Working out the speed of the game loop to update moves
    * Drawing the screen contents (entities, text)
    * Updating game events
    * Checking Input
    * Visibility:
    * @param:
    * @return:
    * From requirement number
    ************************************************** *****/
    public void gameLoop() {

    long lastLoopTime = System.currentTimeMillis();

    // keep looping round til the game ends

    while (gameRunning) {
    // work out how long its been since the last update, this
    // will be used to calculate how far the entities should
    // move this loop

    long delta = System.currentTimeMillis() - lastLoopTime;
    lastLoopTime = System.currentTimeMillis();

    // Get hold of a graphics context for the accelerated
    // surface and blank it out

    Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
    g.setColor(Color.black);
    g.fillRect(0,0,800,600);

    // cycle round asking each entity to move itself

    if (!waitingForKeyPress) {
    for (int i=0;i<entities.size();i++) {
    Entity entity = (Entity) entities.get(i);

    entity.move(delta);
    }
    }

    // cycle round drawing all the entities we have in the game

    for (int i=0;i<entities.size();i++) {
    Entity entity = (Entity) entities.get(i);

    entity.draw(g);
    }

    // brute force collisions, compare every entity against
    // every other entity. If any of them collide notify
    // both entities that the collision has occured

    for (int p=0;p<entities.size();p++) {
    for (int s=p+1;s<entities.size();s++) {
    Entity rec = (Entity) entities.get(p);
    Entity otherRec = (Entity) entities.get(s);

    if (rec.collidesWith(otherRec)) {
    rec.collidedWith(otherRec);
    otherRec.collidedWith(rec);
    }
    }
    }

    // remove any entity that has been marked for clear up

    entities.removeAll(removeList);
    removeList.clear();

    // if a game event has indicated that game logic should
    // be resolved, cycle round every entity requesting that
    // their personal logic should be considered.

    if (logicRequiredThisLoop) {
    for (int i=0;i<entities.size();i++) {
    Entity entity = (Entity) entities.get(i);
    entity.doLogic();
    }

    logicRequiredThisLoop = false;
    }

    // if we're waiting for an "any key" press then draw the
    // current message

    if (waitingForKeyPress) {
    g.setColor(Color.white);
    g.drawString("No. of Alien Killed: "+countAlienKilled,(800-g.getFontMetrics().stringWidth(String.valueOf("No. of Alien Killed: "+countAlienKilled)))/2,150);//Edited
    g.drawString(scoreStr,(800-g.getFontMetrics().stringWidth(scoreStr))/2,200); //Edited
    g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
    g.drawString("Current Level: "+level,(800-g.getFontMetrics().stringWidth("Current Level: "+level))/2,300);
    g.drawString("Press any key to go to the next level",(800-g.getFontMetrics().stringWidth("Press any key to go to the next level"))/2,350);
    }

    // finally, we've completed drawing so clear up the graphics
    // and flip the buffer over

    g.dispose();
    strategy.show();

    // resolve the movement of the ship. First assume the ship
    // isn't moving. If either cursor key is pressed then
    // update the movement appropraitely

    ship.setHorizontalMovement(0);

    if ((leftPressed) && (!rightPressed)) {
    ship.setHorizontalMovement(-moveSpeed);
    } else if ((rightPressed) && (!leftPressed)) {
    ship.setHorizontalMovement(moveSpeed);
    }

    // if we're pressing fire, attempt to fire

    if (firePressed) {
    tryToFire();
    }

    // finally pause for a bit. Note: this should run us at about
    // 100 fps but on windows this might vary each loop due to
    // a bad implementation of timer

    try { Thread.sleep(10); } catch (Exception e) {}
    }
    }

    /**
    * A class to handle keyboard input from the user. The class
    * handles both dynamic input during game play, i.e. left/right
    * and shoot, and more static type input (i.e. press any key to
    * continue)
    *
    * This has been implemented as an inner class more through
    * habbit then anything else. Its perfectly normal to implement
    * this as seperate class if slight less convienient.
    *
    * @author Kevin Glass
    */

    /************************************************** *****

    * Class name: KeyInputHandler
    * Inheritance:
    * Attributes: pressCount
    * Methods: public void keyPressed(KeyEvent e)
    * public void keyReleased(KeyEvent e)
    * public void keyTyped(KeyEvent e)
    *
    * Functionality:A class to handle keyboard input from the user
    * Visibility: press any key to continue
    * From requirement number :

    ************************************************** *****/

    private class KeyInputHandler extends KeyAdapter {
    /** The number of key presses we've had while waiting for an "any key" press */
    private int pressCount = 1;

    /**
    * Notification from AWT that a key has been pressed. Note that
    * a key being pressed is equal to being pushed down but *NOT*
    * released. Thats where keyTyped() comes in.
    *
    * @param e The details of the key that was pressed
    */

    /************************************************** *****

    * Method name: public void keyPressed(KeyEvent e)
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification from AWT that a key has been pressed
    * Visibility:a key has been pressed
    * @param: e The details of the key that was pressed
    * @return:
    * From requirement number
    ************************************************** *****/
    public void keyPressed(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "press"
    if (waitingForKeyPress) {
    return;
    }


    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = true;
    }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = true;
    }
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = true;
    }
    }

    /**
    * Notification from AWT that a key has been released.
    *
    * @param e The details of the key that was released
    */
    /************************************************** *****

    * Method name: public void keyReleased(KeyEvent e)
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification from AWT that a key has been released.
    * Visibility:
    * @param:e The details of the key that was released
    * @return:
    * From requirement number
    ************************************************** *****/
    public void keyReleased(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "released"
    if (waitingForKeyPress) {
    return;
    }

    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = false;
    }
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = false;
    }
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = false;
    }
    }

    /**
    * Notification from AWT that a key has been typed. Note that
    * typing a key means to both press and then release it.
    *
    * @param e The details of the key that was typed.
    */
    /************************************************** *****

    * Method name:public void keyTyped(KeyEvent e)
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:Notification from AWT that a key has been typed.
    * Visibility:Note that typing a key means to both press and then release it.
    * @param: e The details of the key that was typed.
    * @return:
    * From requirement number
    ************************************************** *****/
    public void keyTyped(KeyEvent e) {
    // if we're waiting for a "any key" type then
    // check if we've recieved any recently. We may
    // have had a keyType() event from the user releasing
    // the shoot or move keys, hence the use of the "pressCount"
    // counter.

    if (waitingForKeyPress) {
    if (pressCount == 1) {
    // since we've now recieved our key typed
    // event we can mark it as such and start
    // our new game

    waitingForKeyPress = false;
    startGame();
    pressCount = 0;
    } else {
    pressCount++;
    level++; //NextLevel //Edited
    }
    }

    // if we hit escape, then quit the game

    if (e.getKeyChar() == 27) {
    System.exit(0);
    }
    }
    }

    /**
    * The entry point into the game. We'll simply create an
    * instance of class which will start the display and game
    * loop.
    *
    * @param argv The arguments that are passed into our game
    */
    /************************************************** *****

    * Method name:public static void main(String argv[])
    * Inheritance:
    * Attributes:
    * Precondition:
    * Postcondition:
    * Functionality:The entry point into the game. create an instance of class which will start the display and game loop
    * Visibility:
    * @param:argv The arguments that are passed into our game
    * @return:
    * From requirement number
    ************************************************** *****/
    public static void main(String argv[]) {
    Game g =new Game();
    // Start the main game loop, note: this method will not
    // return until the game has finished running. Hence we are
    // using the actual main thread to run the game.

    g.gameLoop();

    }
    }

  2. #2
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    somebody please help me..
    i really dont know how start the timing code..

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    Moved from Applets section.

    Do you have any specific questions about the posted code?

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    lya likes this.
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Red face Re: code for timing which is every levels have different degree of difficulty.

    Quote Originally Posted by Norm View Post
    Moved from Applets section.

    Do you have any specific questions about the posted code?

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    can you help solve my problem?

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    can you help solve my problem?
    Can you explain what problem(s) you are having? Ask some specific questions about the problems. Post the program's output with some comments saying what is wrong and show what it should be.

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Quote Originally Posted by Norm View Post
    Can you explain what problem(s) you are having? Ask some specific questions about the problems. Post the program's output with some comments saying what is wrong and show what it should be.

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    actually i already enhance this game with levels then now i have problem to add every levels with different timing.. example : levels 1 = 60 seconds , level 2= 55 seconds then level 3 = 50seconds and so on.. Means that if more level increase the time will faster. I want to show that this game have difficulty of time every levels.

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    Please edit your post and wrap your code with code tags:
    [code]
    YOUR CODE HERE
    [/code]
    to get highlighting and preserve formatting.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    
    /**
     * The main hook of our game. This class with both act as a manager
     * for the display and central mediator for the game logic. 
     * 
     * Display management will consist of a loop that cycles round all
     * entities in the game asking them to move and then drawing them
     * in the appropriate place. With the help of an inner class it
     * will also allow the player to control the main ship.
     * 
     * As a mediator it will be informed when entities within our game
     * detect events (e.g. alient killed, played died) and will take
     * appropriate game actions.
     * 
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name:Game
       *  Inheritance:
       *  Attributes:gameRunning,moveSpeed,lastFire,firingInterval,alienCount,message,waitingForKeyPress,leftPressed,rightPressed,firePressed,logicRequiredThisLoop
       *  Methods:private void startGame()
       *          private void initEntities()
       *          public void updateLogic()
       *          public void removeEntity(Entity entity) 
       *          public void notifyDeath()
       *          public void notifyWin()
       *          public void notifyAlienKilled()
       *          public void tryToFire() 
       *          public void gameLoop()
       *          public static void main(String argv[])
       *  Functionality: This class with both act as a manager for the display and central mediator for the game logic. 
       *  Visibility: display overall game
       *  From requirement number : 
    
    *******************************************************/
    public class Game extends Canvas {
        /** The stragey that allows us to use accelerate page flipping */
        private BufferStrategy strategy;
        /** True if the game is currently "running", i.e. the game loop is looping */
        private boolean gameRunning = true;
        /** The list of all the entities that exist in our game */
        private ArrayList entities = new ArrayList();
        /** The list of entities that need to be removed from the game this loop */
        private ArrayList removeList = new ArrayList();
        /** The entity representing the player */
        private Entity ship;
        /** The speed at which the player's ship should move (pixels/sec) */
        private double moveSpeed = 300;
        /** The time at which last fired a shot */
        private long lastFire = 0;
        /** The interval between our players shot (ms) */
        private long firingInterval = 500;
        /** The number of aliens left on the screen */
        private int alienCount;
        private int countAlienKilled = 0;
        /** The message to display which waiting for a key press */
        private String message = "";
        private String scoreStr = ""; //Edit
        /** True if we're holding up game play until a key has been pressed */
        private boolean waitingForKeyPress = true;
        /** True if the left cursor key is currently pressed */
        private boolean leftPressed = false;
        /** True if the right cursor key is currently pressed */
        private boolean rightPressed = false;
        /** True if we are firing */
        private boolean firePressed = false;
        /** True if game logic needs to be applied this loop, normally as a result of a game event */
        private boolean logicRequiredThisLoop = false;
        
        
        private int level = 0; //Edit
        private int score = 0; //Edit
        /**
         * Construct our game and set it running.
         */
        public Game() {
            String inputStr = JOptionPane.showInputDialog("Enter level to start (eg: 1):");
            level = Integer.parseInt(inputStr);
            // create a frame to contain our game
    
            JFrame container = new JFrame("Space Invaders 2013");
            
            // get hold the content of the frame and set up the resolution of the game
    
            JPanel panel = (JPanel) container.getContentPane();
            panel.setPreferredSize(new Dimension(800,600));
            panel.setLayout(null);
            
            // setup our canvas size and put it into the content of the frame
    
            setBounds(0,0,800,600);
            panel.add(this);
            
            // Tell AWT not to bother repainting our canvas since we're
            // going to do that our self in accelerated mode
    
            setIgnoreRepaint(true);
            
            // finally make the window visible 
    
            container.pack();
            container.setResizable(false);
            container.setVisible(true);
            
            // add a listener to respond to the user closing the window. If they
            // do we'd like to exit the game
    
            container.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
              });
            
            // add a key input system (defined below) to our canvas
            // so we can respond to key pressed
    
            addKeyListener(new KeyInputHandler());
            
            // request the focus so key events come to us
    
            requestFocus();
    
            // create the buffering strategy which will allow AWT
            // to manage our accelerated graphics
    
            createBufferStrategy(2);
            strategy = getBufferStrategy();
            
            // initialise the entities in our game so there's something
            // to see at startup
    
            initEntities();
        }
        
        /**
         * Start a fresh game, this should clear out any old data and
         * create a new set.
         */
        /*******************************************************
    
        *  Method name:private void startGame()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Start a fresh game, this should clear out any old data and create a new set.
        *  Visibility:new game
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        private void startGame() {
            // clear out any existing entities and intialise a new set
            
            
            entities.clear();
            initEntities();
            
            // blank out any keyboard settings we might currently have
    
            leftPressed = false;
            rightPressed = false;
            firePressed = false;
        }
        
        /**
         * Initialise the starting state of the entities (ship and aliens). Each
         * entitiy will be added to the overall list of entities in the game.
         */
        /*******************************************************
    
        *  Method name:private void initEntities()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Initialise the starting state of the entities (ship and aliens). 
        *                Each entitiy will be added to the overall list of entities in the game.
        *  Visibility:
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        private void initEntities() {
            // create the player ship and place it roughly in the center of the screen
    
            ship = new ShipEntity(this,"fullScreens/ship.gif",370,550);
            entities.add(ship);
            
            // create a block of aliens (5 rows, by 12 aliens, spaced evenly)
    
            alienCount = 0;
            for (int row=0;row<level;row++) {
                for (int x=0;x<12;x++) {
                    Entity alien = new AlienEntity(this,"fullScreens/alien.gif",100+(x*50),(50)+row*30);
                    entities.add(alien);
                    alienCount++;
                }
            }
        }
        
        /**
         * Notification from a game entity that the logic of the game
         * should be run at the next opportunity (normally as a result of some
         * game event)
         */
        /*******************************************************
    
        *  Method name: public void updateLogic() 
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification from a game entity that the logic of the game
        *                should be run at the next opportunity (normally as a result of some game event)
        *  Visibility:
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void updateLogic() {
            logicRequiredThisLoop = true;
        }
        
        /**
         * Remove an entity from the game. The entity removed will
         * no longer move or be drawn.
         * 
         * @param entity The entity that should be removed
         */
        /*******************************************************
    
        *  Method name:public void removeEntity(Entity entity)
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Remove an entity from the game
        *  Visibility:The entity removed will no longer move or be drawn.
        *  @param:entity The entity that should be removed
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void removeEntity(Entity entity) {
            removeList.add(entity);
        }
        
        /**
         * Notification that the player has died. 
         */
        /*******************************************************
    
        *  Method name:public void notifyDeath()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification that the player has died
        *  Visibility:player has died
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void notifyDeath() {
            message = "Oh no! They got you, try again?";
            waitingForKeyPress = true;
        }
        
        /**
         * Notification that the player has won since all the aliens
         * are dead.
         */
        /*******************************************************
    
        *  Method name:public void notifyWin()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification that the player has won since all the aliens are dead.
        *  Visibility:all the aliens are dead and players win
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void notifyWin() {
            score = (countAlienKilled) * 10; //Edited
            scoreStr = "Score: "+score; //Edited
            message = "Well done! You Win!";
            waitingForKeyPress = true;
        }
        
        /**
         * Notification that an alien has been killed
         */
        /*******************************************************
    
        *  Method name:public void notifyAlienKilled()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality: Notification that an alien has been killed
        *  Visibility: allien has been killed
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void notifyAlienKilled() {
            // reduce the alient count, if there are none left, the player has won!
    
            alienCount--;
            countAlienKilled++;
            
            if (alienCount == 0) {
                notifyWin();
            }
            
            // if there are still some aliens left then they all need to get faster, so
            // speed up all the existing aliens
    
            for (int i=0;i<entities.size();i++) {
                Entity entity = (Entity) entities.get(i);
                
                if (entity instanceof AlienEntity) {
                    // speed up by 2%
    
                    entity.setHorizontalMovement(entity.getHorizontalMovement() * 1.02);
                }
            }
        }
        
        /**
         * Attempt to fire a shot from the player. Its called "try"
         * since we must first check that the player can fire at this 
         * point, i.e. has he/she waited long enough between shots
         */
        /*******************************************************
    
        *  Method name:public void tryToFire()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Attempt to fire a shot from the player
        *  Visibility:to fire a shot
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void tryToFire() {
            // check that we have waiting long enough to fire
    
            if (System.currentTimeMillis() - lastFire < firingInterval) {
                return;
            }
            
            // if we waited long enough, create the shot entity, and record the time.
    
            lastFire = System.currentTimeMillis();
            ShotEntity shot = new ShotEntity(this,"fullScreens/shot.gif",ship.getLocationRow()+10,ship.getLocationColumn()-30);
            entities.add(shot);
        }
        
        /**
         * The main game loop. This loop is running during all game
         * play as is responsible for the following activities:
         * <p>
         * - Working out the speed of the game loop to update moves
         * - Moving the game entities
         * - Drawing the screen contents (entities, text)
         * - Updating game events
         * - Checking Input
         * <p>
         */
        
       /*******************************************************
    
        *  Method name:public void gameLoop()
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality: This loop is running during all game
        *                 play as is responsible for 
        *                 Working out the speed of the game loop to update moves
        *                 Drawing the screen contents (entities, text)
        *                 Updating game events
        *                 Checking Input
        *  Visibility:
        *  @param:
        *  @return:
        *  From requirement number 
        *******************************************************/
        public void gameLoop() {
    
            long lastLoopTime = System.currentTimeMillis();
            
            // keep looping round til the game ends
    
            while (gameRunning) {
                // work out how long its been since the last update, this
                // will be used to calculate how far the entities should
                // move this loop
    
                long delta = System.currentTimeMillis() - lastLoopTime;
                lastLoopTime = System.currentTimeMillis();
                
                // Get hold of a graphics context for the accelerated 
                // surface and blank it out
    
                Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                g.setColor(Color.black);
                g.fillRect(0,0,800,600);
                
                // cycle round asking each entity to move itself
    
                if (!waitingForKeyPress) {
                    for (int i=0;i<entities.size();i++) {
                        Entity entity = (Entity) entities.get(i);
                        
                        entity.move(delta);
                    }
                }
                
                // cycle round drawing all the entities we have in the game
    
                for (int i=0;i<entities.size();i++) {
                    Entity entity = (Entity) entities.get(i);
                    
                    entity.draw(g);
                }
                
                // brute force collisions, compare every entity against
                // every other entity. If any of them collide notify 
                // both entities that the collision has occured
    
                for (int p=0;p<entities.size();p++) {
                    for (int s=p+1;s<entities.size();s++) {
                        Entity rec = (Entity) entities.get(p);
                        Entity otherRec = (Entity) entities.get(s);
                        
                        if (rec.collidesWith(otherRec)) {
                            rec.collidedWith(otherRec);
                            otherRec.collidedWith(rec);
                        }
                    }
                }
                
                // remove any entity that has been marked for clear up
    
                entities.removeAll(removeList);
                removeList.clear();
    
                // if a game event has indicated that game logic should
                // be resolved, cycle round every entity requesting that
                // their personal logic should be considered.
    
                if (logicRequiredThisLoop) {
                    for (int i=0;i<entities.size();i++) {
                        Entity entity = (Entity) entities.get(i);
                        entity.doLogic();
                    }
                    
                    logicRequiredThisLoop = false;
                }
                
                // if we're waiting for an "any key" press then draw the 
                // current message 
    
                if (waitingForKeyPress) {
                    g.setColor(Color.white);
                    g.drawString("No. of Alien Killed: "+countAlienKilled,(800-g.getFontMetrics().stringWidth(String.valueOf("No. of Alien Killed: "+countAlienKilled)))/2,150);//Edited
                    g.drawString(scoreStr,(800-g.getFontMetrics().stringWidth(scoreStr))/2,200); //Edited
                    g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
                    g.drawString("Current Level: "+level,(800-g.getFontMetrics().stringWidth("Current Level: "+level))/2,300);
                    g.drawString("Press any key to go to the next level",(800-g.getFontMetrics().stringWidth("Press any key to go to the next level"))/2,350);
                }
                
                // finally, we've completed drawing so clear up the graphics
                // and flip the buffer over
    
                g.dispose();
                strategy.show();
                
                // resolve the movement of the ship. First assume the ship 
                // isn't moving. If either cursor key is pressed then
                // update the movement appropraitely
    
                ship.setHorizontalMovement(0);
                
                if ((leftPressed) && (!rightPressed)) {
                    ship.setHorizontalMovement(-moveSpeed);
                } else if ((rightPressed) && (!leftPressed)) {
                    ship.setHorizontalMovement(moveSpeed);
                }
                
                // if we're pressing fire, attempt to fire
    
                if (firePressed) {
                    tryToFire();
                }
                
                // finally pause for a bit. Note: this should run us at about
                // 100 fps but on windows this might vary each loop due to
                // a bad implementation of timer
    
                try { Thread.sleep(10); } catch (Exception e) {}
            }
        }
        
        /**
         * A class to handle keyboard input from the user. The class
         * handles both dynamic input during game play, i.e. left/right 
         * and shoot, and more static type input (i.e. press any key to
         * continue)
         * 
         * This has been implemented as an inner class more through 
         * habbit then anything else. Its perfectly normal to implement
         * this as seperate class if slight less convienient.
         * 
         * @author Kevin Glass
         */
        
    /*******************************************************
    
       *  Class name: KeyInputHandler
       *  Inheritance:
       *  Attributes: pressCount
       *  Methods: public void keyPressed(KeyEvent e)
       *           public void keyReleased(KeyEvent e)
       *           public void keyTyped(KeyEvent e)
       *  
       *  Functionality:A class to handle keyboard input from the user
       *  Visibility: press any key to continue
       *  From requirement number : 
    
    *******************************************************/
    
       private class KeyInputHandler extends KeyAdapter {
            /** The number of key presses we've had while waiting for an "any key" press */
            private int pressCount = 1;
            
            /**
             * Notification from AWT that a key has been pressed. Note that
             * a key being pressed is equal to being pushed down but *NOT*
             * released. Thats where keyTyped() comes in.
             *
             * @param e The details of the key that was pressed 
             */
            
        /*******************************************************
    
        *  Method name: public void keyPressed(KeyEvent e)
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification from AWT that a key has been pressed
        *  Visibility:a key has been pressed
        *  @param: e The details of the key that was pressed
        *  @return:
        *  From requirement number 
        *******************************************************/
            public void keyPressed(KeyEvent e) {
                // if we're waiting for an "any key" typed then we don't 
                // want to do anything with just a "press"
                if (waitingForKeyPress) {
                    return;
                }
                
                
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    leftPressed = true;
                }
                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    rightPressed = true;
                }
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    firePressed = true;
                }
            } 
            
            /**
             * Notification from AWT that a key has been released.
             *
             * @param e The details of the key that was released 
             */
            /*******************************************************
    
        *  Method name: public void keyReleased(KeyEvent e)
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification from AWT that a key has been released.
        *  Visibility:
        *  @param:e The details of the key that was released 
        *  @return:
        *  From requirement number 
        *******************************************************/
            public void keyReleased(KeyEvent e) {
                // if we're waiting for an "any key" typed then we don't 
                // want to do anything with just a "released"
                if (waitingForKeyPress) {
                    return;
                }
                
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                    leftPressed = false;
                }
                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                    rightPressed = false;
                }
                if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                    firePressed = false;
                }
            }
    
            /**
             * Notification from AWT that a key has been typed. Note that
             * typing a key means to both press and then release it.
             *
             * @param e The details of the key that was typed. 
             */
            /*******************************************************
    
        *  Method name:public void keyTyped(KeyEvent e)
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:Notification from AWT that a key has been typed.
        *  Visibility:Note that typing a key means to both press and then release it.
        *  @param: e The details of the key that was typed. 
        *  @return:
        *  From requirement number 
        *******************************************************/
            public void keyTyped(KeyEvent e) {
                // if we're waiting for a "any key" type then
                // check if we've recieved any recently. We may
                // have had a keyType() event from the user releasing
                // the shoot or move keys, hence the use of the "pressCount"
                // counter.
    
                if (waitingForKeyPress) {
                    if (pressCount == 1) {
                        // since we've now recieved our key typed
                        // event we can mark it as such and start 
                        // our new game
    
                        waitingForKeyPress = false;
                        startGame();
                        pressCount = 0;
                    } else {
                        pressCount++;
                        level++; //NextLevel //Edited
                    }
                }
                
                // if we hit escape, then quit the game
    
                if (e.getKeyChar() == 27) {
                    System.exit(0);
                }
            }
        }
        
        /**
         * The entry point into the game. We'll simply create an
         * instance of class which will start the display and game
         * loop.
         * 
         * @param argv The arguments that are passed into our game
         */
        /*******************************************************
    
        *  Method name:public static void main(String argv[])
        *  Inheritance:
        *  Attributes:
        *  Precondition:
        *  Postcondition:
        *  Functionality:The entry point into the game. create an instance of class which will start the display and game loop
        *  Visibility:
        *  @param:argv The arguments that are passed into our game
        *  @return:
        *  From requirement number 
        *******************************************************/
        public static void main(String argv[]) {
            Game g =new Game();
            // Start the main game loop, note: this method will not
            // return until the game has finished running. Hence we are
            // using the actual main thread to run the game.
            
            g.gameLoop();
            
        }
    }

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    have problem to add every levels with different timing..
    Please explain what problems you are having with setting timing for the different levels. Where will the timing be set?
    What will the the timing be used for?

    There are several classes missing preventing the code from being compiled and tested.
    If you don't understand my response, don't ignore it, ask a question.

  10. #10
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Quote Originally Posted by Norm View Post
    Please explain what problems you are having with setting timing for the different levels. Where will the timing be set?
    What will the the timing be used for?

    There are several classes missing preventing the code from being compiled and tested.
    this game has 7 classes.. do you want me to upload all classes?.what i mean with What will the timing be used for is to show that this game will be difficult if levels increase. Now this game is no time limit. we can play until the aliens crash on aircraft.

  11. #11
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    /**
     * The entity that represents the players ship
     * 
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name: ShipEntity
       *  Attributes: game
       *  Methods: public void move(long delta)
       *           public void collidedWith(Entity other)
       *  Functionality:  The entity that represents the players ship
       *  Visibility: players ship
    
    *******************************************************/
        public class ShipEntity extends Entity {
        /** The game in which the ship exists */
        private Game game;
        
        /**
         * Create a new entity to represent the players ship
         *  
         * @param game The game in which the ship is being created
         * @param ref The reference to the fullScreen to show for the ship
         * @param locationRow The initial locationRow location of the player's ship
         * @param locationColumn The initial locationColumn location of the player's ship
         */
        public ShipEntity(Game game,String ref,int locationRow,int locationColumn) {
            super(ref,locationRow,locationColumn);
            
            this.game = game;
        }
        /**
         * Request that the ship move itself based on an elapsed ammount of
         * time
         * 
         * @param delta The time that has elapsed since last move (ms)
         */
        /*******************************************************
    
        *  Method name:public void move(long delta)
        *  Functionality:Request that the ship move itself based on an elapsed ammount of time
        *  @param:delta The time that has elapsed since last move (ms)
        *  From requirement number 
        *******************************************************/
        public void move(long delta) {
            // if we're moving left and have reached the left hand side
            // of the screen, don't move
    
            if ((speedHorizontal < 0) && (locationRow < 10)) {
                return;
            }
            // if we're moving right and have reached the right hand side
            // of the screen, don't move
    
            if ((speedHorizontal > 0) && (locationRow > 750)) {
                return;
            }
            
            super.move(delta);
        }
        
        /**
         * Notification that the player's ship has collided with something
         * 
         * @param other The entity with which the ship has collided
         */
        /*******************************************************
    
        *  Method name:public void collidedWith(Entity other)
        *  Functionality:Notification that the player's ship has collided with something
        *  Visibility:ship has collided with something
        *  @param:other The entity with which the ship has collided
        *  
        *******************************************************/
        public void collidedWith(Entity other) {
            // if its an alien, notify the game that the player
            // is dead
    
            if (other instanceof AlienEntity) {
                game.notifyDeath();
            }
        }
    }

  12. #12
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
     /**
     * An entity representing a shot fired by the player's ship
     * 
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name:ShotEntity 
       *  Attributes:moveSpeed,game,used
       *  Methods: public void move(long delta) 
       *           public void collidedWith(Entity other)
       *  Functionality: An entity representing a shot fired by the player's ship  
       *  Visibility: shot fired by the player's ship
    
    *******************************************************/
    
    public class ShotEntity extends Entity {
        /** The vertical speed at which the players shot moves */
        private double moveSpeed = -300;
        /** The game in which this entity exists */
        private Game game;
        /** True if this shot has been "used", i.e. its hit something */
        private boolean used = false;
        
        /**
         * Create a new shot from the player
         * 
         * @param game The game in which the shot has been created
         * @param fullScreen The fullScreen representing this shot
         * @param locationRow The initial locationRow location of the shot
         * @param locationColumn The initial locationColumn location of the shot
         */
        public ShotEntity(Game game,String fullScreen,int locationRow,int locationColumn) {
            super(fullScreen,locationRow,locationColumn);
            
            this.game = game;
            
            speedVertical = moveSpeed;
        }
    
        /**
         * Request that this shot moved based on time elapsed
         * 
         * @param delta The time that has elapsed since last move
         */
        /*******************************************************
    
        *  Method name:public void move(long delta) 
        *  Functionality:Request that this shot moved based on time elapsed
        *  @param:delta The time that has elapsed since last move
        *******************************************************/
        public void move(long delta) {
            // proceed with normal move
    
            super.move(delta);
            
            // if we shot off the screen, remove ourselfs
    
            if (locationColumn < -100) {
                game.removeEntity(this);
            }
        }
        
        /**
         * Notification that this shot has collided with another
         * entity
         * 
         * @parma other The other entity with which we've collided
         */
        /*******************************************************
    
        *  Method name:public void collidedWith(Entity other) 
        *  Functionality: Notification that this shot has collided with another entity
        *  @param:other The other entity with which we've collided
        *******************************************************/
        public void collidedWith(Entity other) {
            // prevents double kills, if we've already hit something,
            // don't collide
    
            if (used) {
                return;
            }
            
            // if we've hit an alien, kill it!
    
            if (other instanceof AlienEntity) {
                // remove the affected entities
    
                game.removeEntity(this);
                game.removeEntity(other);
                
                // notify the game that the alien has been killed
    
                game.notifyAlienKilled();
                used = true;
            }
        }
    }

  13. #13
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    /**
     * An entity which represents one of our space invader aliens.
     * 
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name:AlienEntity
       *  Attributes: moveSpeed,game
       *  Methods:public void move(long delta)
       *          public void movement()
       *          public void collidedWith(Entity other)       
       *  Functionality:An entity which represents one of our space invader aliens
       *  Visibility: aliens invader
    
    *******************************************************/   
       public class AlienEntity extends Entity { 
           /** The speed at which the alient moves horizontally */ 
           private double moveSpeed = 75; 
           /** The game in which the entity exists */ 
           private Game game; 
           /*** Create a new alien entity * 
              * @param game The game in which this entity is being created 
              * @param ref The fullScreen which should be displayed for this alien 
              * @param locationRow The intial locationRow location of this alien 
              * @param locationColumn The intial locationColumn location of this alient */ 
              
              public AlienEntity(Game game,String ref,int locationRow,int locationColumn) { 
                  super(ref,locationRow,locationColumn); 
                  this.game = game; 
                  speedHorizontal = -moveSpeed; 
              }
    
         /**
         * Request that this alien moved based on time elapsed
         * 
         * @param delta The time that has elapsed since last move
         */
         /*******************************************************
    
        *  Method name:public void move(long delta) 
        *  Functionality:Request that this shot moved based on time elapsed
        *  @param:delta The time that has elapsed since last move
        *******************************************************/
           public void move(long delta) { 
           // if we have reached the left hand side of the screen and
           // are moving left then request a logic update
    
        if ((speedHorizontal < 0) && (locationRow < 10)) { 
            game.updateLogic(); 
        } 
        // and vice vesa, if we have reached the right hand side of
        // the screen and are moving right, request a logic update
    
        if ((speedHorizontal > 0) && (locationRow > 750)) { 
            game.updateLogic(); 
        } 
        // proceed with normal move
         super.move(delta); 
        } 
        
         /** * Update the game logic related to aliens */ 
         /*******************************************************
    
        *  Method name:public void movement()
        *  Functionality:Update the game logic related to aliens 
        *  
        *******************************************************/
         public void doLogic() { 
        // swap over horizontal movement and move down the screen a bit
    
          speedHorizontal = -speedHorizontal; 
          locationColumn += 10; 
        // if we've reached the bottom of the screen then the player dies
    
        if (locationColumn > 570) { 
            game.notifyDeath(); 
        } 
      } 
       /*** Notification that this alien has collided with another entity 
          * @param other The other entity */
          /*******************************************************
    
        *  Method name:public void collidedWith(Entity other)
        *  Functionality:Notification that this alien has collided with another entity 
        *  Visibility:alien has collided with another entity
        *  @param:other The other entity
       
        *******************************************************/
          public void collidedWith(Entity other) {
         // collisions with aliens are handled elsewhere
    
        }
    }

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    Are the level values going to be used to set a time out to end the game?

    Where are you having problems with the design of the program?

    There are too many classes with too much code to work with.

    You need to make a small, simple program that can be used for designing the timing features.
    Last edited by Norm; 12-26-2013 at 05:53 PM.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    import java.awt.Graphics;
    import java.awt.Rectangle;
    
    /**
     * An entity represents any element that appears in the game. The
     * entity is responsible for resolving collisions and movement
     * based on a set of properties defined either by subclass or externally.
     * 
     * Note that doubles are used for positions. This may seem strange
     * given that pixels locations are integers. However, using double means
     * that an entity can move a partial pixel. It doesn't of course mean that
     * they will be display half way through a pixel but allows us not lose
     * accuracy as we move.
     * 
     * @author Kevin Glass
     * 
     */
    
    /*******************************************************
    *  Class name       : Entity
    *  Inheritance      : AlienEntity,ShotEntity,ShipEntity
    *  Attributes       : locationRow,locationCloumn,fullScreen,speedHorizontal,speedVertical
    *  Methods          : public void move(long delta)
    *                     public void draw(Graphics g)
    *                     public boolean collidesWith(Entity other) 
    *                     public abstract void collidedWith(Entity other);
    *                     
    *  Functionality    :An entity represents any element that appears in the game. The entity is responsible for resolving collisions and movement 
    *                    based on a set of properties defined either by subclass or externally.
    *******************************************************/
    public abstract class Entity {
        /** The current locationRow location of this entity */ 
        protected double locationRow;
        /** The current locationColumn location of this entity */
        protected double locationColumn;
        /** The fullScreen that represents this entity */
        protected FullScreen fullScreen;
        /** The current speed of this entity horizontally (pixels/sec) */
        protected double speedHorizontal;
        /** The current speed of this entity vertically (pixels/sec) */
        protected double speedVertical;
        /** The rectangle used for this entity during collisions  resolution */
        private Rectangle rec = new Rectangle();
        /** The rectangle used for other entities during collision resolution */
        private Rectangle otherRec = new Rectangle();
        
        /**
         * Construct a entity based on a fullScreen image and a location.
         * 
         * @param ref The reference to the image to be displayed for this entity
         * @param locationRow The initial locationRow location of this entity
         * @param locationColumn The initial locationColumn location of this entity
         */
        public Entity(String ref,int locationRow,int locationColumn) {
            this.fullScreen = fullScreenStore.get().getFullScreen(ref);
            this.locationRow = locationRow;
            this.locationColumn = locationColumn;
        }
        
        /**
         * Request that this entity move itself based on a certain ammount
         * of time passing.
         * 
         * @param delta The ammount of time that has passed in milliseconds
         */
       /*******************************************************
       *  Method name: public void move(long delta)
       *  Functionality: Request that this entity move itself based on a certain ammount of time passing.
       *  @param: delta The ammount of time that has passed in milliseconds
        *******************************************************/
        public void move(long delta) {
            // update the location of the entity based on move speeds
            locationRow += (delta * speedHorizontal) / 1000;
            locationColumn += (delta * speedVertical) / 1000;
        }
        
        /**
         * Set the horizontal speed of this entity
         * 
         * @param speedHorizontal The horizontal speed of this entity (pixels/sec)
         */
        public void setHorizontalMovement(double speedHorizontal) {
            this.speedHorizontal = speedHorizontal;
        }
    
        /**
         * Set the vertical speed of this entity
         * 
         * @param speedHorizontal The vertical speed of this entity (pixels/sec)
         */
        public void setVerticalMovement(double speedVertical) {
            this.speedVertical = speedVertical;
        }
        
        /**
         * Get the horizontal speed of this entity
         * 
         * @return The horizontal speed of this entity (pixels/sec)
         */
        public double getHorizontalMovement() {
            return speedHorizontal;
        }
    
        /**
         * Get the vertical speed of this entity
         * 
         * @return The vertical speed of this entity (pixels/sec)
         */
        public double getVerticalMovement() {
            return speedVertical;
        }
        
        /**
         * Draw this entity to the graphics context provided
         * 
         * @param g The graphics context on which to draw
         */
        /*******************************************************
    
        *  Method name: public void draw(Graphics g)
        *  Functionality:Draw this entity to the graphics context provided
        *  @param: g The graphics context on which to draw
        *******************************************************/
        public void draw(Graphics g) {
            fullScreen.draw(g,(int) locationRow,(int) locationColumn);
        }
        
        /**
    	 * Do the logic associated with this entity. This method
    	 * will be called periodically based on game events
    	 */
    	public void doLogic() {
    	}
        
        
        /**
         * Get the locationRow location of this entity
         * 
         * @return The locationRow location of this entity
         */
        public int getLocationRow() {
            return (int) locationRow;
        }
    
        /**
         * Get the locationColumn location of this entity
         * 
         * @return The locationColumn location of this entity
         */
        public int getLocationColumn() {
            return (int) locationColumn;
        }
        
        /**
         * Check if this entity collised with another.
         * 
         * @param other The other entity to check collision against
         * @return True if the entities collide with each other
         */
        /*******************************************************
    
        *  Method name:public boolean collidesWith(Entity other)
        *  Functionality:Check if this entity collised with another
        *  @param:other The other entity to check collision against
        *  @return:True if the entities collide with each other
        *******************************************************/
        public boolean collidesWith(Entity other) {
            rec.setBounds((int) locationRow,(int) locationColumn,fullScreen.getWidth(),fullScreen.getHeight());
            otherRec.setBounds((int) other.locationRow,(int) other.locationColumn,other.fullScreen.getWidth(),other.fullScreen.getHeight());
    
            return rec.intersects(otherRec);
        }
        
        /**
         * Notification that this entity collided with another.
         * 
         * @param other The entity with which this entity collided.
         */
        /*******************************************************
    
        *  Method name:public abstract void collidedWith(Entity other);
        *  Functionality: Notification that this entity collided with another.
        *  Visibility:entity collided with another.
        *  @param:other The entity with which this entity collided.
        *******************************************************/
        public abstract void collidedWith(Entity other);
    }

  16. #16
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    import java.awt.GraphicsConfiguration;
    import java.awt.GraphicsEnvironment;
    import java.awt.Image;
    import java.awt.Transparency;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.URL;
    import java.util.HashMap;
    import javax.imageio.ImageIO;
    /**
     * A resource manager for fullScreens in the game. Its often quite important
     * how and where you get your game resources from. In most cases
     * it makes sense to have a central resource loader that goes away, gets
     * your resources and caches them for future use.
     * <p>
     * [singleton]
     * <p>
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name:fullScreenStore 
       *  Methods: private void fail(String message)           
       *  Functionality: A resource manager for fullScreens in the game
      
    *******************************************************/
    public class fullScreenStore {
        /** The single instance of this class */
        private static fullScreenStore single = new fullScreenStore();
        
        /**
         * Get the single instance of this class 
         * 
         * @return The single instance of this class
         */
        public static fullScreenStore get() {
            return single;
        }
        
        /** The cached fullScreen map, from reference to fullScreen instance */
        private HashMap fullScreens = new HashMap();
        
        /**
         * Retrieve a fullScreen from the store
         * 
         * @param ref The reference to the image to use for the fullScreen
         * @return A fullScreen instance containing an accelerate image of the request reference
         */
        public FullScreen getFullScreen(String ref) {
            // if we've already got the fullScreen in the cache
            // then just return the existing version
    
            if (fullScreens.get(ref) != null) {
                return (FullScreen) fullScreens.get(ref);
            }
            
            // otherwise, go away and grab the fullScreen from the resource
            // loader
    
            BufferedImage sourceImage = null;
            
            try {
                // The ClassLoader.getResource() ensures we get the fullScreen
                // from the appropriate place, this helps with deploying the game
                // with things like webstart. You could equally do a file look
                // up here.
    
                URL url = this.getClass().getClassLoader().getResource(ref);
                
                if (url == null) {
                    fail("Can't find ref: "+ref);
                }
                
                // use ImageIO to read the image in
    
                sourceImage = ImageIO.read(url);
            } 
                catch (IOException e) {
                fail("Failed to load: "+ref);
            }
            
            // create an accelerated image of the right size to store our fullScreen in
    
            GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
            Image image = gc.createCompatibleImage(sourceImage.getWidth(),sourceImage.getHeight(),Transparency.BITMASK);
            
            // draw our source image into the accelerated image
    
            image.getGraphics().drawImage(sourceImage,0,0,null);
            
            // create a fullScreen, add it the cache then return it
    
            FullScreen fullScreen = new FullScreen(image);
            fullScreens.put(ref,fullScreen);
            
            return fullScreen;
        }
        
        /**
         * Utility method to handle resource loading failure
         * 
         * @param message The message to display on failure
         */
        /*******************************************************
        *  Method name:private void fail(String message)
        *  Functionality:Utility method to handle resource loading failure
        *  @param:message The message to display on failure
        *******************************************************/
        private void fail(String message) {
            // we'n't available
            // we dump the message and exit the game
    
            System.err.println(message);
            System.exit(0);
        }
    }

  17. #17
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Java Code:
    import java.awt.Graphics;
    import java.awt.Image;
    
    /**
     * A fullScreen to be displayed on the screen. Note that a fullScreen
     * contains no state information, i.e. its just the image and 
     * not the location. This allows us to use a single fullScreen in
     * lots of different places without having to store multiple 
     * copies of the image.
     * 
     * @author Kevin Glass
     */
    /*******************************************************
    
       *  Class name:FullScreen
       *  Attributes:image
       *  Methods:public void draw(Graphics g,int locationRow,int locationColumn)         
       *  Functionality:A fullScreen to be displayed on the screen. Note that a fullScreen contains no state information, i.e. its just the image and not the location. 
       *                This allows us to use a single fullScreen in 
       *                lots of different places without having to store multiple copies of the image.
       *  Visibility:A fullScreen to be displayed on the screen
         
    *******************************************************/
    public class FullScreen {
        /** The image to be drawn for this fullScreen */
        private Image image;
        
        /**
         * Create a new fullScreen based on an image
         * 
         * @param image The image that is this fullScreen
         */
        public FullScreen(Image image) {
            this.image = image;
        }
        
        /**
         * Get the width of the drawn fullScreen
         * 
         * @return The width in pixels of this fullScreen
         */
        public int getWidth() {
            return image.getWidth(null);
        }
    
        /**
         * Get the height of the drawn fullScreen
         * 
         * @return The height in pixels of this fullScreen
         */
        public int getHeight() {
            return image.getHeight(null);
        }
        
        /**
         * Draw the fullScreen onto the graphics context provided
         * 
         * @param g The graphics context on which to draw the fullScreen
         * @param locationRow The locationRow location at which to draw the fullScreen
         * @param locationColumn The locationColumn location at which to draw the fullScreen
         */
        /*******************************************************
    
        *  Method name: public void draw(Graphics g,int locationRow,int locationColumn)
        *  Functionality:Draw the fullScreen onto the graphics context provided
        *  Visibility:image of the game 
        *  @param: g The graphics context on which to draw the fullScreen
        *  @param: locationRow The locationRow location at which to draw the fullScreen
        *  @param: locationColumn The locationColumn location at which to draw the fullScreen
      
        *******************************************************/
        public void draw(Graphics g,int locationRow,int locationColumn) {
            g.drawImage(image,locationRow,locationColumn,null);
        }
    }

  18. #18
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    See post#14
    If you don't understand my response, don't ignore it, ask a question.

  19. #19
    lya
    lya is offline Member
    Join Date
    Dec 2013
    Posts
    15
    Rep Power
    0

    Default Re: code for timing which is every levels have different degree of difficulty.

    Do you understand what I want to say?

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,454
    Rep Power
    25

    Default Re: code for timing which is every levels have different degree of difficulty.

    Is this what you want to do?
    Set timer from level's value
    begin game loop
    play game
    if timer done, exit loop
    end game loop
    If you don't understand my response, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 0
    Last Post: 12-26-2013, 03:50 PM
  2. A Timing loop
    By davidfla90 in forum New To Java
    Replies: 1
    Last Post: 11-06-2011, 12:48 AM
  3. thumbnail display timing
    By gatensbury in forum AWT / Swing
    Replies: 14
    Last Post: 07-30-2011, 12:44 AM
  4. Chat GUI timing problem
    By waysgoose in forum Networking
    Replies: 2
    Last Post: 09-08-2010, 11:28 PM
  5. Choosing a degree concentration
    By xcallmejudasx in forum Jobs Discussion
    Replies: 11
    Last Post: 08-14-2009, 11:30 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •