1

Using this code I would like to add a button to the page that displays when the gamestate is either Dead or Win. This button will let the user either start over or go on to the next level. My action listener is not yet fully coded because I can't even get the button to be visible on the page. I have tried coding in a button using

setLayout(new FlowLayout());
this.add(sOver);
sOver = new Button("Start Over");
sOver.addActionListener(this);

But that results in a an error when the game changes state.

 package androidGame;

import java.applet.Applet;
import java.awt.event.*;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.net.*;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;




import androidGame.framework.Animation;

import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URL;

public class StartingClass extends Applet implements Runnable, KeyListener, ActionListener {

    enum GameState {
        Running, Dead, Win
    }

    GameState state = GameState.Running;

    private static Robot robot;
    public static Heliboy hb, hb2, hb3, hb4, hb5, hb6, hb7, hb8, hb9, hb10, hb11, hb12, hb13, hb14, hb15, hb16;
    public static int score = 0;
    public static int rHealth = 120;
    private Font font = new Font(null, Font.BOLD, 30);

    private Image image, currentSprite, character, character2, character3,
            characterDown, characterJumped, background, heliboy, heliboy2,
            heliboy3, heliboy4, heliboy5;

    public static Image tilegrassTop, tilegrassBot, tilegrassLeft,
            tilegrassRight, tiledirt, tilefire, tiledoor;

    private Graphics second;
    private URL base;
    private static Background bg1, bg2;
    private Animation anim, hanim;
    int level = 1;
    AudioClip clip;
    Button next, sOver;

    private ArrayList<Tile> tilearray = new ArrayList<Tile>();

    @Override

    public void init() {

        setSize(800, 480);
        setBackground(Color.BLACK);
        setFocusable(true);
        addKeyListener(this);
        Frame frame = (Frame) this.getParent().getParent();
        frame.setTitle("Robot Mania");
        try {
            base = getDocumentBase();
        } catch (Exception e) {
            // TODO: handle exception
        }

        // Image Setups
        character = getImage(base, "data/character.png");
        character2 = getImage(base, "data/character2.png");
        character3 = getImage(base, "data/character3.png");

        characterDown = getImage(base, "data/down.png");
        characterJumped = getImage(base, "data/jumped.png");

        heliboy = getImage(base, "data/heliboy.png");
        heliboy2 = getImage(base, "data/heliboy2.png");
        heliboy3 = getImage(base, "data/heliboy3.png");
        heliboy4 = getImage(base, "data/heliboy4.png");
        heliboy5 = getImage(base, "data/heliboy5.png");

        background = getImage(base, "data/spacebackground.png");

        tiledirt = getImage(base, "data/tiledirt.png");
        tilegrassTop = getImage(base, "data/tilegrasstop.png");
        tilegrassBot = getImage(base, "data/tilegrassbot.png");
        tilegrassLeft = getImage(base, "data/tilegrassleft.png");
        tilegrassRight = getImage(base, "data/tilegrassright.png");
        tilefire = getImage(base, "data/tilefire.png");
        tiledoor = getImage(base, "data/tiledoor.png");

        anim = new Animation();
        anim.addFrame(character, 1250);
        anim.addFrame(character2, 50);
        anim.addFrame(character3, 50);
        anim.addFrame(character2, 50);

        hanim = new Animation();
        hanim.addFrame(heliboy, 100);
        hanim.addFrame(heliboy2, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy5, 100);
        hanim.addFrame(heliboy4, 100);
        hanim.addFrame(heliboy3, 100);
        hanim.addFrame(heliboy2, 100);




        currentSprite = anim.getImage();
    }

    @Override
    public void start() {
        //Sound.MAIN.loop();
        bg1 = new Background(0, 0);
        bg2 = new Background(2160, 0);
        robot = new Robot();
        // Initialize Tiles
        try {
            loadMap("data/map"+ level +".txt");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Random random = new Random();
        int randomInt = random.nextInt(500);

        hb = new Heliboy(700, 360);
        hb2 = new Heliboy(900 + randomInt, 360);
        hb3 = new Heliboy(2300 + randomInt, 360);
        hb4 = new Heliboy(2900 + randomInt, 360);
        hb5 = new Heliboy(3400 + randomInt, 360);
        hb6 = new Heliboy(3900 + randomInt, 360);
        hb7 = new Heliboy(4300 + randomInt, 360);
        hb8 = new Heliboy(4700 + randomInt, 360);
        hb9 = new Heliboy(5000 + randomInt, 360);
        hb10 = new Heliboy(5300 + randomInt, 360);
        hb11 = new Heliboy(5700 + randomInt, 360);
        hb12 = new Heliboy(6000 + randomInt, 360);
        hb13 = new Heliboy(6300 + randomInt, 360);
        hb14 = new Heliboy(6700 + randomInt, 360);
        hb15 = new Heliboy(7000 + randomInt, 360);
        hb16 = new Heliboy(7200 + randomInt, 360);



        Thread thread = new Thread(this);
        thread.start();
    }



    private void loadMap(String filename) throws IOException {
        ArrayList lines = new ArrayList();
        int width = 0;
        int height = 0;

        BufferedReader reader = new BufferedReader(new FileReader(filename));
        while (true) {
            String line = reader.readLine();
            // no more lines to read
            if (line == null) {
                reader.close();
                break;
            }

            if (!line.startsWith("!")) {
                lines.add(line);
                width = Math.max(width, line.length());

            }
        }
        height = lines.size();

        for (int j = 0; j < 12; j++) {
            String line = (String) lines.get(j);
            for (int i = 0; i < width; i++) {

                if (i < line.length()) {
                    char ch = line.charAt(i);
                    Tile t = new Tile(i, j, Character.getNumericValue(ch));
                    tilearray.add(t);
                }

            }
        }

    }



    @Override
    public void run() {
        if (state == GameState.Running) {


            while (true) {  

                robot.update();
                if (robot.isJumped()) {
                    currentSprite = characterJumped;
                } else if (robot.isJumped() == false
                        && robot.isDucked() == false) {

                    currentSprite = anim.getImage();
                }

                ArrayList projectiles = robot.getProjectiles();
                for (int i = 0; i < projectiles.size(); i++) {
                    Projectile p = (Projectile) projectiles.get(i);
                    if (p.isVisible() == true) {
                        p.update();

                    } else {
                        projectiles.remove(i);
                    }
                }

                updateTiles();
                hb.update();
                hb2.update();
                hb3.update();
                hb4.update();
                hb5.update();
                hb6.update();
                hb7.update();
                hb8.update();
                hb9.update();
                hb10.update();
                hb11.update();
                hb12.update();
                hb13.update();
                hb14.update();
                hb15.update();
                hb16.update();
                bg1.update();
                bg2.update();
                animate();
                repaint();
                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (rHealth == 0) {
                    state = GameState.Dead;                 
                    Sound.MAIN.stop();
                    //Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);                 
                    revalidate();
                    repaint();
                }
                if (robot.getCenterY() > 500) {
                    state = GameState.Dead;
                    Sound.MAIN.stop();
                    //Sound.DIE.play();

                    sOver = new Button("Start Over");
                    this.add(sOver);
                    sOver.addActionListener(this);
                    sOver.setVisible(true);                 
                    revalidate();
                    repaint();

                }

                if (score == 5){
                    state = GameState.Win;
                    Sound.MAIN.stop();
                    //Sound.WIN.play();

                    next = new Button("Next Level");
                    this.add(next);
                    next.addActionListener(this);
                    next.setVisible(true);  
                    revalidate();
                    repaint();

                }
            }
        }
    }

    public void animate() {
        anim.update(10);
        hanim.update(50);
    }

    @Override
    public void update(Graphics g) {
        if (image == null) {
            image = createImage(this.getWidth(), this.getHeight());
            second = image.getGraphics();
        }

        second.setColor(getBackground());
        second.fillRect(0, 0, getWidth(), getHeight());
        second.setColor(getForeground());
        paint(second);

        g.drawImage(image, 0, 0, this);

    }



    @Override
    public void paint(Graphics g) {

        if (state == GameState.Running) {

            g.drawImage(background, bg1.getBgX(), bg1.getBgY(), this);
            g.drawImage(background, bg2.getBgX(), bg2.getBgY(), this);
            paintTiles(g);

            ArrayList projectiles = robot.getProjectiles();
            for (int i = 0; i < projectiles.size(); i++) {
                Projectile p = (Projectile) projectiles.get(i);
                g.setColor(Color.BLUE);
                g.fillRect(p.getX(), p.getY(), 10, 5);
            }

            g.drawImage(currentSprite, robot.getCenterX() - 61,
                    robot.getCenterY() - 63, this);
            g.drawImage(hanim.getImage(), hb.getCenterX() - 48,
                    hb.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb2.getCenterX() - 48,
                    hb2.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb3.getCenterX() - 48,
                    hb3.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb4.getCenterX() - 48,
                    hb4.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb5.getCenterX() - 48,
                    hb5.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb6.getCenterX() - 48,
                    hb6.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb7.getCenterX() - 48,
                    hb7.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb8.getCenterX() - 48,
                    hb8.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb9.getCenterX() - 48,
                    hb9.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb10.getCenterX() - 48,
                    hb10.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb11.getCenterX() - 48,
                    hb11.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb12.getCenterX() - 48,
                    hb12.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb13.getCenterX() - 48,
                    hb13.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb14.getCenterX() - 48,
                    hb14.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb15.getCenterX() - 48,
                    hb15.getCenterY() - 48, this);
            g.drawImage(hanim.getImage(), hb16.getCenterX() - 48,
                    hb16.getCenterY() - 48, this);

            g.setFont(font);
            g.setColor(Color.WHITE);
            g.drawString("Health: " + Integer.toString(rHealth), 5, 30);
            g.drawString("Score: " + Integer.toString(score), 650, 30);

        } else if (state == GameState.Dead) {

            //setLayout(new FlowLayout());


            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You're Dead!", 300, 200);
            g.drawString("Score: " + score, 300, 250);

        }
        else if (state == GameState.Win) {
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 800, 480);
            g.setColor(Color.WHITE);
            g.drawString("You Beat this level!", 300, 200);
            g.drawString("Score: " + score, 300, 250);
            level++;

        }
    }

    private void updateTiles() {

        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            t.update();
        }

    }

    private void paintTiles(Graphics g) {
        for (int i = 0; i < tilearray.size(); i++) {
            Tile t = (Tile) tilearray.get(i);
            g.drawImage(t.getTileImage(), t.getTileX(), t.getTileY(), this);
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {

        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = characterDown;
            if (robot.isJumped() == false) {
                robot.setDucked(true);
                robot.setSpeedX(0);
            }
            break;

        case KeyEvent.VK_LEFT:
            robot.moveLeft();
            robot.setMovingLeft(true);
            break;

        case KeyEvent.VK_RIGHT:
            robot.moveRight();
            robot.setMovingRight(true);
            break;

        case KeyEvent.VK_SPACE:
            robot.jump();
            break;

        case KeyEvent.VK_CONTROL:
            if (robot.isDucked() == false && robot.isJumped() == false
                    && robot.isReadyToFire()) {
                robot.shoot();  
                robot.setReadyToFire(false);

            }
            break;

        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        switch (e.getKeyCode()) {
        case KeyEvent.VK_UP:
            break;

        case KeyEvent.VK_DOWN:
            currentSprite = anim.getImage();
            robot.setDucked(false);
            break;

        case KeyEvent.VK_LEFT:
            robot.stopLeft();
            break;

        case KeyEvent.VK_RIGHT:
            robot.stopRight();
            break;

        case KeyEvent.VK_SPACE:
            break;

        case KeyEvent.VK_CONTROL:
            robot.setReadyToFire(true);
            Sound.GUN.play();
            break;

        }

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }


    public static Background getBg1() {
        return bg1;
    }

    public static Background getBg2() {
        return bg2;
    }

    public static Robot getRobot() {
        return robot;
    }

    @Override
    public void actionPerformed(ActionEvent evt) {
        if (evt.getSource() == next)
            level ++;

        {


        }
        if (evt.getSource() == sOver)

            level = 1;      

        {

        }
    }


}

The error message that I was getting is:

Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at androidGame.StartingClass.paint(StartingClass.java:372)
    at androidGame.StartingClass.update(StartingClass.java:305)
    at sun.awt.RepaintArea.updateComponent(Unknown Source)
    at sun.awt.RepaintArea.paint(Unknown Source)
    at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$300(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
Inessaria
  • 79
  • 1
  • 2
  • 10
  • 2
    Edit your post to include the specific error message you're seeing. Saying "there's an error, help me" is like me asking you "I saw a bird today, can you tell me what it was?" without showing a picture. – CubeJockey May 04 '15 at 19:15
  • Use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson May 05 '15 at 05:00

1 Answers1

1
this.add(sOver);
sOver = new Button("Start Over");

I guess the error is here. You gotta initialize sOver before adding it to the applet. So put it like this :

sOver = new Button("Start Over");
this.add(sOver);

Let's see whether it works or not.

  • That did eliminate the error, so a step in the right direction. However the "start over" button is still not visible anywhere. I moved the sOver = new Button("Start Over"); this.add(sOver); sOver.addActionListener(this); code down below the g.drawString("Score: " + score, 300, 250); line, thinking maybe it was being painted over, but it is still not visible. – Inessaria May 04 '15 at 19:31
  • well. You can try to add the line sOver.setVisible(true); below addActionListener(this); – felix.infinite May 04 '15 at 19:37
  • No change. I have the "You're dead" string, as well as the final score, but no button anywhere. – Inessaria May 04 '15 at 19:38
  • Normally, if you put your button code in the applet's init() method. It would be automatically added. But in your case, you are adding a button at runtime, then you should have a call to revalidate() and repaint() method after adding the button to the applet. revalidate() will update the component to the component hierarchy and repaint() will repaint the whole frame. – felix.infinite May 04 '15 at 19:49
  • I added revalidate(); and repaint(); after the sOver.setVisible(true); line. It DOES result in a start over button. The only problem is that it fills the entire screen with buttons and I only need just one. – Inessaria May 04 '15 at 19:53
  • I guess it is because you put your button in the paint method which is called multiple times, once for each frame. Try to make it called once. My suggestion is to (only) add the button where you set your game state to DEAD. – felix.infinite May 04 '15 at 20:02
  • 1
    You are fantastic and I really appreciate your help. – Inessaria May 04 '15 at 20:10
  • So, if my character dies by being killed by a baddie, the button prints correctly. If he dies by falling into a pit or if he wins, the button prints out over and over. Additionally, the "die " music plays fine if you die by enemy, but gliches on death by falling and the win music glitches. Considering they are happening on the same place, I am assuming they are related. I have edited the code I have above to reflect it's current state – Inessaria May 04 '15 at 22:49
  • So i don't quite get your idea. But it seems you had a bug in your run() method which updates the game data each frame. The if statement : if( state =GameState.Running ) is supposed to be inside while(true) to make sure that it is checked once each frame. And the logic inside win and die by falling won' be called many times just because the game state was changed at that time. Then add an else block after that 'if' i said to call repaint() which paints the background when the player is dead/win. – felix.infinite May 05 '15 at 11:49
  • More on the button logic: when the button is pressed try to set the game state back to Running. Initialize the game data and remove the button by making a call to this.remove(sOver or next); revalidate(). – felix.infinite May 05 '15 at 11:53