何かを書き留める何か

数学や読んだ本について書く何かです。最近は社会人として生き残りの術を学ぶ日々です。

『プログラミング言語Go』読書記録 その2

電池入りの言語

プログラミング言語Go』、今回は1.4から1.8まで。

1.4 GIFアニメーション

リサージュ曲線を描く。リサージュといえば電通大の校章である。

校章・コミュニケーションマーク│電気通信大学

1.4はconst宣言、コンポジットリテラルインスタンス生成、浮動小数点の演算が主題であるが、詳細は後の章に書かれているので、ここでは単純にリサージュを楽しむことにする。 const宣言内部は=で揃えてある。これはgofmtが自動で行ってくれるのでプログラマは普通に入力すればよい。

package main

import (
    "image"
    "image/color"
    "image/gif"
    "io"
    "math"
    "math/rand"
    "os"
    "time"
)

var palette = []color.Color{color.Black, color.RGBA{0x00, 0xFF, 0x00, 0xff}}

const (
    whiteIndex = 0
    blackIndex = 1
)

func main() {
    rand.Seed(time.Now().UTC().UnixNano())
    lissajous(os.Stdout)
}

func lissajous(out io.Writer) {
    const (
        cycles  = 5
        res     = 0.001
        size    = 100
        nframes = 64
        delay   = 8
    )
    freq := rand.Float64() * 3.0
    anim := gif.GIF{LoopCount: nframes}
    phase := 0.0
    for i := 0; i < nframes; i++ {
        rect := image.Rect(0, 0, 2*size+1, 2*size+1)
        img := image.NewPaletted(rect, palette)
        for t := 0.0; t < cycles*2*math.Pi; t += res {
            x := math.Sin(t)
            y := math.Sin(t*freq + phase)
            img.SetColorIndex(size+int(x*size+0.5), size+int(y*size+0.5), blackIndex)
        }
        phase += 0.1
        anim.Delay = append(anim.Delay, delay)
        anim.Image = append(anim.Image, img)
    }
    gif.EncodeAll(out, &anim)
}

実行するには、以下のようにコマンドを実行する。 標準でGIFを扱えるのは中々すごい。

$ go build lissajous.go
$ lissajous.exe > out.gif