Regular Polygons

A polygon is a closed shape formed by straight lines. A regular polygon has sides of equal length and angles of equal size. Convex regular polygons are the common shapes we associate with 3, 4, 5, or more sides, such as the equilateral triangle, square, pentagon, hexagon, and so on.
To draw a regular polygon with n sides, the turtle takes equal steps forward and turns at a consistent angle after each step. Since a full rotation is 360°, the turtle must turn 360 / n degrees after every step to complete the polygon.
For example, the Logo code to draw a hexagon is:
pd repeat 6 [ fd 1 rt 360 / 6 ]
Using this idea, the procedure for drawing a polygon with n sides and radius r may be given by:
to polygon :n :r
; Generate regular n-gon with radius r
make "s 2 * :r * sin ( 180 / :n ) ; Side length
rt 90 fd :r rt 90 + 180 / :n ; Set initial position
pd repeat :n [ fd :s rt 360 / :n ] pu line ; Draw faces
pcoff setdc random 1000 random 1000 random 1000 settr 800 ; Set random face color
face pd repeat :n [ fd :s rt 360 / :n ] pu line ; Draw faces
rt 90 - 180 / :n fd :r rt 90 ; Reset final position
end
- dpietrobon's blog
- Login or register to post comments
- 42 reads