Brauche Hilfe ! (sich bewegender Ball)

Nevar

Grünschnabel
Hallo,

Ich habe ein Problem.
Wie bekomme ich ein Programm hin, wo sich ein Kreis in einem Fenster bewegt und an den Fensterrändern abstößt ?

Wäre super wenn mir jemand den Quelltext / Anleitung schreiben könnte.

Danke
 
Ja, Du brauchst nur Deinen Wunschzettel abzugeben und schon schreibt der Weihnachtsmann Dir das Programm. :-(

Wenn Du in Java programmieren willst, solltest Du auch bereit sein, selbst zu programmieren.
Hilfestellung bekommst Du von uns allen!
 
Hallo!


Code:
/*
 * Created on 13.05.2003
 */
package de.tutorials;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.swing.JFrame;

/**
 * @author ASW
 *
 */
public class Main extends JFrame {

    protected final static int BOUNDS_X = 300;

    protected final static int BOUNDS_Y = 200;

    private int sizeX = 320;

    private int sizeY = 240;

    private int mouseX;

    private int mouseY;

    private Point clickPos;

    private volatile boolean running = true;

    private int crossWidth = 15, crossHeight = 15;

    private BufferStrategy strategy;

    private boolean checkForHit = false;

    private Ball[] balls;

    private volatile int ballCnt = 0;

    private Thread runnerThread = new Thread() {

        {
            setPriority(Thread.MIN_PRIORITY);
        }

        public void run() {
            while (running) {
                try {

                    Graphics gScreen = strategy.getDrawGraphics();
                    gScreen.clearRect(0, 0, sizeX, sizeY);

                    try {
                        Thread.sleep(25l);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        while (checkForHit)
                            Thread.sleep(25l);
                    }

                    Ball b;
                    for (int i = 0; i < balls.length; i++) {
                        b = balls[i];
                        if (b == null)
                            continue;
                        b.move();
                        b.draw(gScreen);

                    }
                    Color c = gScreen.getColor();

                    for (int j = 0; j < balls.length; j++) {
                        b = balls[j];
                        if (b == null)
                            continue;
                        gScreen.setColor(b.color);
                        for (int i = 0; i < b.ballTail.length; i++) {
                            Point p = b.ballTail[i];
                            if (p == null)
                                break;
                            gScreen.fillOval(p.x, p.y, 3, 3);
                        }

                    }
                    gScreen.setColor(c);

                    drawCross(gScreen);

                    gScreen.dispose();

                    strategy.show();

                    if (ballCnt == 0)
                        running = false;

                    b = null;

                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }

            }

            Graphics gScreen = strategy.getDrawGraphics();

            Font font = new Font("Arial", Font.BOLD, 32);
            gScreen.setFont(font);
            gScreen.drawString("Finish", 100, 50);

            gScreen.dispose();

            strategy.show();

            font = null;
            System.out.println("Finish");
        }
    };

    public Main() {
        super("BallGame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(sizeX, sizeY);
        int w = 300;
        int h = 200;

        BufferedImage bim = new BufferedImage(1, 1,
                BufferedImage.TYPE_4BYTE_ABGR);
        setCursor(getToolkit().createCustomCursor(bim, (new Point(0, 0)),
                "HiddenM"));

        this.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent evt) {
                Point p = evt.getPoint();
                mouseX = p.x;
                mouseY = p.y;

            }
        });

        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent evt) {
                checkForHit();
            }
        });

        setVisible(true);
        createBufferStrategy(2);
        strategy = getBufferStrategy();

        ballCnt = 25;
        balls = createBalls(ballCnt, 10);
        runnerThread.start();

    }

    /**
     * @param gScreen
     */
    protected void drawCross(Graphics gScreen) {
        Color c = gScreen.getColor();
        gScreen.setColor(Color.WHITE);
        gScreen.drawOval(mouseX, mouseY, 5, 5);
        gScreen.setColor(c);
    }

    /**
     * 
     */
    protected void checkForHit() {
        // TODO Auto-generated method stub
        checkForHit = true;

        int bDX;
        int bDY;

        for (int i = 0; i < balls.length; i++) {
            Ball b = balls[i];
            if (b == null)
                continue;

            bDX = (b.x + b.diameter) - mouseX;
            bDY = (b.y + b.diameter) - mouseY;

            if (Math.abs(bDX) < b.diameter && Math.abs(bDY) < b.diameter) {
                balls[i] = null;
                ballCnt--;
            }
        }

        checkForHit = false;

        //System.out.println("checkForHit out");
    }

    /**
     * @param i
     * @return
     */
    private Ball[] createBalls(int bcount, int rad) {
        // TODO Auto-generated method stub
        Random rnd = new Random();
        Color col = null;
        int id = 0;

        Ball[] balls = new Ball[bcount];
        for (int j = 0; j < balls.length; j++) {
            switch (rnd.nextInt(5)) {
            case 0:
                col = Color.RED;
                break;
            case 1:
                col = Color.BLUE;
                break;
            case 2:
                col = Color.GREEN;
                break;
            case 3:
                col = Color.YELLOW;
                break;
            case 4:
                col = Color.MAGENTA;
                break;
            }
            balls[j] = new Ball(100 + rnd.nextInt(20), 100 + rnd.nextInt(20),
                    rnd.nextInt(10) % 2 == 0 ? -1 : 1,
                    rnd.nextInt(10) % 2 == 0 ? -1 : 1, rad, col, rnd
                            .nextInt(10) + 1, id++, this);
        }
        col = null;
        rnd = null;
        return balls;
    }

    public static void main(String[] args) {
        new Main();
    }

    protected void killBall(int id) {
        balls[id] = null;
        ballCnt--;
    }

    class Ball extends Point {

        private Main mainRef;

        private int id;

        private int moveCnt;

        private int stepWidth;

        protected int diameter;

        protected int radius;

        protected Color color;

        protected int dx;

        protected int dy;

        protected Point[] ballTail;

        protected int max_tail = 20;

        public Ball(int xPos, int yPos, int dx, int dy, int rad, Color col,
                int sw, int id, Main main) {
            super(xPos, yPos);
            this.dx = dx;
            this.dy = dy;
            this.diameter = rad;
            this.radius = rad / 2;
            this.color = col;
            this.stepWidth = sw;
            this.id = id;
            ballTail = new Point[max_tail];
            this.mainRef = main;
        }

        /**
         * @param ball
         * @return
         */
        protected boolean collision(Ball ball) {
            // TODO Auto-generated method stub
            boolean ret = false;

            if ((Math.abs(ball.x - this.x) <= radius)
                    && (Math.abs(ball.y - this.y) <= radius)) {
                ret = true;
            }

            return ret;
        }

        public void draw(Graphics g) {
            Color oldCol = g.getColor();
            g.setColor(color);
            g.fillOval(x, y, diameter, diameter);
            g.setColor(oldCol);
            oldCol = null;
        }

        protected final void reverseX() {
            dx *= -1;
        }

        protected final void reverseY() {
            dy *= -1;
        }

        public void move() {

            int loc = checkX() + checkY();

            switch (loc) {
            case 7: //oben
            case 13: // unten
                reverseY();
                break;
            case 19: // rechts
            case 17: // links
                reverseX();
                break;
            case 18: // rechts oben
            case 32: // rechts unten
            case 30: // links unten
            case 24: // links oben
            {
                reverseX();
                reverseY();
            }
                ;
                break;
            default:

            }

            x += (stepWidth * dx);
            y += (stepWidth * dy);

            moveCnt++;

            Point p = ballTail[moveCnt % ballTail.length];
            if (p == null) {
                p = new Point(x, y);
            } else {
                p.setLocation(x, y);
            }
            ballTail[moveCnt % ballTail.length] = p;

            //Ball is out of Screen
            if ((x < -20 || x > Main.BOUNDS_X + 20)
                    || (y < -50 || y > Main.BOUNDS_Y + 50)) {
                System.out.println("ohoh");
                mainRef.killBall(id);
                mainRef = null;
            }

        }

        protected final int checkX() {
            if (x - radius <= 0)
                return 17;
            if (x + radius >= Main.BOUNDS_X)
                return 19;
            return 0;
        }

        protected final int checkY() {
            if ((y - radius) <= 0)
                return 7;
            if ((y + radius) >= Main.BOUNDS_Y)
                return 13;
            return 0;
        }
    }

}

Gruß Tom
 
Sieht aus, wie'n Haufen Ameisen, Dein Ball-Spiel Tom. Bin immer wieder positiv überrascht von Dir, Du scheinst eine "Antwort-Factory" zu haben. :)

Code:
public class Tom {
 
public static Antwort toAntwort(Frage frage) {
//Tom's Code-Maschine
}
 
}

:) :) :)
 
Hallo!

Da war Tom mal wieder schneller mit dem Sourcecode als ich mit einer kurzen Antwort.
...aber nur weil ich sowas noch bei mir herumfliegen hatte:
/*
* Created on 13.05.2003
*/

;-)

Bin immer wieder positiv überrascht von Dir, Du scheinst eine "Antwort-Factory" zu haben.

Danke für's Kompliment... ich übe mich immer gern im Kompetenz ausstrahlen, bzw. so zu tun als ob ^^

Gruß Tom
 
Ich bin auch immer wieder beeidruckt, wie schnell Thomas Beispiele aus dem Ärmel zaubert. Trotzdem denke ich, dass manchmal zumindest, eventuell nur ein paar Sätze angebrachter wären, als gleich das ganze Problem für jemanden zu lösen ....

Ok ich gebs zu .. Ich bin nur neidisch ! :D ..
 
Ich freue mich über ein paar Sätze prinzipiell mehr als über ne Ladung Source Code für ein etwas komplexeres Problem. Wenn es um die Verwendung einer bestimmten Klasse geht, ist Source Code optimal, aber sobald es ein paar Klassen mehr sind, wirds für den Einstieg ziemlich heftig.
Das mal als Meinung eines Gelegenheitsprogrammierers, der nach nem Jahr Pause mal wieder was coded...
 
Zurück