MouseMotion Sensor Method Call - java

I have encountered a problem, for which no matter how long I study the API's of the class and superclasses, I can not figure out.
Suppose I wish to design a sort of a game where the mouse motion controls the motion of a block that is used to bounce a ball, which then destroys multi colored bricks.
How do you specifically make the block "listen" to the mouse?
The below code is what I have attempted to achieve the desired results.
/** Breakout Program*/
public class Breakout extends GraphicsProgram implements MouseMotionListener {
...
/** The Paddle Itself */
private GRect paddle = new GRect(0, HEIGHT-PADDLEBOTTOM_OFFSET, PADDLEWIDTH, PADDLEHEIGHT);
...
/** Run the Breakout program. */
public void run() {
paddle.setFillColor(Color.BLACK);
paddle.setFilled(true);
add(paddle);
paddle.addMouseListener(this);
...
}
/** Move the horizontal middle of the paddle to the x-coordinate of the mouse position -
* -but keep the paddle completely on the board. */
public void mouseMoved(MouseEvent e) {
GPoint p= new GPoint(e.getPoint());
double x = p.getX();
paddle.setLocation(x, HEIGHT-PADDLEBOTTOM_OFFSET);
}
}
Any clarification on why/what I am doing incorrectly would be helpful, thanks.

Your class is all set to be used as a mouse listener -- you just have to tell some component to send you MouseEvents. In order to do that, you need to implement MouseMotionListener, which you've already done, so you're most of the way there.
All that's left to do is call the method addMouseMotionListener(this) on your JFrame, JDialog, or whatever window you're using.
In the future, it may be worth setting up a separate class to serve as the listener, just to keep your code straight; the most common solution is called an anonymous inner class, which you may want to Google. But with your deadline approaching, what you've got will work fine.

After mouseMoved() updates the paddle location, you would typically invoke repaint() on the display component. Is there anything in GraphicsProgram apropos to this?

It looks like all of the classes belong to your application, so I am guessing you are working with AWT or Swing.
Try calling repaint() on the paddle.

Just an extra comment to "Etaoin", when you get time and if you are serious about doing OO well, do a search on "is-a" and "has-a" relationships in OO.
If the "is-a" relationship holds true (an apple "is-a" fruit) then its legitimate to use the implements on the class, otherwise if its a "has-a" relationship (a car "has-a" wheel, but a car "is-not-a" wheel) then implements is NOT appropriate - you need to use composition, in other words a member variable of the class.
In your code, can you say that the Breakout class "is-a" MouseMotionListener? The answer is "no", BTW! Breakout "is-a" game, or is an application, but the MOuseMotionListener is part of the implementation.
As "Etaoin" has said, you should implement the MouseMotionListener as an inner class, though I prefer private inner classes, not anonymous classes (to keep the constructor short and to the point, among other reasons).
When you "get" OO, its great and very powerful, but takes real effort to make the "paradigm shift" from procedural thinking.

Related

drawing simple shapes -> paint method and interface for JavaFX

I'm doing an assignment for school and I can't get my head around the logic I need to use to solve this. I hope some of you can point me in the right direction.
I have some classes to draw simple shapes:
Class Diagram 1
Extended Class Diagram
According to the assignment every deferred class under DrawingItem needs a paint() method to be able to paint the particular (Oval, Spline etc..) independent from GraphicsContext. For Oval, my guess is this method would be something like:
public void paint(Graphics g){
g.setColor(super.getColor());
g.drawOval(
(int) dw.getAnchor().getX(), (int) dw.getAnchor().getY(),
(int)this.width, (int)this.height
);`
}
Extended class diagram shows an interface IPaintable which I have created with a method for every shape. The JavaFX side (DrawingTool) implements this interface and all of its methods. These methods want the shape object as argument. I use these methods to draw the shapes in javaFX, again the oval example:
strokeOval(
oval.getHeight(), oval.getWidth(), oval.getAnchor().getX(), oval.getAnchor().getY()
);
The main questions I have are these:
Am I going in the right direction with the paint() methods in the shape subclasses and if so how do I call them from the JavaFX side?
How can I "implement" the paint(paintable:IPaintable) method in the Drawing and DrawingItem classes?
There are 2 design patterns easily identifiable in the class diagrams:
The IPaintable is supposed to be a wrapper(Facade) for the GUI drawing operations allowing you to use the classes in Class Diagram 1 independent from the GUI library used. You should only use the methods provided by IPaintable in the paint methods.
The classes in Class Diagram 1 are the command part of the Command Pattern; DrawingTool is the invoker/client and IPaintable is the receiver.
The DrawingTool class should contain code like this:
IPaintable paintable = new JavaFXPaintable(canvas.getGraphicsContext());
and use it like this, if the drawing needs to be redrawn:
drawing.paint(paintable);
Implementing the paint methods
Since a Oval can be drawn using IPaintable's methods, it should implement paint like this:
public void paint(IPaintable paintable) {
paintable.setColor(color);
paintable.paintOval(this);
}
Polygon would use the paintLine methods of the IPaintable passed to it's paint method for drawing itself, Drawing.paint would clear the IPaintable and draw all it's items ect.
In JavaFxPaintable the paintOval method would be implemented like this:
public void paintOval(Oval oval) {
Point anchor = oval.getAnchor();
graphics.strokeOval(anchor.getX(), anchor.getY(), oval.getWidth(), oval.getHeight());
}
You may need to modify this a bit, if anchor denotes the top-left instead of the the center.
Thanks fabian, pointing me in this direction realy helped a lot (as cleaning up my post for readability did too).
Now I have implemented these pointers and they seem to work. With the draw() method in Drawingtool I call the paint(IPaintable paintable) method in the Drawing class, which loops through the list of drawingitems in this class like so:
public void paint(IPaintable paintable){
for (DrawingItem test : drawingitems){
if (test instanceof Oval){
paintable.paintOval((Oval) paintable);
} else if (test instanceof Image){
paintable.paintImage((Image) paintable);
This should paint the shapes and seem to work. The last part is adding them to the canvas initialized in the DrawingTool class. I can't seem to figure out how to do this. I've tried to add them while going through the list with drawing items but this does not seem to work (or I'm handling it wrong).

Greenfoot issue with making ball go away from player

I'm trying to get a baby to kick a ball into the goal. So far I have managed to get the ball to go into the goal when the baby touches it by using move(-300); to go into the desired position, but that isn't technically getting the baby to hit the ball into the goal, because the baby can hit it from any direction and it will go into the goal.
I would just like to know the right code to use, I don't need to know the exact solution; I can learn the code and work it out myself but I have literally no idea where to start.
I struggle quite a lot with this particular type of language so my last resort is to ask online.
Thanks for any help and please comment for any additional information.
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class ball here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class ball extends Actor
{
/**
* Act - do whatever the ball wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
playerHitIt();
}
public void playerHitIt()
{
Actor player;
player=getOneObjectAtOffset(0,0,player.class);
if (player !=null)
{
setLocation(getX()-4, getY());
}
}
}
You could start by asking what a Ball is. It's probably not something that should act()* and have playerHitIt() at least unqualifed by which way it was hit. It probably has a field(s) representing position, and probably a velocity. If you consult the Actor API, you'll see the ball has the built-in capacity to do probably all you want because of extending Actor. This and other greenfoot documentation is the place to start. Surely the player is or is controlling an Actor object with its own direction as well, and kicking happens when they intersect.
just provide an empty implementation act(){}

Mouselistener in chess game

I am creating a chess game, and I have now populated my graphic chessboard with all the pieces, now I need to use Mouselistner to move the pieces around. Before implementing the graphic version I created a 2D console version, that took in "player moves", so I do have all those methods, but I need to now use Mouselistener, I read up about the methods, however, do I need to implement mouselistener in each class?
I have 1 abstract Piece class as well as 7 subclasses (incl Dummy piece), and a ChessBoard class that populates all the pieces and provides methods for moving (from the console version..) so where do I put the mouselistener? In the Jcomponent extension, JFrame or ChessBoard class that contains the methods to populate the chessboard and moves?
Sorry for such a simple answer, but all you need to do is add the mouselistener to your ChessBoard class. From there I'm assuming you can access the Piece subclass objects you've instantiated and call methods on them (i.e. mouseClicked, piece.pickUp()). If you code is arranged in such a way that you need to implement a mouse listener in many of your classes, consider the following:
addMouseListener( new MouseAdapter() {
#Override
public void mouseClicked( MouseEvent e ) {
// Do something
}
} );
http://docs.oracle.com/javase/7/docs/api/java/awt/event/MouseAdapter.html
Also, if it were me, I would transfer the methods for moving your Pieces to your Piece class, preferably at a higher level and then you don't have to rewrite the same code twice. Then in your game, whenever mouseReleased is invoked, call some method like attemptToMove(BoardPoint p) that will check if your piece's current position and the new position, p are within your piece's means of travel. A BoardPoint could be something you set up with x, y coordinates for your own board in an 8 X 8 style, like a 2-dimensional integer array.
It depends somewhat on how you have your pieces implemented. If they are GUI objects themselves, such as buttons or panels, then putting the mouseListener on them will allow the Swing framework to figure out which one has been clicked on. If the pieces all extend a Piece class, then you can put a handler in that as long as the logic it needs to execute (such as moving a piece around) can be made the same for all pieces.
If, on the other hand, you are drawing graphic images on the board in your code, so there is no GUI component for Swing to detect being clicked, then it makes more sense to implement the mouseListener on the board. In this case, your code is going to have to figure out which square was clicked on, and whether it has a piece on it; after that the handling will be much like the previous case.

Box2D/AndEngine - ContactListener for multiple object classes

I'm developing a little Android game in Java, using AndEngine for graphics and Box2D for physics - specifically, collision handling. I have some different types of objects with constructors in classes, like so:
MainActivity.java
Enemy.java
Npc.java
Door.java
I have a static PhysicsWorld in the main class, and I was setting up a ContactListener from the Enemy class, to define what happens when one of the enemies hits something. However, I tried to set up another ContactListener for the Door class, when I discovered that each PhysicsWorld has only one ContactListener.
Essentially, my question is this: what is the best way to get around this?
I'm aware I've probably explained this rather badly, so my apologies.
You can use your single ContactListener to manage the entire world; Contact.getFixtureA/B() will return the fixtures involved in the contact. You can utilize Fixture.getBody() to get the associated Body with each collision fixture; if, for example, your Door and Enemy objects are associated with the Bodys as user data, then you can use Body.getUserData() to retrieve that.

How to model game object rendering and behavior in modular way?

I'm making a Java shoot em up game for Android phones. I've got 20 odd enemies in the game that each have a few unique behaviors but certain behaviors are reused by most of them. I need to model bullets, explosions, asteroids etc. and other things that all act a bit like enemies too. My current design favors composition over inheritance and represents game objects a bit like this:
// Generic game object
class Entity
{
// Current position
Vector2d position;
// Regular frame updates behaviour
Behaviour updateBehaviour;
// Collision behaviour
Behaviour collideBehaviour;
// What the entity looks like
Image image;
// How to display the entity
Renderer renderer;
// If the entity is dead and should be deleted
int dead;
}
abstract class Renderer { abstract void draw(Canvas c); }
abstract class Behaviour { abstract void update(Entity e); }
To just draw whatever is stored as the entity image, you can attach a simple renderer e.g.
class SimpleRenderer extends Renderer
{
void draw(Canvas c)
{
// just draw the image
}
}
To make the entity fly about randomly each frame, just attach a behavior like this:
class RandomlyMoveBehaviour extends Behaviour
{
void update(Entity e)
{
// Add random direction vector to e.position
}
}
Or add more complex behaviour like waiting until the player is close before homing in:
class SleepAndHomeBehaviour extends Behaviour
{
Entity target;
boolean homing;
void init(Entity t) { target = t; }
void update(Entity e)
{
if (/* distance between t and e < 50 pixels */)
{
homing = true;
// move towards t...
}
else
{
homing = false;
}
}
}
I'm really happy with this design so far. It's nice and flexible in that you can e.g. modularize the latter class so you could supply the "sleep" behavior and the "awake" behavior so you could say something like new WaitUntilCloseBehaviour(player, 50/pixels/, new MoveRandomlyBehaviour(), new HomingBehaviour()). This makes it really easy to make new enemies.
The only part that's bothering me is how the behaviors and the renderers communicate. At the moment, Entity contains an Image object that a Behaviour could modify if it chose to do so. For example, one behavior could change the object between a sleep and awake image and the renderer would just draw the image. I'm not sure how this is going to scale though e.g.:
What about a turret-like enemy that faces a certain direction? I guess I could add a rotation field to Entity that Behavior and Renderer can both modify/read.
What about a tank where the body of the tank and the gun of the tank have separate directions? Now the renderer needs access to two rotations from somewhere and the two images to use. You don't really want to bloat the Entity class with this if there is only one tank.
What about an enemy that glows as his gun recharges? You'd really want to store the recharge time in the Behaviour object, but then the Renderer class cannot see it.
I'm having trouble thinking of ways to model the above so the renderers and the behaviors can be kept somewhat separate. The best approach I can think of is to have the behavior objects contain the extra state and the renderer object then the behavior objects call the renderers draw method and pass on the extra state (e.g. rotation) if they want to.
You could then e.g. have a tank-like Behaviour object that wants a tank-like Renderer where the latter asks for the two images and two rotations to draw with. If you wanted your tank to just be a plain image, you would just write a subclass Renderer that ignored the rotations.
Can anyone think of any alternatives? I really want simplicity. As it's a game, efficiency may be a concern as well if e.g. drawing a single 5x5 enemy image, when I have 50 enemies flying around at 60fps, involves many layers of function calls.
The composition design is a valid one, as it allow to mix-and-match the behaviour(s) and render.
In the game we're toying with, we've added a "databag" that contains basic informations (in your case the position and the dead/alive status), and variables datas that are set/unset by the behaviour and collision subsytem. The renderer can then use these data (or not if not needed). This work well, and allows for neat effect, such as setting a "target" for a given graphical effect.
A few problems :
if the Renderer ask for data that the behaviour did not set. In our case, the event is logged, and default values (defined in renderer) is used.
It's a little bit harder to check for the needed informations beforehand (ie what data should be in the databag for the Renderer A ? what data are set by the Behaviour B ?). We try to keep the doc up-to-date, but we're thinking of recording the set/get by the classes, and generate a doc page...
Currently we're using a HashMap for the databag, but this is on a PC, not an IPhone. I don't know if perfomance will be enough, in which case another struct could be better.
Also in our case, we've decided for a set of specialized renderer. For example, if the entity possess a non void shield data, the ShieldRenderer display the representation... In your case, the tank could possess two renderer linked to two (initialization-defined) datas :
Renderer renderer1 = new RotatedImage("Tank.png", "TankRotation");
Renderer enderer2 = new RotatedImage("Turret.png", "TurretRotation");
with "TankRotation" and "TurretRotation" set by the behaviour. and the renderer simply rotating the image before displaying it at the position.
image.rotate (entity.databag.getData(variable));
Hope this help
Regards
Guillaume
The design you're going with looks good to me. This chapter on components may help you.

Categories

Resources