tgpl

The Go Programming Language - Solutions
Log | Files | Refs

exercise-1-5.go (938B)


      1 package main
      2 
      3 import (
      4 	"image"
      5 	"image/color"
      6 	"image/gif"
      7 	"io"
      8 	"math"
      9 	"math/rand"
     10 	"os"
     11 )
     12 
     13 var palette = []color.Color{color.RGBA{0x25, 0x5C, 0x1c, 0xff},
     14                             color.RGBA{0x00, 0x00, 0x00, 0xff}}
     15 
     16 const (
     17 	whiteIndex = 0
     18 	blackIndex = 1
     19 )
     20 
     21 func main() {
     22 	lissajous(os.Stdout)
     23 }
     24 
     25 func lissajous(out io.Writer) {
     26 	const (
     27 		cycles 	= 5
     28 		res	= 0.001
     29 		size	= 100
     30 		nframes = 64
     31 		delay 	= 8
     32 	)
     33 	freq := rand.Float64() * 3.0
     34 	anim := gif.GIF{LoopCount: nframes}
     35 	phase := 0.0
     36 	for i := 0; i < nframes; i++ {
     37 		rect := image.Rect(0, 0, 2*size+1, 2*size+1)
     38 		img := image.NewPaletted(rect, palette)
     39 		for t := 0.0; t < cycles*2*math.Pi; t += res {
     40 			x := math.Sin(t)
     41 			y := math.Sin(t*freq + phase)
     42 			img.SetColorIndex(size+int(x*size+0.5),
     43 			size+int(y*size+0.5),
     44 			blackIndex)
     45 		}
     46 		phase += 0.1
     47 		anim.Delay = append(anim.Delay, delay)
     48 		anim.Image = append(anim.Image, img)
     49 	}
     50 	gif.EncodeAll(out, &anim)
     51 }