2018年2月1日木曜日

Python - Random Fun and Games: Go Ahead, Take a Chance!(RANDOM SIDES AND THICKNESS, random module, randrange method, choice method)

Teach Your Kids to Code: A Parent-Friendly Guide to Python Programming (Bryson Payne(著)、No Starch Press)のChapter 6.(Random Fun and Games: Go Ahead, Take a Chance!)、PROGRAMMING CHALLENGES、#1: RANDOM SIDES AND THICKNESSを取り組んでみる。

#1: RANDOM SIDES AND THICKNESS

コード(Emacs)

Python 3

```#!/usr/bin/env python3
import random
import turtle

t = turtle.Pen()
t.speed(0)
turtle.bgcolor('black')
colors = ['red', 'yellow', 'blue', 'green',
'orange', 'purple', 'white', 'gray']

for n in range(50):
t.pencolor(random.choice(colors))
size = random.randrange(10, 41)
sides = random.randrange(2, 9)
thick = random.randrange(1, 7)
t.width(thick)
x = random.randrange(0, turtle.window_width() // 2)
y = random.randrange(0, turtle.window_height() // 2)
for x0, y0 in [(x, y), (-x, y), (-x, -y), (x, -y)]:
t.penup()
t.setpos(x0, y0)
t.pendown()
for m in range(size):
t.forward(m * 2)
t.left(360 / sides + 1)

print('done')
input()
```

```\$ ./sample1.py
done
q
\$ ./sample1.py
done
close
\$
```