i have a program i have to do where i have to take individual shape objects and combine them to create a final car shape. we are given premade shapes such as front tire, back tire, body, windshield, and roof and supposed to combine them into one car shape. the code already given to me is the following:
CompositeShape shape = new CompositeShape();
final double WIDTH = 60;
Rectangle2D.Double body
= new Rectangle2D.Double(0, WIDTH / 6,
WIDTH, WIDTH / 6);
Ellipse2D.Double frontTire
= new Ellipse2D.Double(WIDTH / 6, WIDTH / 3,
WIDTH / 6, WIDTH / 6);
Ellipse2D.Double rearTire
= new Ellipse2D.Double(WIDTH * 2 / 3, WIDTH / 3,
WIDTH / 6, WIDTH / 6);
shape.add(body);
shape.add(frontTire);
shape.add(rearTire);
now, i have to create the compositeShape class which is where the combining takes place, but im not sure what to do in the add(Shape) method. we were also told that we were supposed to use a pathiterator method, but we werent really taught about pathiterator or what we are supposed to do with it. Im not asking for someone to tell me what exactly to code, just some helpful starter points.
the first thing that came to my mind was something like this:
public class CompositeShape implements Shape {
Graphics2D g2;
public void add(Shape shape){
g2.draw(shape);
}
but it doesnt work because i cant instantiate a new graphics object and i get a null pointer exception. after that, im pretty much stumped as to what to do. any help would be greatly appreciated. thanks!
Probably, instead of drawing the Shape inside the add() method, you're just supposed to store the added Shape for drawing later. You could do that by giving CompositeShape some kind of collection to hold Shapes that are added, and that's all I'd put in the add() method. Beyond that, it would depend what other behavior CompositeShape is supposed to have. If you have to be able to draw a CompositeShape, then you'll probably be given an Graphics object to draw on. You won't have to create your own. Then drawing a CompositeShape would be drawing all of the Shapes that it contains.
java.awt.geom.Area can combine multiple shapes with methods add, subtract, exclusiveOr, and intersect. It's a ready-made class for CompositeShape.
It seems extremely weird that you've been asked to recreate it as "CompositeShape", because Area already does what you want.
The solution could be as simple as
class CompositeShape extends java.awt.geom.Area {}
and you're done.
Or, the fact that you've been given a hint about PathIterator, it might be that you're being encouraged to manage the added shapes in a list manually, then implement all the methods of the Shape interface in terms of iterating over the other shapes.
E.g., getBounds() needs to return the rectangular bounds of the shape, so get the rectangular bounds of the first, then use Rectangle.union to join it with the bounds of the others.
And for getPathIterator(), return a new inner class implementing PathIterator that will iterate over all the shapes in your collection, and iterate the path segments of each of their getPathIterator methods, returning each path segment.
It all sounds unnecessary in practice, since the needed class already exists. I think you should get clarification on what is wanted. Good luck.
To clarify what I said about the implementation of getPathIterator, return something like this. I didn't test this. This assumes your list is called shapes.
public PathIterator getPathIterator(final AffineTransform at, final double flatness) {
return new PathIterator() {
private PathIterator currentPathIterator;
private Iterator<Shape> shapeIterator = shapes.iterator();
{ nextShape(); }
private void nextShape() {
if (shapeIterator.hasNext()) {
currentPathIterator = shapeIterator.next().getPathIterator(at, flatness);
} else {
currentPathIterator = null;
}
}
public int getWindingRule() {
return WIND_NON_ZERO;
}
public boolean isDone() {
for (;;) {
if (currentPathIterator == null) return true;
if (!currentPathIterator.isDone()) return false;
nextShape();
}
}
public void next() {
currentPathIterator.next();
}
public int currentSegment(float[] coords) {
return currentPathIterator.currentSegment(coords);
}
public int currentSegment(double[] coords) {
return currentPathIterator.currentSegment(coords);
}
};
}
Related
I'm implementing Bomberman clone in Java. Its map has a scale of 17*13 tiles. Now I'm storing the game map in the ArrayList. Obviously it's unproductive since game mechanics provides only discrete moving (right, left, up, down). Bombs can have only discrete position too. So with the ArrayList I have to look for four adjacent tiles through whole list while processing collisions or fire generating. So what are the best practices for storing such maps in Java.
There are lots of ways you could model this. Here's a suggestion that I've used often for similar problems:
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
class Position {
private final int x;
private final int y;
public static Stream<Position> getAllPositions();
public Stream<Position> getNeighbours();
public Optional<Position> positionInDirection(Direction direction);
// make sure you implement equals and hashCode
}
class Map {
private final Map<Position, Tile> tiles = new HashMap<>();
public Map() {
Position.getAllPositions().forEach(pos -> tiles.put(pos, new Tile());
}
public Tile getTile(Position position) {
return tiles.get(position);
}
}
This provides lots of useful encapsulation. For example the Position class is the only one that needs to know about the size of the map and edges.
Now to see if an adjacent position has a bomb (for example), you would use:
position.getNeighbours().map(map::getTile).anyMatch(Tile::hasBomb);
I want to extend the JavaFX class Line, cause i want the startpoint and endingpoint to be a circle or arrow or sth. like that. In addition to that, i want to tag the line in the future.
The problem is how to overwrite the paint method? What method is responsible for drawing the line and how do I have to implement my wishes?
Until now, i got that, but if I instaciate a Line it doesn´t change the appearance:
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
public class LabeledLine extends Line {
private Circle startCircle;
private Circle endCircle;
public LabeledLine(){
super();
startCircle = new Circle(getStartX(), getStartY(), 10);
endCircle = new Circle(getEndX(), getEndY(), 10);
startCircle.setFill(getFill());
endCircle.setFill(getFill());
}
public LabeledLine(double startX, double startY, double endX, double endY){
super(startX, startY, endX, endY);
startCircle = new Circle(getStartX(), getStartY(), 10);
endCircle = new Circle(getEndX(), getEndY(), 10);
startCircle.setFill(getFill());
endCircle.setFill(getFill());
}
}
To the extent of my knowledge you shouldn't extend base Shapes directly. Rather extend Region and use a composed Line as a child node.
https://github.com/aalmiray/jsilhouette uses a similar approach. Properties are set on types that "look like" Shapes but aren't.
Note that the implementation you provided won't work if, e.g. you were to do
LabeledLine l = new LabeledLine() ;
l.setStartX(100);
It is actually quite difficult to fix this using a strategy of subclassing Line.
At any rate, Shapes are rendered by delegating to a private native peer class, which (as I understand it) allows them to be rendered highly efficiently by a hardware graphics pipeline in many cases. So there is no accessible "paint" method for you to override here.
Instead, subclass Group and let your subclass wrap a line (basically, this is "favor composition over inheritance" from Effective Java by Joshua Bloch):
public class LabeledLine extends Group {
public LabeledLine(Line line) {
Circle startCircle = new Circle(10);
startCircle.centerXProperty().bind(line.startXProperty());
startCircle.centerYProperty().bind(line.startYProperty());
startCircle.fillProperty().bind(line.fillProperty());
Circle endCircle = new Circle(10);
endCircle.centerXProperty().bind(line.endXProperty());
endCircle.centerYProperty().bind(line.endYProperty());
endCircle.fillProperty().bind(line.fillProperty());
getChildren().addAll(line, startCircle, endCircle);
}
}
You would then use this as:
Line line = new Line();
Pane somePane = new Pane();
somePane.getChildren().add(new LabeledLine(line));
Note also that the implementation above actually adds no state or behavior to Group, so you could completely refactor it as a method:
public Group labelLine(Line line) {
Circle startCircle = new Circle(10);
startCircle.centerXProperty().bind(line.startXProperty());
startCircle.centerYProperty().bind(line.startYProperty());
startCircle.fillProperty().bind(line.fillProperty());
Circle endCircle = new Circle(10);
endCircle.centerXProperty().bind(line.endXProperty());
endCircle.centerYProperty().bind(line.endYProperty());
endCircle.fillProperty().bind(line.fillProperty());
return new Group(line, startCircle, endCircle);
}
and then
Pane somePane = new Pane();
Line line = new Line();
somePane.getChildren().add(labelLine(line));
I tried this here, and it worked well:
public Group labelLine(Line line) {
Circle startCircle = new Circle(line.getStartX(), line.getStartY(), 10);
Circle endCircle = new Circle(line.getEndX(), line.getEndY(), 10);
return new Group(line, startCircle, endCircle);
}
Still wonderin why your implementation won't work, because it looks nice.
In the following for each loop, I get a "bird cannot be resolved" error at lines marked !. I have setup an interface Bird implemented by an abstract class BirdType of which Cardinal, Hummingbird, Bluebird, and Vulture are children. getColor() and getPosition() methods are defined in the abstract class while fly() is unique to each of the child classes. This client code was actually provided by my professor to test the interface/inheritance relations I have setup. Note I have tested the interface, abstract class and child classes and they all seem to work. I think the issue is with the for-each loop but I can provide code for the other classes if needs be. Any advice?
import java.awt.*;
public class Aviary {
public static final int SIZE = 20;
public static final int PIXELS = 10;
public static void main(String[] args){
//create drawing panel
DrawingPanel panel = new DrawingPanel(SIZE*PIXELS,SIZE*PIXELS);
//create pen
Graphics g = panel.getGraphics();
//create some birds
Bird[] birds = {new Cardinal(7,4), new Cardinal(3,8),
new Hummingbird(2,9), new Hummingbird(16,11),
new Bluebird(4,15), new Bluebird(8,1),
new Vulture(3,2), new Vulture(18,14)};
while (true){
//clear screen
g.setColor(Color.WHITE);
g.fillRect(0, 0, SIZE*PIXELS, SIZE*PIXELS);
//tell birds to fly and redraw birds
for (Bird bird : birds)
bird.fly();
! g.setColor(bird.getColor());
! Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
}
}
}
You need to wrap the body you want to be executed in the for loop in braces
for (Bird bird : birds) {
bird.fly();
g.setColor(bird.getColor());
Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
}
Otherwise, the body of the for loop is the next statement following the ). So it is equivalent to
for (Bird bird : birds)
bird.fly();
// bird is not in scope anymore
g.setColor(bird.getColor());
Point pos = bird.getPosition();
g.fillOval((int)pos.getX()*PIXELS, (int)pos.getY()*PIXELS,
PIXELS, PIXELS);
panel.sleep(500);
As Darien has said in the comments, indentation is not part of the Java language, it has no bearing on the syntax. But you should use it to make your code easier to read, as expressed in the Java code style conventions.
Hey I am new java so forgive me if what I am about to ask is obvious, but I will try to explain as best as I can.
Its just a project that has been set for university so its not in a serious manner.
I have a class called MarsRoom which holds the attributes say for all the dimensions of the room like the totalheight and width of the walls in order to calculate the heat loss that the room will suffer in order to adjust the amount of solar energy that is needed to keep the room at the room temperature set.
The problem I am having is what is better practice or solution, to pass the attributes of the size of the room in a constructor(but this could get quite long in size, as the ones below are not only the ones that I may need) or create a whole different class specifically for that room like ROOM TYPE U? and set the attributes in there.
As it stands I can create a whole new room just by instantiating the room with the new values, but its going to get a little long, whereas I would rather not create a whole new class for a different room which may only differ from another room by a few meters on one of the walls!.
So what I am really trying to get at it, is is it ok to pass that many attributes to the constructor on instantiation?
//the instantiation in the runnable
MarsRoom room1 = new MarsRoom("RoomU", 40, 40, 20, 20, 8, 2, 4);
//the constructor in the MarsRoom class
public MarsRoom(String roomname, int windowsH, int windowsW, int wallsH, int wallsW, int windowC, int heaters, int lights){
name = roomname;
TotalWindowHeight = windowsH;
TotalWindowWidth = windowsW;
TotalWallHeight = wallsH;
TotalWallWidth = wallsW;
windowCeiling = windowC;
numheaters = heaters;
numlights = lights;
roomheaters = new Heaters[numheaters];
}
I'd say that you should be adding factory methods here.
Basically, keep your constructor, but add methods like
static Room createLaundryRoom(laundryRoomParameters) {
return new Room(...laundry room parameters plus defaults
common to all laundry rooms...);
}
One of the great benefits object oriented programming is the possibility of not repeating yourself in code. Hence objects, which define data (members) and functionality (methods), and no requirement to create instances of these "prototypes" with hard values until run-time. To create a new class for each room when it
may only differ from another room by a few meters on one of the walls
would be to deny OOP (and Java) by gross repetition. I'd stick with the constructors, and if similar kinds of rooms end up emerging, try one of the static factory methods suggested, or break up common functionality using inheritanceOracle.
Create a map with the keys being
Map<String, Integer> map = new HashMap();
map.put("TotalWindowHeight", new Integer(10));
map.put("TotalWindowWidth", new Integer(5));
...
map.put("NumberOfHeaters", new Integer(3));
MarsRoom room1 = new MarsRoom("RoomU", map);
Constructor will be like:
public MarsRoom(String roomname, HashMap<String, Integer> params) {
name = roomname;
TotalWindowHeight = map.get("TotalWindowHeight").intValue();
TotalWindowWidth = map.get("TotalWindowWidth").intValue;
...
roomheaters = new Heaters[map.get("NumberOfHeaters").intValue()];
}
this is not good OO however, but it seems like you are looking for something quick. If you want good OO you need to create an object for Window and in it you have hieght and width, another for ceiling, and you should not have number of something as a field, you should have an array to store the heater objects, and so and so forth, but this is quick and meets your requirement.
While technically legal, constructors with very long argument lists may be inconvenient to use. It also depends on whether you this the list may grow in the future or in subclasses.
If you have many parameters, but they have defaults and sometimes only a few need to be changed, you may find the Builder pattern useful. The idea is to replace constructor arguments with function calls, and allow them to be chained, for example:
public MarsRoom() {
//empty or just basic stuff set here
}
public MarsRoom setTotalWindowHeight(int TotalWindowHeight) {
this.TotalWindowHeight = TotalWindowHeight;
return this;
}
public MarsRoom setTotalWindowWidth(int TotalWindowWidth) {
this.TotalWindowWidth = TotalWindowWidth;
return this;
}
...
then, you can call:
MarsRoom room1 = new MarsRoom()
.setTotalWindowHeight(20)
.setTotalWindowWidth(40);
Of course, if you wanted to set all parameters this way, it's longer (thou maybe more readable) than the single constructor. But if you only set 2 parameters out of 10, it will usually be more convenient.
You don't show what the fields of MarsRoom are, but for each feature, I would have a Collection of sub-objects. A MarsRoom has-a List of Windows. A MarsRoom has-a List of Walls. etc... Then have setters and getters for each and methods to add new instances of these features.
Since this is for school, I'm only including a little bit of pseudo code.
public class MarsWindow {
int height;
int length;
// Setters & Getters
// standard getters & setters go here
int getArea() {
return this.height * this.width;
}
}
public class MarsRoom {
List<MarsWindow> windows;
List<MarsWall> walls;
List<MarsLight> lights;
List<MarsHeater> heaters;
public List<MarsWindow> addWindow(MarsWindow window) {
// Add a window to the "windows" list here
}
public List<MarsWall> addWall(MarsWall wall) {
// Add a wall to the "walls" list here
}
// Do this for the other fields
int getTotalWindowArea() {
int area = 0;
// Iterate over all windows
for(MarsWindow window : windows) {
area += window.getArea();
}
return area;
}
// Add other calculation methods here
}
If what you're trying to do is simply not duplicate the parameters you're passing the constructor, you can simply put them in a separate static method, like so:
public static MarsRoom newRoomU() {
return new MarsRoom("RoomU", 40, 40, 20, 20, 8, 2, 4);
}
You could also use some polymorphism or have different types of rooms or something similar to this and then have a superclass with the common values that all rooms will have.
You can also have more than one constructor and have different ones for values you wish to set depending on the room type etc.
Its always better to work with objects rather than primitives, you could use factory to create objects.
//the constructor in the MarsRoom class
public MarsRoom(String roomname, WindowDimension windowDimension, WallsDimensions wallDimension, RoomAmbience ambience){
}
public class WindowDimension{
private int height; //int windowsH
private int width; //int windowsW
private int circumference; //assumed windowC is circumference
}
public class WallsDimension{
private int height; //int wallsH
private int width; //int wallsW
}
public class RoomAmbience{
private int heaters;
private int lights;
}
I have a program that allows you to move various Shapes about. I want to be able to return a boolean that returns true if two shapes are intersecting. This is what I have thus far:
public boolean overlaps(MyShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
PathIterator pi = path.getPathIterator(null);
return path.intersects(pi,otherShapeBoundary);
}
...where path is a GeneralPath (these are all straight from the API, except MyShape).
One thing I'm unsure on is how PathIterator works, which might be the problem. I've also tried this, but I was getting a similar error:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
The error is that this method almost always returns false. I'm unsure when/why it is returning true, but it is very infrequent.
What I tried second was actually the correct answer. Just to be clear:
public boolean overlaps(OverlappableSceneShape s){
Rectangle2D.Double otherShapeBoundary
= new Rectangle2D.Double(s.getX(), s.getY(), s.getWidth(), s.getHeight());
return path.intersects(otherShapeBoundary);
}
is the best method of determining intersection.