Ink Ball

Status
Nicht offen für weitere Antworten.

aggro600

Mitglied
Hey Leute ich suche das spiel ink ball was man von vista kennt in java als quelcode.
ich brauche es für ein schulprojekt
ich habe bis jetzt nur ein ball der die richtung ändert wenn er gegen den rand kommt.

es wäre echt wichtig das ich so ein programm auf die beine bekomm
hat jemand soeins wo ich mir was abgucken kann mit ner erklrung oder so?

InkBall by jack86 Alpha 1
 

0x7F800000

Top Contributor
Hey Leute ich suche das spiel ink ball was man von vista kennt in java als quelcode.
ich brauche es für ein schulprojekt
ich habe bis jetzt nur ein ball der die richtung ändert wenn er gegen den rand kommt.

es wäre echt wichtig das ich so ein programm auf die beine bekomm
hat jemand soeins wo ich mir was abgucken kann mit ner erklrung oder so?

InkBall by jack86 Alpha 1

Hier hat vor kurzem einer Pinball programmieren wollen, da hat er auch kollision von einem runden ball mit irgendwelchen schrägen polygonen gebraucht. ich habe dazu ein kurzes Demo gebastelt, der (hoffentlich) gesamte code ist hier zu finden:
http://www.java-forum.org/511660-post16.html

Dieses Ink-dingens ist ja nochmal dasselbe in grün, nur dass man die polygone während der ausführun mit der maus reinzeichnen kann.
Das applet auf das du verlinkt hast arbeitet aus irgendeinem grund mit quadraten... Naja... Wäre halb so schlimm, wenn es nicht derart massive probleme mit den threads hätte.

Viel erläutert oder kommentiert habe ich an meinem code nicht, aber da ist im wesentlichen nichts drin, was über 10. Klasse physik oder 11. Klasse Mathe hinausgehen würde...

Wenn von deiner Seite etwas mehr eigeninitiative zu sehen ist, könnte ich evtl ja bei gelegenheit noch den einen oder den anderen Tipp rüberschmeißen...

Dem anderen Typen hat's jedenfalls anscheinend geholfen (siehe Originalthread). Villeicht hilft's dir ja auch ein wenig... :bahnhof:
 

aggro600

Mitglied
jo danke erstmal ich guck mir das morgen mal alles an
hab jetzt schon son programm wo der ball an den wänden abprallt nur das mir dem krummen linien zeichen find ich noch nicht naja morgen ^^
 

aggro600

Mitglied
Hey ich habe keine ahnung wie ich ne linie zeichnen kann.
weiß auch nicht genau wonach ich suchen muss
kann mir jmd helfen? ist es besser ne gerade line zu nehmen für ink ball oder ne kurvige?
prauche hilfe bei meinem prjekt sonst schaff ich das nicht -.-
 

aggro600

Mitglied
das mit dem linien hab ich jetzt nur kp wie ich das in mein programm einfügen kann

BBDEMO.java:

Code:
// File: animation/bb/BBDemo.java
// Description: Illustrates animation with a ball bouncing in a box
//              Possible extensions: faster/slower button,
// Author: Fred Swartz
// Date:   February 2005 ...

import javax.swing.*;

/////////////////////////////////////////////////////////////// BBDemo
public class BBDemo extends JApplet {
    
    //============================================== applet constructor
    public BBDemo() {
        add(new BBPanel());
    }
    
    //============================================================ main
    public static void main(String[] args) {
        JFrame win = new JFrame("Ink Ball");
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        win.setContentPane(new BBPanel());
        
        win.pack();
        win.setVisible(true); 
    }
}//endclass BBDemo


BBPanel:

Code:
// File:  animation/bb/BBPanel.java
// Description: Panel to layout buttons and graphics area.
// Author: Fred Swartz
// Date:   February 2005

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/////////////////////////////////////////////////////////////////// BBPanel
class BBPanel extends JPanel {
    BallInBox m_bb;   // The bouncing ball panel
    
    //========================================================== constructor
    /** Creates a panel with the controls and bouncing ball display. */
    BBPanel() {
        //... Create components
        m_bb = new BallInBox();        
        JButton startButton = new JButton("Start");        
        JButton stopButton  = new JButton("Stop");
        
        //... Add Listeners
        startButton.addActionListener(new StartAction());
        stopButton.addActionListener(new StopAction());
        
        //... Layout inner panel with two buttons horizontally
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(startButton);
        buttonPanel.add(stopButton);
        
        //... Layout outer panel with button panel above bouncing ball
        this.setLayout(new BorderLayout());
        this.add(buttonPanel, BorderLayout.NORTH);
        this.add(m_bb       , BorderLayout.CENTER);
    }//end constructor
    
    
    ////////////////////////////////////// inner listener class StartAction
    class StartAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            m_bb.setAnimation(true);
        }
    }
    
    
    //////////////////////////////////////// inner listener class StopAction
    class StopAction implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            m_bb.setAnimation(false);
        }
    }
}//endclass BBPanel

BallInBox:

Code:
// File:   animation/bb/BouncingBall.java
// Description: This Graphics panel simulates a ball bouncing in a box.
//         Animation is done by changing instance variables
//         in the timer's actionListener, then calling repaint().
//         * Flicker can be reduced by drawing into a BufferedImage, 
//           and/or using a clip region.
//         * The edge of the oval could be antialiased (using Graphics2).
// Author: Fred Swartz
// Date:   February 2005

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/////////////////////////////////////////////////////////////// BouncingBall
public class BallInBox extends JPanel {
    //============================================== fields
    //... Instance variables representing the ball.
    private Ball m_ball         = new Ball(0, 0, 2, 3);
    
    //... Instance variables for the animiation
    private int   m_interval  = 35;  // Milliseconds between updates.
    private Timer m_timer;           // Timer fires to anmimate one step.

    //========================================================== constructor
    /** Set panel size and creates timer. */
    public BallInBox() {
        setPreferredSize(new Dimension(200, 80));
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        m_timer = new Timer(m_interval, new TimerAction());
    }
    
    //========================================================= setAnimation
    /** Turn animation on or off.
     *@param turnOnOff Specifies state of animation.
     */
    public void setAnimation(boolean turnOnOff) {
        if (turnOnOff) {
            m_timer.start();  // start animation by starting the timer.
        } else {
            m_timer.stop();   // stop timer
        }
    }

    //======================================================= paintComponent
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // Paint background, border
        m_ball.draw(g);           // Draw the ball.
    }
    
    //////////////////////////////////// inner listener class ActionListener
    class TimerAction implements ActionListener {
        //================================================== actionPerformed
        /** ActionListener of the timer.  Each time this is called,
         *  the ball's position is updated, creating the appearance of
         *  movement.
         *@param e This ActionEvent parameter is unused.
         */
        public void actionPerformed(ActionEvent e) {
            m_ball.setBounds(getWidth(), getHeight());
            m_ball.move();  // Move the ball.
            repaint();      // Repaint indirectly calls paintComponent.
        }
    }
}//endclass


Bounce:

Code:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
/**
   Shows an animated bouncing ball.
*/
public class Bounce
{
   public static void main (String [] args)
   {
      JFrame frame = new BounceFrame ();
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      frame.show ();
   }
}
/**
   The frame with canvas and buttons.
*/
class BounceFrame extends JFrame implements MouseMotionListener
{
   /**
      Constructs the frame with the canvas for showing the
      bouncing ball and Start and Close buttons
   */
   public BounceFrame ()
   {
      setSize (WIDTH, HEIGHT);
      setTitle ("Bounce");

      Container contentPane = getContentPane ();
      canvas = new BallCanvas ();
      contentPane.add (canvas, BorderLayout.CENTER);
      JPanel buttonPanel = new JPanel ();
      addButton (buttonPanel, "Start",
         new ActionListener ()
            {  
               public void actionPerformed (ActionEvent evt)
               {
                  addBall ();
               }
            });

      addButton (buttonPanel, "Close",
         new ActionListener ()
            {
               public void actionPerformed (ActionEvent evt)
               {
                  System.exit (0);
               }
            });
      contentPane.add (buttonPanel, BorderLayout.SOUTH);
   }

   /**
      Adds a button to a container.
      @param c the container
      @param title the button title
      @param listener the action listener for the button
   */
   public void addButton (Container c, String title,
      ActionListener listener)
   {
      JButton button = new JButton (title);
      c.add (button);
      button.addActionListener (listener);
   }

   /**
      Adds a bouncing ball to the canvas and makes 
      it bounce 1,000 times.
   */
   public void addBall ()
   {
      try
      {
         Ball b = new Ball (canvas);
         canvas.add (b);

         for  (int i = 1; i <= 1000; i++)
         {
            b.move ();
            Thread.sleep (5);
         }
      }
      catch (InterruptedException exception)
      {                    
      }
   }

   private BallCanvas canvas;
   public static final int WIDTH = 450;
   public static final int HEIGHT = 350;  
}

/**
   The canvas that draws the balls.
*/
class BallCanvas extends JPanel
{
   /**
      Add a ball to the canvas.
      @param b the ball to add
   */
   public void add (Ball b)
   {
      balls.add (b);
   }

   public void paintComponent (Graphics g)
   {
      super.paintComponent (g);
      Graphics2D g2 = (Graphics2D)g;
      for (int i = 0; i < balls.size (); i++)
      {
         Ball b = (Ball)balls.get (i);
         b.draw (g2);
      }     
   }

   private ArrayList balls = new ArrayList ();
}

/**
   A ball that moves and bounces off the edges of a 
   component
*/
class Ball
{
   /**
      Constructs a ball in the upper left corner
      @c the component in which the ball bounces
   */
   public Ball (Component c) { canvas = c; }

   /**
      Draws the ball at its current position
      @param g2 the graphics context
   */
   public void draw (Graphics2D g2)
   {
      g2.fill (new Ellipse2D.Double (x, y, XSIZE, YSIZE));
   }

   /**
      Moves the ball to the next position, reversing direction
      if it hits one of the edges
   */
   public void move ()
   {
      x += dx;
      y += dy;
      if (x < 0)
      { 
         x = 0;
         dx = -dx;
      }
      if (x + XSIZE >= canvas.getWidth ())
      {
         x = canvas.getWidth () - XSIZE; 
         dx = -dx; 
      }
      if (y < 0)
      {
         y = 0; 
         dy = -dy;
      }
      if (y + YSIZE >= canvas.getHeight ())
      {
         y = canvas.getHeight () - YSIZE;
         dy = -dy; 
      }

      canvas.paint (canvas.getGraphics ());
   }

   private Component canvas;
   private static final int XSIZE = 15;
   private static final int YSIZE = 15;
   private int x = 0;
   private int y = 0;
   private int dx = 2;
   private int dy = 2;
}


Mouse: ( der Code zum zeichnen der Linie)

Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;


public class Mouse extends JFrame implements MouseMotionListener{
	
	private Point origin,target;
	
	public Mouse() {
		addMouseListener(new MouseAdapter() {
		
			@Override
			public void mouseReleased(MouseEvent e) {
				target=null;
				//repaint();
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				origin=e.getPoint();
			}
		
		});
		addMouseMotionListener(this);
		
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setSize(500,500);
		setLocationRelativeTo(null);
		setVisible(true);
		
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		if(origin==null || target==null)
			return;
		g.setColor(Color.BLUE);
		g.drawLine(origin.x, origin.y, target.x, target.y);
	}
	public void mouseDragged(MouseEvent e) {
		target=e.getPoint();
		repaint();
		
	}
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String[] args) {
		new Mouse();
	}
}

jetzt will ich iwie bei BallInBox.java das mit dem Linien zeichnen aus Mouse.java einfügen nur bin ich noch nicht so geübt in Java :D
 
S

SlaterB

Gast
und was funktioniert nicht?
ich sehe nirgendwo ein Setzen von target,

wieso nicht in mouseReleased():
target=e.getPoint();
?

(edit: ach, in mouseDragged(), was klappt denn nun nicht?,
logge oder debugge genau mit, wann wo welche Postition gesetzt oder gemalt wird)



aber das klingt mir eh schon nach einem 20 Seiten-Thread mit jedem Programmierschritt einzeln,
da werde ich eh nicht oft antworten, überleg dir gut was du fragst ;)
 

aggro600

Mitglied
Sry ich weiß so Java Newbes können nerven ^^
1.) also bounce.java gehört da gar nciht rein ^^
2.) also das programm mouse zum zeichnen funktioniert ja aber es arbeitet nicht mit dem BBdemo zusammen
so ich möchte es so haben, dass ich BBDemo starte und er das mit dem ball läd (das geht ja schon) und dann da wo der ball rum springt bzw. sind bewegt ich linien zeichnen kann.
3.) von den linien muss er nachher noch abprallen aber 1 nach 2 nach 3 ^^

danke erstmal das du mir hilfst =)
 
S

SlaterB

Gast
> ich möchte [..], dass ich [..] da wo der ball rum springt bzw. sind bewegt ich linien zeichnen kann.

niemand hindert dich daran,

da die Klasse Ball nicht gepostet ist, kann man dazu schwerlich was sagen,
der müsste schon Infos zu seiner Bewegung rausrücken, Start + Ende,
Funktionsbeschreibung falls in Kurvenbewegung,

schlimmstenfalls muss man alle x ms seine Position abfragen und eine kurze Linie seit der letzten Position merken/ malen,
oder dem Ball selber sagen, dass er auf seinem Wege eine Linie hinterlassen soll,

aber das wird ja wirklich experimentell.., ich sehe da sehr schwarz bei deinen Ansätzen,
anscheinend nur zusammenkopiert
 

aggro600

Mitglied
Ja ich bin halt nicht so gut in Java
aber ich brauch das wirklich wirklich dringend
wie bekomm ich das linien zeichen programm denn im meinem ball programm untergebracht?
 
S

SlaterB

Gast
BallInBox hat einen Timer mit einer TimerTask alle 35 ms,
da wird anscheindend der Ball ein Stück bewegt,
dort kannst du die Position vorher + nachher abfragen, in beliebigen Datenstrukturen (Listen) speichern und im paint dann auf diese Infos zugreifen, um z.B. für alle Positionen Linien zu malen,
viel hat das mit dem anderen Programm nicht mehr zu tun, da es ja überhaupt nicht mehr um Maus-Steuerung geht

in Vorausahnung der nächsten Frage 'ja und wie geht das genau?' + 100 weiterer:
viel Glück und Erfolg weiterhin ;)
 

aggro600

Mitglied
wie ich ne linie male weiß ich
nur ich möchte nicht das der ball ne linie hinter sich her zieht sondern ich zieh eine mit der maus
das programm Mouse.java ist ja auch schon genau richtig
nur ich check nicht wie ich die klasse mouse in BallInBax einfügen kann
so schwer kanns ja nicht sein nur vllt hab ich was übersehn?
 
S

SlaterB

Gast
na gut, das klingt ja ganz anders,

schwer kann es nicht sein, was meinst du mit 'übersehn'? du programmierst es einfach nicht, deswegen ist es noch nicht drin,
mit übersehen hat das nix zu tun,

> public class BallInBox extends JPanel

public class BallInBox extends JPanel implements MouseMotionListener

+


addMouseListener(new MouseAdapter() {
....
});

in den Konstruktor von BallInBox übernehmen,
die Methoden mouseDragged usw. in BallInBox definieren, auch die Variablen origin + target

und den paint-Kram
> if(origin==null || target==null)
> return;
> g.setColor(Color.BLUE);
> g.drawLine(origin.x, origin.y, target.x, target.y);


am Ende von paintComponent(Graphics g) in BallInBox einfügen
 

aggro600

Mitglied
Das hab ich gemacht und bekommen 29 Errors
Code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
// File:   animation/bb/BouncingBall.java
// Description: This Graphics panel simulates a ball bouncing in a box.
//         Animation is done by changing instance variables
//         in the timer's actionListener, then calling repaint().
//         * Flicker can be reduced by drawing into a BufferedImage, 
//           and/or using a clip region.
//         * The edge of the oval could be antialiased (using Graphics2).
// Author: Fred Swartz
// Date:   February 2005

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

/////////////////////////////////////////////////////////////// BouncingBall
public class BallInBox extends JPanel implements MouseMotionListener {
    //============================================== fields
    //... Instance variables representing the ball.
    private Ball m_ball         = new Ball(0, 0, 3, 0);
    
    //... Instance variables for the animiation
    private int   m_interval  = 20;  // Milliseconds between updates.
    private Timer m_timer;           // Timer fires to anmimate one step.
	
	//Neu
	
	addMouseListener(new MouseAdapter() {
		
			@Override
			public void mouseReleased(MouseEvent e) {
				target=null;
				//repaint();
			}
			
			@Override
			public void mousePressed(MouseEvent e) {
				origin=e.getPoint();
			}
		
		});//Ende des neuen
    //========================================================== constructor
    /** Set panel size and creates timer. */
    public BallInBox() {
        setPreferredSize(new Dimension(800, 600));
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        m_timer = new Timer(m_interval, new TimerAction());
    }
    
    //========================================================= setAnimation
    /** Turn animation on or off.
     *@param turnOnOff Specifies state of animation.
     */
    public void setAnimation(boolean turnOnOff) {
        if (turnOnOff) {
            m_timer.start();  // start animation by starting the timer.
        } else {
            m_timer.stop();   // stop timer
        }
    }

    //======================================================= paintComponent
    public void paintComponent(Graphics g) {
        super.paintComponent(g);  // Paint background, border
        m_ball.draw(g);           // Draw the ball.
    
    
    //Neu     
    if(origin==null || target==null)
			return;
		g.setColor(Color.BLUE);
		g.drawLine(origin.x, origin.y, target.x, target.y);
	}
	public void mouseDragged(MouseEvent e) {
		target=e.getPoint();
		repaint();
		
	}
	public void mouseMoved(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String[] args) {
		new Mouse();
	}  //Ende des neuen
        
        
    }// Ende paintComponent
    
    //////////////////////////////////// inner listener class ActionListener
    class TimerAction implements ActionListener {
        //================================================== actionPerformed
        /** ActionListener of the timer.  Each time this is called,
         *  the ball's position is updated, creating the appearance of
         *  movement.
         *@param e This ActionEvent parameter is unused.
         */
        public void actionPerformed(ActionEvent e) {
            m_ball.setBounds(getWidth(), getHeight());
            m_ball.move();  // Move the ball.
            repaint();      // Repaint indirectly calls paintComponent.
        }
    }
}//endclass
Fehler:
Hab 29 Fehler nur kann ich die iwie nicht aus JOE kopieren oO
Code:
C:\Dokumente und Einstellungen\Nils\Eigene Dateien\Java\BallInBox.java:35: invalid method declaration; return type required 	addMouseListener(new MouseAdapter() { 	^
so hatte ichs gerade auch schon und das meinte ich mit übersehn vllt seh ich den Wald ja vor lauter Bäumen nicht
 
Zuletzt bearbeitet:
S

SlaterB

Gast
hier mal ein bisschen hin und her geschoben, so dass es Eclipse zumindest formatiert,
wenn du den MouseListener VOR dem Konstruktor addest, dann scheinen dir anscheinend selbst Grundlagen aus Kapitel 1 zu fehlen,

zum x-ten Mal: so wird das doch nix ;)



Java:
class BallInBox
    extends JPanel
    implements MouseMotionListener
{
    // ============================================== fields
    // ... Instance variables representing the ball.
    private Ball m_ball = new Ball(0, 0, 3, 0);

    // ... Instance variables for the animiation
    private int m_interval = 20; // Milliseconds between updates.
    private Timer m_timer; // Timer fires to anmimate one step.


    // ================================================== ======== constructor
    /** Set panel size and creates timer. */
    public BallInBox()
    {
        setPreferredSize(new Dimension(800, 600));
        setBorder(BorderFactory.createLineBorder(Color.BLACK));
        m_timer = new Timer(m_interval, new TimerAction());

        // Neu

        addMouseListener(new MouseAdapter()
            {

                @Override
                public void mouseReleased(MouseEvent e)
                {
                    target = null;
                    // repaint();
                }

                @Override
                public void mousePressed(MouseEvent e)
                {
                    origin = e.getPoint();
                }

            });// Ende des neuen
    }

    // ================================================== ======= setAnimation
    /**
     * Turn animation on or off.
     * 
     * @param turnOnOff
     *            Specifies state of animation.
     */
    public void setAnimation(boolean turnOnOff)
    {
        if (turnOnOff)
        {
            m_timer.start(); // start animation by starting the timer.
        }
        else
        {
            m_timer.stop(); // stop timer
        }
    }

    // ================================================== ===== paintComponent
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g); // Paint background, border
        m_ball.draw(g); // Draw the ball.


        if (origin == null || target == null) return;
        g.setColor(Color.BLUE);
        g.drawLine(origin.x, origin.y, target.x, target.y);

    }// Ende paintComponent

    // Neu

    public void mouseDragged(MouseEvent e)
    {
        target = e.getPoint();
        repaint();
    }

    public void mouseMoved(MouseEvent e)
    {
        // TODO Auto-generated method stub

    }

    public static void main(String[] args)
    {
        //
    } // Ende des neuen

    // ////////////////////////////////// inner listener class ActionListener
    class TimerAction
        implements ActionListener
    {
        // ================================================== actionPerformed
        /**
         * ActionListener of the timer. Each time this is called, the ball's position is
         * updated, creating the appearance of movement.
         * 
         * @param e
         *            This ActionEvent parameter is unused.
         */
        public void actionPerformed(ActionEvent e)
        {
            m_ball.setBounds(getWidth(), getHeight());
            m_ball.move(); // Move the ball.
            repaint(); // Repaint indirectly calls paintComponent.
        }
    }
}// endclass

edit
> vllt seh ich den Wald ja vor lauter Bäumen nicht

solche Sätze nerven mehr als dass sie relativieren, wenn man anscheinend völlig fern von gesicherten Kenntnissen agiert
 
Zuletzt bearbeitet von einem Moderator:

aggro600

Mitglied
so hab alles gemacht auch mit
private Point origin,target;
und 0 Errors aber kann nix malen

hat das vllt was damit zu tun
Code:
    // Neu
 
    public void mouseDragged(MouseEvent e)
    {
        target = e.getPoint();
        repaint();
    }
 
    public void mouseMoved(MouseEvent e)
    {
        // TODO Auto-generated method stub
 
    }
der ruft ja repaint() auf is da vllt ein fehler in der logig
 
Zuletzt bearbeitet:
Status
Nicht offen für weitere Antworten.

Neue Themen


Oben