2019年4月5日金曜日

開発環境

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-3(CHANGING SHEEP SIZE)の解答を求めてみる。

コード

Python 3

import random
import time
patch_size = 10
sheep_list = []
grass_list = []
rows_of_grass = None


class Sheep:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.energy = 20
        self.size = self.energy * 0.5
        self.age = 0

    def update(self):
        self.age += 0.2
        if self.age > 12:
            sheep_list.remove(self)
            return
        self.size = self.energy * 0.5
        move = 10
        self.x += random.randrange(-move, move + 1)
        self.y += random.randrange(-move, move + 1)
        if self.x > width:
            self.x %= width
        elif self.x < 0:
            self.x += width
        if self.y > height:
            self.y %= height
        elif self.y < 0:
            self.y += height
        x_scale = int(self.x / patch_size)
        y_scale = int(self.y / patch_size)
        grass = grass_list[x_scale * rows_of_grass + y_scale]
        if not grass.eaten:
            self.energy += grass.energy
            grass.eaten = True
        fill(255)
        ellipse(self.x, self.y, self.size, self.size)
        if self.energy <= 0:
            sheep_list.remove(self)
        elif self.energy >= 50:
            self.energy -= 30
            sheep_list.append(Sheep(self.x, self.y))


class Grass:
    def __init__(self, x, y, size):
        self.x = x
        self.y = y
        self.energy = 2
        self.eaten = False
        self.size = size

    def update(self):
        if self.eaten:
            if random.randrange(100) < 5:
                self.eaten = False
            else:
                fill(color(165, 42, 42))
        else:
            fill(color(0, 255, 0))
        rect(self.x, self.y, self.size, self.size)


def setup():
    global patch_size, grass_list, sheep_list, rows_of_grass
    size(960, 515)
    rows_of_grass = height / patch_size
    noStroke()
    grass_list = [Grass(x, y, patch_size)
                  for x in range(0, width, patch_size)
                  for y in range(0, height, patch_size)]
    sheep_list = [Sheep(random.randrange(width),
                        random.randrange(height))
                  for _ in range(20)]


def draw():
    background(255)
    for grass in grass_list:
        grass.update()
    for sheep in sheep_list:
        sheep.update()

0 コメント:

コメントを投稿

関連コンテンツ