proce55ing + jython(3)

現在の状態。もう少し整理がいるが、とりあえずの役には立つ、processing の対話的開発環境。

  • emacs から jython を起動し、
  • import xx で Sketch 相当の jython コードをロード。
  • 以下のように対話的に pa (PApplet のサブクラス) のインスタンスを生成。draw, setup メソッドは、jython 関数 draw_fn, setup_fn を呼ぶようになっている。
  • 対話的に操作したり、reload(foo) とすれば draw_fn を書き換えたり。
  • エラーが起きたときに復旧できなかったり。
>>> import foo
>>> p = foo.init_p()
>>> f = foo.open_frame(p)
>>> p.frameRate(100)
from javax.swing import JFrame
from processing.core import PApplet

class pa(PApplet):
    def draw(this):
        draw_fn(this)
    def setup(this):
        setup_fn(this)

class ball:
    def __init__(this, p, x, y):
        this.x = x
        this.y = y
        this.r = 2
        this.p = p
    def move(this):
        this.x = this.x + this.p.random(10)
        this.y = this.y - this.p.random(5)
        if this.y < 0:
            this.y = this.p.height
        if this.x > this.p.width:
            this.x = 0
    def draw(this):
        this.p.fill(3, 0)
        this.p.ellipse(this.x, this.y, this.r, this.r)

def draw_fn(p):
    for b in p.balls:
        if (p.random(1) > 0.9):
            b.move()
        b.draw()
    p.rectMode(p.CORNER);
    p.fill(3, 3*0.3);
    p.rect(0, 0, p.width, p.height);

def setup_fn(p):
    p.colorMode(p.HSB, 3)
    pass

def init_p():
    p = pa()
    p.balls = []
    for i in range(10):
        p.balls.append(ball(p, p.random(100),p.random(100)))
    return p

def open_frame(p):
    f = JFrame()
    f.setSize(200, 200)
    f.contentPane.add(p)
    p.init()
    f.visible = 1
    return f

作業イメージ

  • 例えば Boids のアルゴリズムを勉強して実装してみようとしている、とする。
  • Boid クラスを作ってインスタンスを適当に表示させておく。
  • 少しずつ実装して動くようにする。常に動くものを見ながら確認。
  • 特定のインスタンスの色だけ変更したり、パラメーターを変更したりして確認と調整。作業の間、PApplet はずっと動いたまま。