Hi,Norm jon,
I am posting a new thread for tagging the code accordingly. Hope this helps out.

1.My ball is not bouncing within the circle i drew.(Within circle 2).It just goes vaguely toward one direction and comes back.I want the ball to bounce randomly.Just like in the game ball and the brick where u have to break the bricks using the ball bouncing randomly.

2.And , i also want to move the triangle according to my direction keys.(Look at the triangle class and the KeyPressed() method).The triangle does move but only once.After that no matter how many times i press the directional key all in vain. I would like to request you to run the code in your locally machine in Eclipse for a better idea of what am asking. You will easily get what m trying to do.

3. And if possible the triangle i made gotta shoot small balls(like bullets from a gun) and when it strikes the bouncing ball, the ball should break up into 2 separate balls.Any idea on how to do this functionality will be of great help.
Hope to c your reply really soon.

import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.*;
import java.awt.Frame;
import java.awt.geom.*;

class BallEntity/* THE BALL CLASS */
{

	private int top = 0, left = 0, height = 0, width = 0;

	// getter methods
	public int getTop() {
		return top;
	}

	public int getLeft() {
		return left;
	}

	public int getHeight() {
		return height;
	}

	public int getWidth() {
		return width;
	}

	// setter methods
	public void setTop(int t) {
		top = t;
	}

	public void setLeft(int l) {
		left = l;
	}

	public void setHeight(int h) {
		height = h;
	}

	public void setWidth(int w) {
		width = w;
	}
}

class Triangle extends Polygon /* THE TRIANGLE CLASS */
{
	public Triangle(int x1, int y1, int x2, int y2, int x3, int y3)
	{
		super(new int[] { x1, x2, x3 }, new int[] { y1, y2, y3 }, 3);
	}

}

public class Mygame extends Frame implements Runnable, KeyListener /*
																	 * Main
																	 * class,KeyListner
																	 * interface
																	 * implemented
																	 * to
																	 * capture
																	 * keyevents
																	 */
{
	Shape circle1 = new Ellipse2D.Float(250.0f, 210.0f, 500.0f, 500.0f);/*
																		 * MAKING
																		 * OF
																		 * OUTER
																		 * CIRCLE
																		 */
	Shape circle2 = new Ellipse2D.Float(270.0f, 230.0f, 460.0f, 460.0f);/*
																		 * MAKING
																		 * OF
																		 * INNER
																		 * CIRCLE,Shape
																		 * an
																		 * interface,Ellipse2D.Float
																		 * a
																		 * class
																		 */
	Shape triangle = new Triangle(400, 500, 450, 500, 425, 550);
	BallEntity ball;

	public void initBall()/* INITIALIZATION OF BALL */
	{
		ball.setTop(500);
		ball.setLeft(500);
		ball.setHeight(40);
		ball.setWidth(40);

	}

	public void paint(Graphics g)/* MAKING SHAPES IN THE FRAME CLASS */
	{

		Graphics2D ga = (Graphics2D) g;
		ga.draw(circle1);
		ga.setPaint(Color.black);

		ga.setPaint(Color.black);
		ga.draw(circle2);

		/* ga.drawOval(ball.getLeft(),ball.getTop(),ball.getHeight(),ball.getWidth()); */
		ga.setColor(Color.black);
		ga.fillOval(ball.getLeft(), ball.getTop(), ball.getHeight(), ball.getWidth());
		ga.draw(triangle);

	}

	public static void main(String[] args) {
		Mygame obj = new Mygame();

		obj.addWindowListener(new WindowAdapter()/* closing event */
		{
			public void windowClosing(WindowEvent we) {
				System.exit(0);

		}

		});
	}

	Mygame()/* constructor,making of frame,starting of thread, */
	{

		this.setSize(500, 800);
		this.setVisible(true);
		this.setTitle("My Game");
		ball = new BallEntity();
		initBall();

		Thread th = new Thread(this);
		th.start();
		this.addKeyListener(this);
	}

	public void keyPressed(KeyEvent e) /* KEY BOARD MOVEMENTS CAPTURED */
	{
		int Key_Code = e.getKeyCode();
		int d = 5;

		switch (Key_Code) {
		case java.awt.event.KeyEvent.VK_LEFT:
			triangle = new Triangle(400 - d, 500, 450 - d, 500, 425 - d, 550);
			break;
		case java.awt.event.KeyEvent.VK_RIGHT:
			triangle = new Triangle(400 + d, 500, 450 + d, 500, 425 + d, 550);
			break;
		case java.awt.event.KeyEvent.VK_UP:
			triangle = new Triangle(400, 500 - d, 450, 500 - d, 425, 550 - d);
			break;
		case java.awt.event.KeyEvent.VK_DOWN:

			triangle = new Triangle(400, 500 + d, 450, 500 + d, 425, 550 + d);
			break;

		}
		this.repaint();
	}

	public void keyTyped(KeyEvent e) {
	}

	public void keyReleased(KeyEvent e) {

	}

	public void run() {

		// variables for storing direction of the ball and its amount of
		// distance
		// by which we move it in the next movement
		int direction = 5; // 1 north
		// 2 south
		// 3 east
		// 4 west
		// 5 north east
		// 6 north west
		// 7 south east
		// 8 south west

		int dist1 = 10;
		int dist2 = 5;

		// continue till the program ends
		while (true) {
			// just a temporary variable for storing intermediate ball position
			int tempTop = 0;
			int tempLeft = 0;

			// if direction is set to go up i.e. 2 then subtract distance
			// if direction is set to go down then add distance
			switch (direction) {
			case 1: // north
				tempTop = ball.getTop() + dist1;
				break;
			case 2: // south
				tempTop = ball.getTop() - dist1;
				break;
			case 3: // east
				tempTop = ball.getLeft() - dist2;
				break;
			case 4: // west
				tempTop = ball.getLeft() + dist2;
				break;
			case 5: // north east
				tempTop = ball.getTop() - dist1;
				tempLeft = ball.getLeft() - dist2;
				break;
			case 6: // north west
				tempTop = ball.getTop() - dist1;
				tempLeft = ball.getLeft() + dist2;
				break;
			case 7: // south east
				tempTop = ball.getTop() + dist1;
				tempLeft = ball.getLeft() - dist2;
				break;
			case 8: // south west
				tempTop = ball.getTop() + dist1;
				tempLeft = ball.getLeft() + dist2;
				break;
			}
			// update the balls position in the datastructure
			ball.setTop(tempTop);
			ball.setLeft(tempLeft);
			// if you have reached bottom change directions
			if (ball.getTop() >= 350 && direction == 1) // coming north now go
														// south
				direction = 2;
			// if you have reached the top change directions
			if (ball.getTop() <= 50 && direction == 2) // coming south now go
														// north
				direction = 1;
			if (ball.getLeft() <= 50 && direction == 3)
				// coming east now go west
				direction = 4;
			if (ball.getLeft() >= 450 && direction == 4)
				// coming east now go west
				direction = 3;
			if ((ball.getLeft() <= 50 || ball.getTop() <= 50) && direction == 5)
				// coming north east now go south west
				direction = 8;
			if ((ball.getLeft() >= 450 || ball.getTop() <= 50)
					&& direction == 6)
				// coming north west now go south east
				direction = 7;
			if ((ball.getLeft() <= 50 || ball.getTop() >= 350)
					&& direction == 7)
				// coming south east now go north west
				direction = 6;
			if ((ball.getLeft() >= 450 || ball.getTop() >= 350)
					&& direction == 8)
				// coming north east now go south west
				direction = 5;
			// redraw the ball at new locations
			this.repaint();
			// putting the thread to sleep so we can create some delay
			// so the ball's motion looks natural.
			try {
				Thread.sleep(300);
				// maikng the thread sleep for while to make d motion of d ball
				// look a bit real
			} catch (Exception e) {

				System.out.println("Error in running thread " + e);
			}
		}
	}

}

Hey Norm,

1.My problem is that the triangle i am trying to move using directional keys is not working properly in the frame .(Code line 139 to 160):

2.Also i want to bounce the ball randomly in the circle which also is not functioning properly.(Code170 to272) If you could suggest a different idea to what m trying to do will also be of help.

3.If any idea of how can i make my triangle shoot small balls from any of the vertices of the triangle will also be of great help.

This is much easier to read. (I'm actually glad that you didn't include debug code here, although I agree with Norm that they will certainly help you know what's going on at any given point in your code.)


I'm reading it now, notes follow:

- why no constructor for your Ball class? You have setters, and an initBall method that sets up your ball to a default set of values. Ball should have a constructor that takes any values that you expect to be set at startup. You should then create a void constructor to handle your default Ball. This would just call your more elaborate constructor with the default values.
Like this:

public BallEntity(int thisOne, int thatOne, int theOtherOne)
{
this.thisOne = thisOne;  // your variables here
this.thatOne = thatOne;
this.theOtherOne = theOtherOne;
}

public BallEntity()
{
this(45, 90, 23);  // calls the full contructor with these values
}

Then get rid of initBall, you don't need it. When you make a new BallEntity, without parameters in the constructor, it'll just build you the basic standard default BallEntity. (there are times when you need to initialize an object from another object, but this isn't one of them)

- Ball is just a bag of data. This is okay, but you should wonder what it is that balls do, and why this one doesn't do anything. You might find that there are bits of functionality that you're doing in other places which would be better localized in the BallEntity class. Haven't seen them yet, but I'm still walking through the code.

- Still in Ball: do you expect the width and height to change in the course of the applet? Do you expect the ball to be anything but circular? You can get rid of setters that aren't going to be called, and replace height and width with radius if the ball is a circle. If the ball will change shape in the game, of course, you might want to keep these. Better, though (referring to previous comment) to let the ball change itself. If the ball grows under some circumstances, put in a "grow()" method which figures out what its new size should be and sets itself accordingly. This way you don't have to keep track of the size (or use those getters, also probably not necessary) to deal with the size of the ball in some class. (Imagine a terrible mailroom worker: you bring him a letter, and he asks you how much postage to put on it. You either have to have that written down somewhere, or you ask him, what's the postage on a letter?, and he tells you, and you say, okay, put that much on the letter)

Okay, so we haven't got to your actual problems yet, but there's some things to fix. I'll have more for you shortly, which might even address the problem you asked about.

My problem is that the triangle i am trying to move using directional keys is not working properly

Why is that? Add some debugging statements to see what is happening. There is no magic here. The code is generating numbers different from what you are expecting. If you print out the numbers you will see what is happening and can then work on how to change the code to make it do what you want.
Let me take your hand and show you how to do this. Add the following in the Triangle constructor after the call to super:

System.out.println("tri at=" + x1 + " " + y1); // show where

You could add the other 4 variables if these 2 are not enough.

This is much easier to read. (I'm actually glad that you didn't include debug code here, although I agree with Norm that they will certainly help you know what's going on at any given point in your code.)


I'm reading it now, notes follow:

- why no constructor for your Ball class? You have setters, and an initBall method that sets up your ball to a default set of values. Ball should have a constructor that takes any values that you expect to be set at startup. You should then create a void constructor to handle your default Ball. This would just call your more elaborate constructor with the default values.
Like this:

public BallEntity(int thisOne, int thatOne, int theOtherOne)
{
this.thisOne = thisOne;  // your variables here
this.thatOne = thatOne;
this.theOtherOne = theOtherOne;
}

public BallEntity()
{
this(45, 90, 23);  // calls the full contructor with these values
}

Then get rid of initBall, you don't need it. When you make a new BallEntity, without parameters in the constructor, it'll just build you the basic standard default BallEntity. (there are times when you need to initialize an object from another object, but this isn't one of them)

- Ball is just a bag of data. This is okay, but you should wonder what it is that balls do, and why this one doesn't do anything. You might find that there are bits of functionality that you're doing in other places which would be better localized in the BallEntity class. Haven't seen them yet, but I'm still walking through the code.

- Still in Ball: do you expect the width and height to change in the course of the applet? Do you expect the ball to be anything but circular? You can get rid of setters that aren't going to be called, and replace height and width with radius if the ball is a circle. If the ball will change shape in the game, of course, you might want to keep these. Better, though (referring to previous comment) to let the ball change itself. If the ball grows under some circumstances, put in a "grow()" method which figures out what its new size should be and sets itself accordingly. This way you don't have to keep track of the size (or use those getters, also probably not necessary) to deal with the size of the ball in some class. (Imagine a terrible mailroom worker: you bring him a letter, and he asks you how much postage to put on it. You either have to have that written down somewhere, or you ask him, what's the postage on a letter?, and he tells you, and you say, okay, put that much on the letter)

Okay, so we haven't got to your actual problems yet, but there's some things to fix. I'll have more for you shortly, which might even address the problem you asked about.

Hi Jon,
The setters method are there to reposition the ball in d frame(NOT APPLET) after the thread sleep(Code line 170-272).This thread runs to make the ball bounce in the circle randomly much like the brick and ball game where we break the bricks with ball bouncing randomly.But the randomness in the bouncing isn't there.May be a different approach should be applied.You can suggest one .I can try it.

And the other messy part is the keyPressed() method.(code line 139).My Triangle object do move by pressing the directional keys but only once.i think you can figure out the problem as its a very short logic involving only Triangle object and the keyPressed() method.I gotta move the triangle in the frame. Seemed easy but could not go do it.

Okay, continuing on. Your Triangle class is pretty minimal. It creates itself and then there's no way to do anything to it. This may be why it's not moving. Norm's advice is (as usual) good advice. If you want to know what's happening in Triangle, you should ask it to tell you.

Okay, so now I'm looking in your main, and I see a whole lot of code dedicated to moving a ball around. Is this best done by the main class? Or is there a class that's more directly concerned with the ball's position and location?
Incidentally, I don't see any code that's responsible for moving your Triangle. (the code you think is moving it, isn't - what is it really doing?)

Looking at the code for motion, it's obvious why your motion is not random: you have no call to a randomizer. However, that's not your problem. Newtonian mechanics is not random, and that's what you're trying to model, apparently. So don't go bringing in java.util.Random or Math.random - they're not what you need here.
Instead, look at your series of if statements, and run them through by hand. Pick a reasonable set of starting values, and move through the steps you've coded. I think you'll find pretty quickly that you're in a steady cycle, which is what you mean by "not random".
The problem is that your physics allows only for reversing direction.

The fix is not going to be easy - you have to rewrite all of your motion code to reflect the actual bouncing of a ball. In a simplified, frictionless world, that's not so difficult, but pretty much everything you've got is going to have to be replaced. I see no way to salvage this code and make it bounce a ball in the way you want to, particularly not when you're talking about bouncing inside a circle. I don't think this can be done with if statements - there are formulas for this, I don't know off the top of my head what you'd use for a ball moving at (deltzX, deltaY) bouncing off the impact of a circle - possibly you'd figure it as if it were hitting a line tangent to the circle at the point of impact, but I don't know if that's right.
Anyway, I'm sorry, but there's no easy fix for the ball bouncing, given your current code.

My Triangle object do move by pressing the directional keys but only once.i think you can figure out the problem

Try debugging your code by adding the following in the Triangle constructor after the call to super:

System.out.println("tri at=" + x1 + " " + y1); // show where

You could add the other 4 variables if these 2 are not enough.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.