2019年3月28日木曜日

開発環境

Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART 3(BLAZING YOUR OWN TRAIL)、9(BUILDING OBJECTS WITH CLASSES)、EXERCISE 9-1(CREATING BALLS OF DIFFERENT SIZES)の解答を求めてみる。

コード

Python 3

class Ball:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.x_velocity = random(-2, 2)
        self.y_velocity = random(-2, 2)
        self.color = color(*[random(255) for _ in range(3)])
        self.size = random(5, 50)

    def update(self):
        self.x += self.x_velocity
        self.y += self.y_velocity
        if self.x > width or self.x < 0:
            self.x_velocity *= -1
        if self.y > height or self.y < 0:
            self.y_velocity *= -1
        fill(self.color)
        ellipse(self.x, self.y, self.size, self.size)


balls = []


def setup():
    global balls
    size(960, 515)
    for i in range(20):
        balls.append(Ball(random(width), random(height)))


def draw():
    global balls
    background(0)
    for ball in balls:
        ball.update()

0 コメント:

コメントを投稿

関連コンテンツ