Java catch the ball Game

1.8k views Asked by At

I am having trouble with my Java project for school. The plan was to make a simple game where you need to catch the ball and if you catch the ball you will get points. At the moment I have 2 problems:

  • I have no idea how I make the balls appear at a random width and make it stay at that width (cause random value is constantly changing ).
  • How can I make a statement that checks if the catcher caught the ball?

This is my current code:

import instruct.*;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.Timer;

public class opdracht extends WindowPanel implements MouseMotionListener {
    List<comet> comets;
    Image afb1;
    Image afb2;
    Image comet;
    int xmuis;
    int score;
    int random;
    int h;
    int plaats;
    static int randomNum;
    private static final int D_W = 700;
    private static final int X_INC = 10;

    public opdracht() throws IOException {
        score = 0;
        h = -100;
        afb1 = ImageIO.read(new File("afb/space.jpg"));
        afb2 = ImageIO.read(new File("afb/pipe.png"));
        BufferedImage cometbuf = ImageIO.read(new File("afb/comet.png"));
        File output = new File("comet.png");
        ImageIO.write(cometbuf, "png", output);
        comet = ImageIO.read(new File("comet.png"));
        addMouseMotionListener(this);
        try {
            drawcomet();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        plaats = randomNum;
        comets = new LinkedList<>();

        Timer timer = new Timer(40, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Iterator<comet> it = comets.iterator();
                while (it.hasNext()) {
                    comet ball = it.next();
                    if (ball.h > D_W) {
                        it.remove();
                        System.out.println(comets.size());
                    } else {
                        ball.h += X_INC;
                        repaint();
                    }
                }
            }
        });
        timer.start();
    }

    public void paintComponent(Graphics g) {
        g.drawImage(afb1, 0, 0, 1200, 800, this);
        g.setColor(Color.yellow);
        g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
        g.drawString("score = " + score, 1020, 30);
        for (comet ball : comets) {
            ball.drawcomet(g);
        }
        g.drawImage(afb2, xmuis, 730, 70, 75, this);
    }

    public static void randInt(int min, int max) {
        // NOTE: Usually this should be a field rather than a method
        // variable so that it is not re-seeded every call.
        Random rand = new Random();

        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        randomNum = rand.nextInt((max - min) + 1) + min;

        System.out.print(randomNum);
    }

    public void drawcomet() throws InterruptedException {
        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                comets.add(new comet(comet));
            }
        }, 0, 2, TimeUnit.SECONDS);
    }

    public class comet {
        protected int h;
        Image comet;

        public comet(Image image) {
            comet = image;
        }

        public void drawcomet(Graphics g) {
            g.drawImage(comet, plaats, h, 75, 50, null);
        }
    }

    public void mouseMoved(MouseEvent e) {
        xmuis = e.getX();
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
        // do something
    }

    public static void main(String[] a) throws IOException {
        new opdracht().createGUI();
    }
}

package instruct;

import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class WindowPanel extends JPanel {
    JFrame frame;

    public WindowPanel() {
        this.setPreferredSize(new Dimension(1200, 800));
        this.setFocusable(true);
        this.requestFocusInWindow();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        // System.out.println( "class: "+ getClass().getName() );
        frame.setTitle("Space Game");
    }

    protected void createAndShowGUI() {
        frame = new JFrame();
        frame.setSize(1200, 800);
        frame.setLocation(300, 100);
        frame.setResizable(false);
        frame.add(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

        // Create a new blank cursor.
        Cursor blankCursor =
                        Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0),
                                        "blank cursor");

        // Set the blank cursor to the JFrame.
        frame.getContentPane().setCursor(blankCursor);
    }

    public void createGUI() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    public JFrame getFrame() {
        return frame;
    }
}
1

There are 1 answers

3
Freek de Bruijn On BEST ANSWER

First question: "I have no idea how i make the ball's appear at a random width."

I assume you want to give the ball (= an instance of the comet class) a random x position (= the plaats field)? You could make the following changes (which make the randomNum field no longer required, this could now be a local variable):

    //plaats = randomNum;
    plaats = randInt(0, 1200);

    // more code...

//public static void randInt(int min, int max) {
public static int randInt(int min, int max) {

    // more code...

    return randomNum;
}

Second question: "And how can make a statement that checks if catcher cached ball."

To determine whether the ball is catched, you could compare xmuis to plaats when the y coordinate of the ball (the h field?) is equal to the top of the pipe (around 730).