Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Simple thread - Bouncing ball

bouncing ball

  • Please log in to reply
11 replies to this topic

#1 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 28 November 2009 - 08:08 AM

Hey Codecall !

I saw some threads with ping pong games and such, however most of them were broken.
So I thought, well let people have something simple to work with?
Maybe a running thread?

Anyways here it is !

Classes needed
import java.awt.*;
First class, our own Thread class that has a function we want...
class XThread extends Thread {
    public static boolean delay(long millis) {
        if (interrupted())
            return false;
        try {
            sleep(millis);
        } catch (InterruptedException e) {
            return false;
        }
        return true;
    }
}
Firstly, we inherit from Thread, since I didn't want to do something heavy, just made something simple. XThread will be the one to run later on...
The ball class
public class Ball extends Panel implements Runnable {
	protected Thread activity;
	private int r,x0,y0;
	private int xStep,yStep;
So, our ball, extends its area from Panel and we implement the runnable interface for our ball to since we are going to work with one thread...
Thread activity is our thread for the main dish...
While r,x0,y0 will represent the r for radius of a ball and x0 y0 start points.
Balls everywhere !
public Ball(int radius,int xSpeed, int ySpeed) {
		r = radius; xStep = xSpeed; yStep = ySpeed;
		x0 = r; y0 = r;
	}
Our constructor that will create the main ball every time we want to have balls.
Thread activity - Start || Stop
public void start() {
		if(activity == null) {
			activity = new Thread(this);
			activity.start();
		}
	}
	public void stop() {
		if(activity != null) {
			activity.interrupt();
			}
		}
As for our methods that will start of the execution of tasking we want(moving a ball...)
We will have to see when the activity is null. Thats when we will start a new thread which will allow the ball to interact with out panel area...
As stop checks if activity isn't null it will interrupt the activity, inherit from Thread applied to our own class called XThread.
Running with a Runnable interface you will need a method called run
public void run() {
		while(XThread.delay(100)) {
			if(x0-r+xStep<0 || x0+r+xStep > getSize().width)
				xStep = -xStep;
				x0 += xStep;
			if(y0-r+yStep<0 || y0+r+yStep > getSize().height)
				yStep = - yStep;
				y0 += yStep;
				repaint();
		}
	}
So ** mentioned, XThread is just a small adjustment of our own taste, my tasted I gotten to taste... Allowing the execution happen while the thread isn't destroyed or interrupted...
So, how does it move, while executing the process we have to have conditions it can follow or be bound to... ifx0-r+xStep<0 or x0+r+xStep>getSize().width Follows to, if start point minus radius+the speed in x axle, is less than 0 or invers, meaning from |<-->|. Literally from first point of wall to the last...
Same goes for in the y axle...
Drawing the ball...
public void paint(Graphics g) {
		g.fillOval(x0-r,y0-r,2*r,2*r);
	}
}
Drawing the ball depending from the radius point of x0 and y0. The rest is simple to get...Math...meh :-P
Demonstration of our ball, first off classes needed
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;
Nothing much to pinpoint at...
Our class
public class BallDemo extends JFrame implements ActionListener {
Inheriting everything from JFrame as well using the interface ActionListener.
Every item we come to need to create a simple interface...
private Ball b;
	private JPanel panel = new JPanel();
	private JMenuBar JMB = new JMenuBar();
	private JMenu JM = new JMenu("Edit");
	private JMenuItem[] JMI = new JMenuItem[3];
	int r,sp;
As we connect a bridge with ball, and gave it the name b, we will be able to reach every method(public or protected) and instances...
Constructor
public  BallDemo() {
		JMI[0] = new JMenuItem("Start");
		JMI[1] = new JMenuItem("Stop");
		JMI[2] = new JMenuItem("Close");
		JMB.setSize(640, 20);
		String s = showInputDialog(null,"Radie");
		r = Integer.parseInt(s);
		s = showInputDialog(null,"Speed");
		sp = Integer.parseInt(s);
		b = new Ball(r,sp,sp);
		setLayout(null);
		add(panel);
		panel.setBackground(Color.white);
		panel.setSize(640,440);
		panel.setLocation(JMB.getX(), JMB.getY()+20);
		b.setLocation(b.getWidth(), b.getHeight());
		panel.setLayout(new BorderLayout());
		panel.add(b);
		add(JMB);
		JMB.add(JM);
		JM.add(JMI[0]);
		JM.add(JMI[1]);
		JM.add(JMI[2]);
		setSize(640,480);
		setResizable(false);
		JMI[0].addActionListener(this);
		JMI[1].addActionListener(this);
		JMI[2].addActionListener(this);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		show();
	}
As we used an array for our buttons, we will have to define every position of the array with a new button option thus allowing us to give them proper name as well use them correct...
Also, as I inheriting everything from JFrame, I can easily just use the methods without a reference variable.
Methods calling the balls stop and start methods.
public void start() {
		b.start();
	}
	public void stop() {
		b.stop();
	}
Nothing much to see, just using our reference to grab .stop and .start for our simple bouncing ball.
Our actionlistener...
public void actionPerformed(ActionEvent e) {
		if(e.getSource()==JMI[0]) {
				start();
			
		}
		else if(e.getSource()==JMI[1]) {
			stop();
		}
		else {
			System.exit(0);
		}
	}
As we used buttons, with names that supposedly do, so while pressing Start we activate our own method which activates the Balls method called start weird right?
Main
public static void main(String[] arg) {
		new BallDemo();
	}
	
}
So, just create a new BallDemo and run it while having fun !
More or less this is it :)
Grab it, evolve it or just reconstruct it the way you want it or, just make your own without looking at this one !

Run it...
[ATTACH]2366[/ATTACH]
Running...
[ATTACH]2367[/ATTACH]
Stopping...
[ATTACH]2368[/ATTACH]
Closing it...
[ATTACH]2369[/ATTACH]

Cheers ! :amr:

Attached Thumbnails

  • run it4.PNG
  • run it3.PNG
  • run it2.PNG
  • run it.PNG

  • 3

#2 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 29 November 2009 - 12:00 PM

Neat! Well done, +rep!
  • 0

#3 marwex89

marwex89

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 2857 posts

Posted 29 November 2009 - 12:01 PM

Neat! +rep
  • 0
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#4 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 29 November 2009 - 12:05 PM

Neat! Well done, +rep!

Thank you :)

Neat! +rep

Thank you too :)
  • 0

#5 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 30 November 2009 - 08:53 AM

Nicely done, +rep
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#6 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 30 November 2009 - 10:12 AM

Nicely done, +rep


Haha thank you :)
  • 0

#7 amrosama

amrosama

    CC Mentor

  • VIP Member
  • PipPipPipPipPipPipPipPip
  • 2765 posts

Posted 30 November 2009 - 12:40 PM

nice one, was waiting for it :D!
+rep
  • 0
yo homie i heard you like one-line codes so i put a one line code that evals a decrypted one line code that prints "i love one line codes"
eval(base64_decode("cHJpbnQgJ2kgbG92ZSBvbmUtbGluZSBjb2Rlcyc7"));
www.amrosama.com | the unholy methods of javascript

#8 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 30 November 2009 - 12:52 PM

nice one, was waiting for it :D!
+rep


Haha, sounds great :)
  • 0

#9 Impulser

Impulser

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 13 January 2010 - 06:54 PM

Very nice explanation and overall a great tutorial. I learned I bit from this.

Thanks.
  • 0

#10 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 13 January 2010 - 11:56 PM

Very nice explanation and overall a great tutorial. I learned I bit from this.

Thanks.


Great to know :)
  • 1

#11 whitey6993

whitey6993

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 156 posts

Posted 30 January 2010 - 02:45 PM

Very Cool, +rep.
  • 0

#12 Turk4n

Turk4n

    ???

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1919 posts
  • Location:Sweden
  • Programming Language:C, Java, PHP, Python, Bash
  • Learning:C++, C#, JavaScript, Visual Basic .NET, Others

Posted 31 January 2010 - 12:35 AM

Very Cool, +rep.


Thank you :)
  • 0





Also tagged with one or more of these keywords: bouncing ball

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download