Java attraper le jeu de balle


J'ai des problèmes avec mon projet Java pour l'école. Le plan était de faire un jeu simple où vous devez attraper la balle et si vous attrapez la balle, vous obtenez des points. Pour le moment j'ai 2 problèmes:

  • Je n'ai aucune idée de la façon dont je fais apparaître les boules à une largeur aléatoire et les fais rester à cette largeur (car la valeur aléatoire change constamment ).
  • Comment puis-je faire une déclaration qui vérifie si le receveur a attrapé la balle?

C'est mon 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;
    }
}
Author: Joshua Offermans, 2015-06-08

1 answers

Première question: "Je n'ai aucune idée de la façon dont je fais apparaître la balle à une largeur aléatoire."

Je suppose que vous voulez donner à la balle (= une instance de la classe comet) une position x aléatoire (=le champ plaats)? Vous pouvez apporter les modifications suivantes (ce qui rend le champ randomNum plus requis, cela pourrait maintenant être une variable locale):

    //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;
}

Deuxième question: "Et comment peut-on faire une déclaration qui vérifie si catcher a mis en cache la balle."

Pour déterminer si la balle est captée, vous pouvez comparez xmuis à plaats lorsque la coordonnée y de la balle (la h champ?) est égale au sommet du tuyau (environ 730).

 1
Author: Freek de Bruijn, 2015-06-08 21:33:41