1

I am programming a game for a school project and when I run the code, it works sometimes and then ill run it again and the paddle or ball won't move and the print statements in my keylistener dont show up.

Now I am running two timers, one for the animation and one for a countdown, could this be an issue? It seems like multiple threads are running or when I close the jframe and then rerun the program is picking up where it left off?

public class LobPong extends JPanel implements KeyListener {
    public static double xCoordinate;
    public static double yCoordinate;
    public static Timer timer;
    static int xPaddleLeft;
    private static int yPaddle = 800;
    private static int score = 0;
    private static int level = 1;
    public static JLabel scoreLabel = new JLabel(" Score: 0 "); 
    public static JLabel timeLabel = new JLabel(" ");
    public static JLabel levelLabel = new JLabel(" Level: ");
    private static int life = 3;
    private static int levelTime = 30000;
    public static int dx, dy;
    private static double times = 0;

    public static void main(String[] args) {
        JFrame LobPongApp = new JFrame();
        LobPong canvas = new LobPong();
        canvas.setBackground(Color.BLUE);
        LobPongApp.add(canvas);
        LobPongApp.setSize(800, 900);
        LobPongApp.setTitle("Lob Pong");
        LobPongApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        LobPongApp.setVisible(true);
        canvas.setFocusable(true);
        LobPongApp.addKeyListener(canvas);
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GREEN);
        g.fillOval((int) xCoordinate, (int) yCoordinate, 50, 50);

        g.fillRect(xPaddleLeft, yPaddle, 100, 10);
        drawLife(g, getLife()); 
    }

    public LobPong() {
        timer = new Timer(1, new timerCallBack());
        timer.start();
        setLayout(new FlowLayout());
        scoreLabel.setOpaque(true);
        timeLabel.setOpaque(true);
        levelLabel.setOpaque(true);
        scoreLabel.setBackground(Color.black);
        timeLabel.setBackground(Color.black);
        levelLabel.setBackground(Color.black);
        scoreLabel.setForeground(Color.WHITE);
        timeLabel.setForeground(Color.WHITE);
        levelLabel.setForeground(Color.WHITE);
        levelLabel.setText("Level: " + 1);
        add(scoreLabel);
        add(timeLabel);
        add(levelLabel);
        xPaddleLeft = 375; //debug
        xCoordinate = 0;
        yCoordinate = 0;
        setTime(levelTime); //sets current level time (increases by 10 seconds every 2 levels)
    }

    public static void nextLevel(Graphics g, int levels) {
        level += 1;
        g.drawString("NEXT LEVEL!", 400, 400);
        timer.stop();
        //TODO call run() ?
    }

    public static void updateScore(int scoreAdd) {
        score += scoreAdd;
        scoreLabel.setText("Score: " + score);
    }

    public static int getScore() {
        return score;
    }

    public static void updateLife(int x) {
        life += x;
    }

    public static int getLife() {
        return life;
    }

    public static void drawLife(Graphics g, int x) {
        g.setColor(Color.RED);
        for(int i = 0; i < (x * 10); i += 10) { //for loop to offset lives and draw enough balls per lives
            g.fillOval(30 + i, 10, 10, 10);
        }

    }

    public static void extraLife(boolean x) {
        if (x == true) {
            updateLife(1);
        }
    }

    Timer timerDisplay = new Timer(1000, new TimerListener());
    private static int totalTime;

    public static void setTime(int time) {
         totalTime = time;
    }
    public static int getTime() {
        return totalTime;
    }
    protected class TimerListener implements ActionListener { //handles countdown timer

        @Override
        public void actionPerformed(ActionEvent arg0) {
            setTime(getTime() - 1000);
            LobPong.timeLabel.setText("Time Remaining: " + getTime()/1000 + " ");
            if(getTime() <= 0) {
                timerDisplay.stop();
                timer.stop();
            }
        }
    }


    public void keyPressed(KeyEvent arg0) {
        int key = arg0.getKeyCode();
        System.out.println("testing");
        if(key == 37) {
            if (xPaddleLeft > 0) {
                xPaddleLeft -= 50;
                System.out.println("TEST"); //debug
            }
        }
        if(key == 39) {
            if (xPaddleLeft < (getWidth() - 50)) {
                xPaddleLeft += 50;
            }
        }
        if(key == KeyEvent.VK_ENTER) {
            dx = 2;
            timer.start();
            timerDisplay.start();
            System.out.println("start"); //debug
        }
        repaint();

    }
    boolean horizontal = true; //handles horizontal movement
    boolean vertical = true; //handles vertical
    double upwards;

    public class timerCallBack implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            times += .01;

            if (horizontal == true) { //check
                xCoordinate += dx;

            }
            if(xCoordinate <= 0) { //check
                horizontal = true;

            }
            if(xCoordinate >= getWidth()) { //check
                horizontal = false;

            }
            if(horizontal == false) { //check
                xCoordinate -= dx;

            }

            if(vertical == true) { //check
                dy = (int) times;
                yCoordinate += dy;

            }
            if (vertical == false) { //check
                dy = (int) (upwards - times);
                yCoordinate -= dy;

            }
            if(dy == 0) { //check
                vertical = true;
                times = 0;

            }

            if(yCoordinate == getHeight()) { //check
                updateLife(-1);
                if (getLife() == 0) {
                    timer.stop();
                    timerDisplay.stop();

                    //TODO you lose and print high score
                }
                extraLife(false); 
                xCoordinate = 0;
                yCoordinate = 0;
                dy = 0;
                dx = 0;
                vertical = true;

            }
            if(xCoordinate <= (xPaddleLeft + 100) && xCoordinate >= xPaddleLeft && (yCoordinate + 50) == yPaddle) {
                upwards = times;
                times = 0;
                vertical = false;
                updateScore(1);
                repaint();

                //TODO plus one point, paddle bounce physics, direction
            }
            repaint();


        }
    }

    @Override
    public void keyReleased(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

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

    }
}
5
  • Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently. Dec 6, 2015 at 2:41
  • 1
    I don't think the use of multiple times/threads is you issue, but the over use of static isn't going to help, but you main problem is the use KeyListener, which is well known for it's fickle focus requirements, instead, you should be using the key bindings API, see How to Use Key Bindings for more details. Having said that, if you can reduce your logic down to a singe Timer you get better results Dec 6, 2015 at 2:50
  • I am now using a single timer that seems to be working and am looking up keybindings as the single timer fixed my display, but not the movement of the paddle Dec 6, 2015 at 2:52
  • I general, when I can't figure out the problem with the current code, I start over. Typically, if you start from the ground up, making one improvement at a time, you'll know exactly when the code stops working. For the first cut, just get the paddle and the ball drawn. Then add a KeyListener (or look up the key bindings mentioned by @MadProgrammer) and verify that they are receiving your input. Then, ensure you are overriding the correct paint method. Look up the docs on paint, repaint, update, etc. Run the code after each modification and it will make all the difference.
    – Mike
    Dec 6, 2015 at 3:21
  • 1
    Actually i switched to key bindings and it worked (cue "i told you"). They are incredibly more efficient and my dual timer was totally messing up my whole logic. Thanks for the help! Dec 6, 2015 at 6:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.