2019年1月27日日曜日

数学 - Python - HITCHIN' UP YOUR PYTHON WAGON - DRAWING POLYGONS WITH THE TURTLE MODULE - POLYGON FUNCTIONS(internal angle, external angle)

Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART Ⅰ(HITCHIN' UP YOUR PYTHON WAGON)、1(DRAWING POLYGONS WITH THE TURTLE MODULE)、EXERCISE1-4(POLYGON FUNCTIONS)の解答を求めてみる。

コード

Python 3

```#!/usr/bin/env python3
import time
import turtle
# 保存用
import io
from PIL import Image

turtle.shape('turtle')
turtle.speed(0)

def polygon(sides=3, side_length=100):
triangle_count = sides - 2
internal_angle = 180 * triangle_count / sides
external_angle = 180 - internal_angle
for _ in range(sides):
turtle.forward(side_length)
turtle.right(external_angle)

colors = ['red', 'green', 'blue', 'orange', 'brown']
color_len = len(colors)
for i, color in enumerate(colors):
sides = color_len - i + 2
turtle.pencolor(color)
side_length = 20 * sides
for _ in range(3):
polygon(sides, side_length)
turtle.right(120)

# 保存
ps = turtle.getscreen().getcanvas().postscript()
with io.BytesIO() as buffer:
buffer.write(ps.encode('ascii'))
im = Image.open(buffer)
im.save(f'sample4.png')
```

```\$ python3 sample4.py
\$
```