| """
Shapes.cobra
for http://onestepback.org/articles/poly/
whose purpose is to "see this small problem written in several different OO languages"
http://cobra-language.com/
by CsabaU@Hotmail.com & Charles Esterbrook
"""
class Shape is abstract
"""
The root class for all 2D shapes which are anchored to an (x, y) point in
space, but can be moved.
"""
cue init(x as number, y as number)
base.init
_x, _y = x, y
pro x from var as number
pro y from var as number
def moveTo(newX as number, newY as number)
""" Move to the given absolute position. """
_x, _y = newX, newY
def relativeMove(deltaX as number, deltaY as number)
""" Move position by the given delta. """
_x += deltaX
_y += deltaY
def draw
"""
Subclasses should override, invoke base and print the rest of
their properties.
"""
print 'Draw [.typeOf.name] at ([_x], [_y]), ' stop
class Rectangle inherits Shape
cue init(x as number, y as number, width as number, height as number)
base.init(x, y)
_width, _height = width, height
pro width from var as number
pro height from var as number
def draw
base.draw
print 'height [_height], width [_width]'
class Circle inherits Shape
cue init(x as number, y as number, radius as number)
base.init(x, y)
_radius = radius
pro radius from var as number
def draw
base.draw
print 'radius [_radius]'
class Program
def main
shapes = [Rectangle(10, 20, 5, 6), Circle(15, 25, 8)]
# using shapes polymorphically
for shape in shapes
shape.draw
shape.relativeMove(100, 100)
shape.draw
# access rectangle specific features
rect = Rectangle(0, 0, 15, 15)
rect.width = 30
rect.draw
|