/* mobile.java */ /* A Mobile can be constructed from strings (cords), struts, and weights. The simplest mobile is just a weight hanging on a cord. We build bigger mobiles by replacing the weight with a strut that has another mobile hanging on both its left end and its right end. Design the data that represents mobiles. -- Draw the mobile on the given Canvas. -- Compute the height of the mobile. -- Compute the total weight of the mobile -- determine whether the mobile is balanced - i.e. every strut is balanced (ask for a physics hint, if you need it) */ import draw.*; import geometry.*; import colors.*; /* +--------+ | Mobile |<----------------+ +--------+ | +--------+ | | | / \ | --- | | | --------------------- | | | | +--------------+ +--------------+ | | Item | | Support | | +--------------+ +--------------+ | | Posn origin | | Posn origin | | | IColor color | | int offset | | +--------------+ | int length | | | Mobile left |-+ | | Mobile right |-+ | +--------------+ | | | | +--+ */ // to represent a mobile interface Mobile { boolean draw(Canvas c); } // to represent an item hanging at the end of a mobile class Item implements Mobile { Posn origin; IColor color; Item(Posn origin, IColor color) { this.origin = origin; this.color = color; } boolean draw(Canvas c){ return c.drawDisk(this.origin, 20, this.color); } } // to represent a part of support structure for a mobile class Support implements Mobile { Posn origin; int leftSide; int rightSide; Mobile left; Mobile right; Support(Posn origin, int leftSide, int rightSide, Mobile left, Mobile right) { this.origin = origin; this.leftSide = leftSide; this.rightSide = rightSide; this.left = left; this.right = right; } boolean draw(Canvas c){ return // draw the left support c.drawLine(this.origin, new Posn(this.origin.x - this.leftSide, this.origin.y), new Black()) && // draw the left string c.drawLine(new Posn(this.origin.x - this.leftSide, this.origin.y), new Posn(this.origin.x - this.leftSide, this.origin.y + 30), new Yellow()) && // draw the left submobile this.left.draw(c) && // draw the right support c.drawLine(this.origin, new Posn(this.origin.x + this.rightSide, this.origin.y), new Black()) && // draw the right string c.drawLine(new Posn(this.origin.x + this.rightSide, this.origin.y), new Posn(this.origin.x + this.rightSide, this.origin.y + 30), new Yellow()) && // draw the right submobile this.right.draw(c); } } class Examples { Examples(){} Mobile i1 = new Item(new Posn(70, 120), new Blue()); Mobile i2 = new Item(new Posn(120, 120), new Red()); Mobile i3 = new Item(new Posn(180, 90), new Green()); Mobile i4 = new Item(new Posn(20, 90), new Green()); Mobile s1 = new Support(new Posn(90, 90), 20, 30, this.i1, this.i2); Mobile s2 = new Support(new Posn(140, 60), 50, 40, this.s1, this.i3); Mobile s3 = new Support(new Posn(100, 30), 80, 40, this.i4, this.s2); Canvas c = new Canvas(300, 200); boolean makeDrawing = this.c.show() && this.s3.draw(this.c); }