Java catch the ball

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

  • I have no idea how to make the balls appear at a random width and make it stay at that width (because the random value is constantly changing).
  • How can I make an operator that checks if the catcher has 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;
    }
}

      

+3


source to share


1 answer


First question: "I don't know how to make the ball appear at a random width."

I am assuming you want to give the ball (= class instance comet

) a random x position (= field plaats

)? You can make the following changes (which no longer require the field randomNum

, it can 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;
}

      



The second question is, "And how do I make an expression that checks if the ball is cached."

To determine if the ball has hit, you can compare xmuis

with plaats

when the y coordinate of the ball (field h

?) Is equal to the top of the tube (about 730).

+1


source







All Articles