tgpl

The Go Programming Language - Solutions
Log | Files | Refs

exercise-1-6.go (1132B)


      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 			    color.RGBA{0x3B, 0x3B, 0x71, 0xff}}
     16 
     17 const (
     18 	greenIndex = 0
     19 	blackIndex = 1
     20 	blueIndex = 2
     21 )
     22 
     23 func main() {
     24 	lissajous(os.Stdout)
     25 }
     26 
     27 func lissajous(out io.Writer) {
     28 	const (
     29 		cycles 	= 5
     30 		res	= 0.001
     31 		size	= 100
     32 		nframes = 64
     33 		delay 	= 8
     34 	)
     35 	freq := rand.Float64() * 3.0
     36 	anim := gif.GIF{LoopCount: nframes}
     37 	phase := 0.0
     38 	for i := 0; i < nframes; i++ {
     39 		rect := image.Rect(0, 0, 2*size+1, 2*size+1)
     40 		img := image.NewPaletted(rect, palette)
     41 		for t := 0.0; t < cycles*2*math.Pi; t += res {
     42 			x := math.Sin(t)
     43 			y := math.Sin(t*freq + phase)
     44 			if t < cycles*2*math.Pi/2 {
     45 				img.SetColorIndex(size+int(x*size+0.5),
     46 				size+int(y*size+0.5),
     47 				blackIndex)
     48 			} else {
     49 				img.SetColorIndex(size+int(x*size+0.5),
     50 				size+int(y*size+0.5),
     51 				blueIndex)
     52 			}
     53 		}
     54 		phase += 0.1
     55 		anim.Delay = append(anim.Delay, delay)
     56 		anim.Image = append(anim.Image, img)
     57 	}
     58 	gif.EncodeAll(out, &anim)
     59 }