| 1 | """ |
|---|
| 2 | Shapes.cobra |
|---|
| 3 | |
|---|
| 4 | for http://onestepback.org/articles/poly/ |
|---|
| 5 | whose purpose is to "see this small problem written in several different OO languages" |
|---|
| 6 | |
|---|
| 7 | http://cobra-language.com/ |
|---|
| 8 | |
|---|
| 9 | by CsabaU@Hotmail.com & Charles Esterbrook |
|---|
| 10 | """ |
|---|
| 11 | |
|---|
| 12 | |
|---|
| 13 | class Shape is abstract |
|---|
| 14 | """ |
|---|
| 15 | The root class for all 2D shapes which are anchored to an (x, y) point in |
|---|
| 16 | space, but can be moved. |
|---|
| 17 | """ |
|---|
| 18 | |
|---|
| 19 | cue init(x as number, y as number) |
|---|
| 20 | base.init |
|---|
| 21 | _x, _y = x, y |
|---|
| 22 | |
|---|
| 23 | pro x from var as number |
|---|
| 24 | |
|---|
| 25 | pro y from var as number |
|---|
| 26 | |
|---|
| 27 | def moveTo(newX as number, newY as number) |
|---|
| 28 | """ Move to the given absolute position. """ |
|---|
| 29 | _x, _y = newX, newY |
|---|
| 30 | |
|---|
| 31 | def relativeMove(deltaX as number, deltaY as number) |
|---|
| 32 | """ Move position by the given delta. """ |
|---|
| 33 | _x += deltaX |
|---|
| 34 | _y += deltaY |
|---|
| 35 | |
|---|
| 36 | def draw |
|---|
| 37 | """ |
|---|
| 38 | Subclasses should override, invoke base and print the rest of |
|---|
| 39 | their properties. |
|---|
| 40 | """ |
|---|
| 41 | print 'Draw [.typeOf.name] at ([_x], [_y]), ' stop |
|---|
| 42 | |
|---|
| 43 | |
|---|
| 44 | class Rectangle inherits Shape |
|---|
| 45 | |
|---|
| 46 | cue init(x as number, y as number, width as number, height as number) |
|---|
| 47 | base.init(x, y) |
|---|
| 48 | _width, _height = width, height |
|---|
| 49 | |
|---|
| 50 | pro width from var as number |
|---|
| 51 | |
|---|
| 52 | pro height from var as number |
|---|
| 53 | |
|---|
| 54 | def draw |
|---|
| 55 | base.draw |
|---|
| 56 | print 'height [_height], width [_width]' |
|---|
| 57 | |
|---|
| 58 | |
|---|
| 59 | class Circle inherits Shape |
|---|
| 60 | |
|---|
| 61 | cue init(x as number, y as number, radius as number) |
|---|
| 62 | base.init(x, y) |
|---|
| 63 | _radius = radius |
|---|
| 64 | |
|---|
| 65 | pro radius from var as number |
|---|
| 66 | |
|---|
| 67 | def draw |
|---|
| 68 | base.draw |
|---|
| 69 | print 'radius [_radius]' |
|---|
| 70 | |
|---|
| 71 | |
|---|
| 72 | class Program |
|---|
| 73 | |
|---|
| 74 | def main |
|---|
| 75 | shapes = [Rectangle(10, 20, 5, 6), Circle(15, 25, 8)] |
|---|
| 76 | |
|---|
| 77 | # using shapes polymorphically |
|---|
| 78 | for shape in shapes |
|---|
| 79 | shape.draw |
|---|
| 80 | shape.relativeMove(100, 100) |
|---|
| 81 | shape.draw |
|---|
| 82 | |
|---|
| 83 | # access rectangle specific features |
|---|
| 84 | rect = Rectangle(0, 0, 15, 15) |
|---|
| 85 | rect.width = 30 |
|---|
| 86 | rect.draw |
|---|