Category talk:Wren-polygon: Difference between revisions

Content added Content deleted
(→‎Source code: Added 3 new methods including one to facilitate the creation of regular polygons.)
(→‎Source code: Added convenience classes: Rectangle and Square.)
Line 4: Line 4:


import "graphics" for Canvas, Color
import "graphics" for Canvas, Color
import "math" for Point


/* Polygon represents a polygon in 2 dimensional space. */
/* Polygon represents a polygon in 2 dimensional space. */
Line 154: Line 155:
// Returns the string representation of the current instance.
// Returns the string representation of the current instance.
toString { _vertices.toString }
toString { _vertices.toString }
}
} </lang>

/* Rectangle represents a rectangle in 2 dimensional space. */
class Rectangle is Polygon {
// Constructs a new Rectangle object with top left corner (x, y), width w and height h.
construct new (x, y, w, h) {
if (!((x is Num) && (y is Num) && (w is Num) && (h is Num))) {
Fiber.abort("All arguments must be numbers.")
}
super([[x, y], [x + w, y], [x + w, y + h] , [x, y + h]])
_x = x
_y = y
_w = w
_h = h
}

// Constructs a new Rectangle object with center (cx, cy), width w and height h.
static fromCenter(cx, cy, w, h) { new(cx - w/2, cy - h/2, w, h) }

// Properties
x { _x }
y { _y }
cx { _x + _w/2 }
cy { _y + _h/2 }
width { _w }
height { _h }

topLeft { Point.new(_x, _y) }
center { Point.new(cx, cy) }
perimeter { 2 * (_w + _h) }
area { _w * _h }
}

/* Square represents a square in 2 dimensional space. */
class Square is Rectangle {
// Constructs a new Square object with top left corner (x, y) and side s.
construct new (x, y, s) {
super(x, y, s, s)
_s = s
}

// Constructs a new Rectangle object with center (cx, cy) and side s.
static fromCenter(cx, cy, s) { new(cx - s/2, cy - s/2, s) }

// Properties.
side { _s }
}</lang>