Jump to content

Simple thread - Bouncing ball

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
11 replies to this topic

#1
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts
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 ass 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 Files


Posted Image

#2
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Neat! Well done, +rep!

#3
marwex89

marwex89

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 10,720 posts
Neat! +rep
Hey! Check out my new Toyota keyboaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

#4
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

Jordan said:

Neat! Well done, +rep!
Thank you :)

marwex89 said:

Neat! +rep
Thank you too :)
Posted Image

#5
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Nicely done, +rep
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#6
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

WingedPanther said:

Nicely done, +rep

Haha thank you :)
Posted Image

#7
amrosama

amrosama

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 8,674 posts
nice one, was waiting for it :D!
+rep
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

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

amrosama said:

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

Haha, sounds great :)
Posted Image

#9
Impulser

Impulser

    Newbie

  • Members
  • Pip
  • 5 posts
Very nice explanation and overall a great tutorial. I learned I bit from this.

Thanks.

#10
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

Impulser said:

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

Thanks.

Great to know :)
Posted Image

#11
whitey6993

whitey6993

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 437 posts
Very Cool, +rep.

#12
Turk4n

Turk4n

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,847 posts

whitey6993 said:

Very Cool, +rep.

Thank you :)
Posted Image