Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "flag"
- "fmt"
- "image"
- "image/color"
- "image/png"
- "os"
- "time"
- )
- func main() {
- iterations := flag.Int("iterations", 0, "The number of iterations of the curve.")
- filename := flag.String("file", "dragon.png", "The filename of the resulting image.")
- encode := flag.Bool("png", true, "Whether to encode into png.")
- flag.Parse()
- drag := Dragon{0, 0, 0, 0, 0, 0, 0, []image.Point{}}
- start := time.Now()
- drag.generate(*iterations)
- fmt.Println(time.Since(start), "to generate.")
- if *encode {
- render := time.Now()
- drag.render(*filename)
- fmt.Println(time.Since(render), "to render.")
- }
- fmt.Println(drag.Points[10^12])
- fmt.Println("\n", time.Since(start), "total.")
- }
- type Dragon struct {
- Dir, X, Y, Maxx, Maxy, Minx, Miny int
- Points []image.Point
- }
- func (d *Dragon) right() {
- if d.Dir == 3 {
- d.Dir = 0
- } else {
- d.Dir += 1
- }
- }
- func (d *Dragon) left() {
- if d.Dir == 0 {
- d.Dir = 3
- } else {
- d.Dir -= 1
- }
- }
- func (d *Dragon) forward() {
- switch d.Dir {
- case 0:
- d.Y += 4
- d.Points = append(d.Points, image.Point{d.X, d.Y - 3}, image.Point{d.X, d.Y - 2}, image.Point{d.X, d.Y - 1}, image.Point{d.X, d.Y})
- case 1:
- d.X += 4
- d.Points = append(d.Points, image.Point{d.X - 3, d.Y}, image.Point{d.X - 2, d.Y}, image.Point{d.X - 1, d.Y}, image.Point{d.X, d.Y})
- case 2:
- d.Y -= 4
- d.Points = append(d.Points, image.Point{d.X, d.Y + 3}, image.Point{d.X, d.Y + 2}, image.Point{d.X, d.Y + 1}, image.Point{d.X, d.Y})
- case 3:
- d.X -= 4
- d.Points = append(d.Points, image.Point{d.X + 3, d.Y}, image.Point{d.X + 2, d.Y}, image.Point{d.X + 1, d.Y}, image.Point{d.X, d.Y})
- }
- if d.X > d.Maxx {
- d.Maxx = d.X
- }
- if d.X < d.Minx {
- d.Minx = d.X
- }
- if d.Y > d.Maxy {
- d.Maxy = d.Y
- }
- if d.Y < d.Miny {
- d.Miny = d.Y
- }
- }
- func (d *Dragon) a(iterations int) {
- if iterations == 0 {
- return
- }
- d.a(iterations - 1)
- d.right()
- d.b(iterations - 1)
- d.forward()
- d.right()
- }
- func (d *Dragon) b(iterations int) {
- if iterations == 0 {
- return
- }
- d.left()
- d.forward()
- d.a(iterations - 1)
- d.left()
- d.b(iterations - 1)
- }
- func (d *Dragon) generate(iterations int) {
- d.forward()
- d.a(iterations)
- }
- func (d *Dragon) render(filename string) {
- white := color.NRGBA{255, 255, 255, 255}
- image := image.NewGray(image.Rect(d.Minx, d.Miny, d.Maxx+1, d.Maxy+1))
- for _, p := range d.Points {
- image.Set(p.X, p.Y, white)
- }
- file, _ := os.Create(filename)
- defer file.Close()
- png.Encode(file, image)
- }
Add Comment
Please, Sign In to add comment