Bounce off

M

Max

I am trying to have a bouncing ball that (as you can probably tell
from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.

private void detectTopOrBottom(){
if (location.x <= 1 || location.x >= (width - 1)){
dx = -dx;}
if (location.y <= 1 || location.y >= (height - 1)){
dy = -dy;}}
 
A

Andrew Thompson

I am trying to have a bouncing ball that (as you can probably tell
from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.

That's too bad. Did you have a question,
or were you just after sympathy**?

If the former, you might try posting a short,
compilable example* that would explain things
like..
- what is location, when is it updated and by what?
- " " width " " " " " " "?
- " " height " " " " " " "?
- ..

* More specifically, an SSCCE is generally the
preferred way to express that.
<http://www.physci.org/codes/sscce.html>

** Oh, and if the latter.
'There there.. there there'

Andrew T.
 
A

Andreas Leitgeb

Max said:
I am trying to have a bouncing ball that (as you can probably tell
from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.

private void detectTopOrBottom(){
if (location.x <= 1 || location.x >= (width - 1)){
dx = -dx;}
if (location.y <= 1 || location.y >= (height - 1)){
dy = -dy;}}

There is some lack of information about dx,dy:
can they be >1 (fast moves) ?
can they be <1 (slow move, or purely horizontal/vertical move)
can they be anything between 0 and 1 ? (type double or int?)

If they can be anything else than 1 or -1, then you might run
into the problem that just reversing the direction fails to move
the ball back inside the bounds. (for that to really happen,
there must be some more places that modify speed or position,
but I find it quite likely that this happens, or the balls
trajectory would be quite boring)
Once the ball is "out", and reversing the direction doesn't bring
it "in" immediately, it will toggle direction every time, and it's
a question of mere luck whether it gets back "in" any time at all.

if (location.x <= 1) {
if (dx<0) dx=-dx;
location.x=1-location.x;
}
if (location.x >= (width-1) ) {
if (dx>0) dx=-dx;
location.x=2*(width-1)-location.x;
}

And analogously for "y". if your dx,dy are ints you might need
casts for the Math.abs()... or you just throw in a second "if":
if (dx<0) dx=-dx;

PS: the bounds of your field look asymmetric:
if the field is exactly "width" positions wide, then
the valid indices are 0..(width-1) You cut the left
edge, but don't cut the right edge.
If this is on purpose, then it's fine, otherwise it my be some bug.
 
A

Alex Hunsley

Max said:
I am trying to have a bouncing ball that (as you can probably tell
from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.

private void detectTopOrBottom(){
if (location.x <= 1 || location.x >= (width - 1)){
dx = -dx;}
if (location.y <= 1 || location.y >= (height - 1)){
dy = -dy;}}

Perhaps this code doesn't work because you haven't defined a class, a
main method, etc?
(Hint: try actually asking a question and stating what your actually
problem is apart from "does not work".)
 
F

Faton Berisha

I am trying to have a bouncing ball that (as you can probably tell
from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.
[snip]

Bellow follows a complete working example with model, view and
controller components.

Pay attention to the OO design implemented.

If I may, I would also suggest a very good book to begin with: D.
Schmidt, Programming principles in Java -- architectures and
interfaces, which can be obtained for free at the following site:

http://www.cis.ksu.edu/santos/schmidt/ppj

Regards,
Faton Berisha


public class MovingBall
{ private int xPos;
private int yPos;
private int radius;
private int xVelocity = 5;
private int yVelocity = 2;
private Box container;

public MovingBall(int xInit, int yInit, int r, Box box)
{ xPos = xInit;
yPos = yInit;
radius = r;
container = box;
}

public int xPosition()
{ return xPos; }

public int yPosition()
{ return yPos; }

public int radiusOf()
{ return radius; }

public void move()
{ xPos = xPos + xVelocity;
if ( container.inHorizontalContact(xPos) )
{ xVelocity = -xVelocity; }
yPos = yPos + yVelocity;
if ( container.inVerticalContact(yPos) )
{ yVelocity = -yVelocity; }
}
}


public class Box
{ private int boxSize;
public Box(int size)
{ boxSize = size; }

public boolean inHorizontalContact(int xPosition)
{ return xPosition <= 0 || xPosition >= boxSize; }

public boolean inVerticalContact(int yPosition)
{ return yPosition <= 0 || yPosition >= boxSize; }

public int sizeOf()
{ return boxSize; }
}


import java.awt.*;
public class BallWriter
{ private MovingBall ball;
private Color color;

public BallWriter(MovingBall b, Color c)
{ ball = b;
color = c;
}

public void paint(Graphics g)
{ g.setColor(color);
int radius = ball.radiusOf();
g.fillOval(ball.xPosition() - radius,
ball.yPosition() - radius, 2 * radius, 2 * radius);
}
}


import java.awt.*;
public class BoxWriter
{ private Box box;

public BoxWriter(Box b)
{ box = b; }

public void paint(Graphics g)
{ int size = box.sizeOf();
g.setColor(Color.white);
g.fillRect(0, 0, size, size);
g.setColor(Color.black);
g.drawRect(0, 0, size, size);
}
}


import javax.swing.*;
import java.awt.*;
public class AnimationWriter extends JPanel
{ private BoxWriter boxWriter;
private BallWriter ballWriter;

public AnimationWriter(BoxWriter bx, BallWriter bl, int size)
{ boxWriter = bx;
ballWriter = bl;
JFrame f = new JFrame();
f.getContentPane().add(this);
f.setTitle("Topi kërcyes");
f.setSize(size, size);
f.setVisible(true);
}

public void paintComponent(Graphics g)
{ boxWriter.paint(g);
ballWriter.paint(g);
}
}


public class BounceController
{ private MovingBall ball;
private AnimationWriter writer;

public BounceController(MovingBall b, AnimationWriter w)
{ ball = b;
writer = w;
}

public void runAnimation()
{ while ( true )
{ delay(20);
ball.move();
writer.repaint();
}
}

private void delay(int milisecs)
{ try { Thread.sleep(milisecs); }
catch (InterruptedException e) { }
}
}


import java.awt.*;
public class TestBouncingBall
{ public static void main(String[] args)
{ int boxSize = 200;
int ballRadius = 6;
Box box = new Box(boxSize);
MovingBall ball = new MovingBall(boxSize / 3, boxSize / 5,
ballRadius, box);
BallWriter ballWriter = new BallWriter(ball, Color.red);
BoxWriter boxWriter = new BoxWriter(box);
AnimationWriter writer = new AnimationWriter(boxWriter,
ballWriter, boxSize);
new BounceController(ball, writer).runAnimation();
}
}
 
A

alexandre_paterson

from the name), bounces off of the walls. I only want the top and
bottom walls to bounce, but the code I am using does not work.

[snip]

Bellow follows a complete working example with model, view and
controller components.

Pay attention to the OO design implemented.

I did and I've got a few comments. I wouldn't have
commented if you hadn't say "Pay attention to the
OO design implemented"... But you said so so now I
want to nitpick a little ;)

For a start, why does the MovingBall have a Box?
I fail to see how this could possibly be good OO.

public void move()
{ xPos = xPos + xVelocity;
if ( container.inHorizontalContact(xPos) )
{ xVelocity = -xVelocity; }
yPos = yPos + yVelocity;
if ( container.inVerticalContact(yPos) )
{ yVelocity = -yVelocity; }
}

You're testing for the ball as a single point (the
center of the ball), without taking the radius into
account at all.

public void runAnimation()
{ while ( true )
{ delay(20);
ball.move();
writer.repaint();
}
}
From an OO point of view you shouldn't "ask" the ball
to move. What you should do is "tell" the ball that,
say, 20 ms elapsed and the ball should act accordingly:

ball.update() or, better, ball.update(20);

On a personal note I'll add that I'm a big fan of ADT
(Abstract Data Types), even for the simplest types.
The very book you point out does indeed recommend to
model using interfaces, which you ommited to do in
your example.

That's it, I'm done nitpicking ;)
 
A

alexandre_paterson

Pay attention to the OO design implemented.

If I may, I would also suggest a very good book to begin with: D.
Schmidt, Programming principles in Java -- architectures and
interfaces, which can be obtained for free at the following site:

http://www.cis.ksu.edu/santos/schmidt/ppj

<rant>

I took a quick look at that book. It's a piece of crap.

Forget it.

An advice I read once about choosing a good OO book is
to first look out for the definitions the book gives
for a few terms: type, class, inheritance, subtyping,
polymorphism, etc.

This book is just a plain joke... And written in very
poor english (I'm not a native english speaker, but
then I'm not written english book neither ;)

The definition of inheritance from that book:

"Inheritance is often used when someone has written
a basic class that contains clever methods, and other
people wish to use the clever methods in their own
classes without copying the code."

Even if we forget for a second that implementation
inheritance ain't the only form of inheritance (Obj-C
wouldn't exist if that was the case :) -- which is
important in the Java context -- that paragraph is
just plain laughable.

Another random paragraph:

"The classifying values into species prevents
inappropriate combinations of values..."

wtf!? Was there any editing done on that book?

And now onto subtyping: at this point I wasn't
expecting anything good

"The numeric primitive types related by subtyping:
int is a subtype of double, written int <= double"

Explaining subtyping in an OO Java book by taking
primitives seems weirder than weird.

A last one:

"An abstract class is an "incomplete program" and
"we might use a collection of abstract classes to
"write a complex, powerful, but incomplete program
"that another programmer finishes by write one or
"two concrete classes. A framework is such an
"incomplete program.

The author writes in a very poor english, makes up
new terms for things he doesn't know (his attempts
at redefining "static typing" are pathetic).

It looks like this book is a compilation of notes
that the author took while he was discovering both
Java and OO for the first time.

Overall it's a very poor book. If you've got an
hard-copy of it make yourself a favor: lit a fire.

I now realized that your MovingBall example comes
from that book and it's a poor example: you don't
ask a ball to move. You tell the ball what is
happenning and the ball reacts accordingly (and,
yup, I've worked in the video game industry on
games involving balls ;)

That "Box" has nothing to do in the MovingBall
class.

The author knows jack sh*t about OO.

A poor example and a very, very, bad Java book
that, is, IMHO, part of the problem...
</rant>
 
C

Chris Uppal

Noted...


I took a quick look at that book. It's a piece of crap.

I looked at it too and, based on what I saw, I don't agree at all. I admit
that I only skimmed the first half-dozen chapters, but what I saw seemed
promising.

Put it this way. I would hate to find myself obliged to give an introductory
course on programming, I would hate even more to be obliged to use Java for
that course, but if the fates did conspire against me, then I'd take the time
to read Schmidt's (proto-)book very carefully, because I suspect that it could
for a sound basis for such a course. (And would be /much/ easier than writing
my own material ;-)

An advice I read once about choosing a good OO book is
to first look out for the definitions the book gives
for a few terms: type, class, inheritance, subtyping,
polymorphism, etc.

I doubt if there is even one book anywhere which gives a definition/explanation
of any of those terms which is both usable and complete/correct. (Note that
even such an abstruse theorist as Luca Cardelli got his mathematical model of
OO
semantics wrong -- OO is more subtle than it looks, and the terminology
/benefits/ from not being tied down too much).

Also note that Schmidt's book is not intended to be an advanced thesis on OO,.
but an introduction to programming from scratch. As such it is impossible for
it to take the same sort of line as a textbook for more advanced programmers
would.

The definition of inheritance from that book:

"Inheritance is often used when someone has written
a basic class that contains clever methods, and other
people wish to use the clever methods in their own
classes without copying the code."

I think you are being unfair. I haven't noticed that passage myself, but I
cannot at all believe that he intends that as any kind of definition of
inheritance, and I don't really even believe that he intends it as his primary
/explanation/ of inheritance. For instance the first mention of the term that
I noticed is:

============
Inheritance lets us add minor customizations to a class. For example, our
design of a basic CASHIER might need some customization to fit perfectly into
the Italian restaurant, say, perhaps the cashier must speak Italian. We
customize the CASHIER class by writing the new method, speakItalian, and
inventing new name, say, ITALIAN CASHIER, for the customized class that
possesses all the methods of the CASHIER plus the new method. The situation we
have in mind is drawn like this in class-diagram style:

The ITALIAN CASHIER inherits (or ``extends'') the CASHIER class, because it has
all the methods of the original plus the additional customizations. The large
arrowhead in the diagram denotes this inheritance.

The attractive feature of inheritance is that the customizations are not
inserted into the original class but are attached as extensions. Thus, several
people can use the one and only original class but extend it in distinct ways.
(For example, the basic CASHIER class might be extended into an Italian
restaurant cashier and extended also into a bank cashier. For that matter, a
restaurant might be built to have one CASHIER object (who does not speak
Italian) and one ITALIAN CASHIER object (who does)).
============

Which is not at all how I would express it to an audience of semantically
sophisticated programmers, but (considering that this is chapter 1 of a first
introduction to any kind of programming at all) I don't think it's a bad
statement.

"The classifying values into species prevents
inappropriate combinations of values..."

wtf!? Was there any editing done on that book?

Are you an author ? If so do /you/ pay for copy-editing of preliminary
drafts ?

It looks like this book is a compilation of notes
that the author took while he was discovering both
Java and OO for the first time.

That is /way/ unfair. Indeed, I don't see how anyone could possibly come to
that conclusion. The book may not always approach things in quite the way I
would prefer (though there is more good than bad, IMO) but it has clearly been
carefully considered and (as it were) /designed/.

-- chris
 
F

Faton Berisha

I did and I've got a few comments. I wouldn't have
commented if you hadn't say "Pay attention to the
OO design implemented"... But you said so so now I
want to nitpick a little ;)

For a start, why does the MovingBall have a Box?
I fail to see how this could possibly be good OO.

Identifying the components of your model is a good starting point for
your design. Now, do you think it is a good modeling of a bouncing
ball if you expect it to "know" about all kinds of obstacles in its
way while bouncing? Or you need another component (for a start, and
perhaps later more of them), whose responsibility it is to pose
obstacles? Try to think of the application as if you intend (at some
point in in the future) to expand it to, say, a pinball game. Would
you intend to code all the knowledge about all the obstacle objects
(including the box) into a bouncing ball?
You're testing for the ball as a single point (the
center of the ball), without taking the radius into
account at all.

Yes, I am, the reason being simplicity (a general property of models,
I am afraid). You shouldn't have too much trouble to take into account
the radius. You might have some minor ones, though, with remedying the
fact that the ball will go beyond the barriers due to moving "a step
at a time".
From an OO point of view you shouldn't "ask" the ball

to move. What you should do is "tell" the ball that,
say, 20 ms elapsed and the ball should act accordingly:

ball.update() or, better, ball.update(20);

If understand you correctly, you mind the name chosen for the method
in the first case. In the second one, you would expect the ball to
measure the time (in millisecs). Do you consider this to be a
realistic property of a ball model?
On a personal note I'll add that I'm a big fan of ADT
(Abstract Data Types), even for the simplest types.
The very book you point out does indeed recommend to
model using interfaces, which you ommited [sic] to do in
your example.

I omitted lots of other things as well (commenting/documenting for
one).
That's it, I'm done nitpicking ;)

I only fail to see you demand an apology for those.

Faton Berisha
 
F

Faton Berisha

I took a quick look at that book. It's a piece of crap.

Forget it.

I have to say that I don't like at all your attitude here. Do not
forget that you began with few lines of code not working for you to
eventually end up, few days later, with such an evaluation of a book
and an advice for me to dismiss it.

In addition to all what Chris wrote in his replay, and for the sake of
the fact that I initiated a discussion about a book while the author
possibly not reading it, I would like to say that I used it for
teaching several courses of introductory level to programming.
Compared to several other textbooks I also used, I am impressed with
what it has to offer for the purpose. On top of it, its free.

Commenting your other remarks is not worth the effort. It goes without
saying that I like them even less.

Faton Berisha
 
L

Lew

Faton said:
If understand you correctly, ... you would expect the ball to
measure the time (in millisecs). Do you consider this to be a
realistic property of a ball model?

They said "tell" the ball that the time has elapsed, they did not say it was a
property of the "ball model". Clearly it was a property of another component
that knows how to measure time, not the ball. THerefore I'm guessing their
answer to your question is, "No. So what?"
 
L

Lew

Faton said:
I have to say that I don't like at all your attitude here.

How come when people on newsgroups don't agree with someone's points, they
blame it on "attitude"? There was no "attitude": in alexandre's post, just
opinion, supported by evidence (which isn't the same as "correct").
Do not forget that you began with few lines of code not working for you to

That was the OP, not alexandre.
eventually end up, few days later, with such an evaluation of a book
and an advice for me to dismiss it.

Sure. Why not?
In addition to all what Chris wrote in his replay, and for the sake of
the fact that I initiated a discussion about a book while the author
possibly not reading it, I would like to say that I used it for
teaching several courses of introductory level to programming.
Compared to several other textbooks I also used, I am impressed with
what it has to offer for the purpose. On top of it, its free.

Commenting your other remarks is not worth the effort. It goes without
saying that I like them even less.

You might not like them, but the passages that alexandre cited sure sounded
like "crap". Maybe the rest of the book was good, but the cited passages sure
weren't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,195
Latest member
tewan

Latest Threads

Top