Skip to content

Instantly share code, notes, and snippets.

@santiaago
Created January 11, 2015 16:33
Show Gist options
  • Save santiaago/a749e510cd95d50314db to your computer and use it in GitHub Desktop.
Save santiaago/a749e510cd95d50314db to your computer and use it in GitHub Desktop.
Building a chessboard image in go
package main
import (
"image"
"image/color"
"image/jpeg"
"log"
"os"
)
func main() {
m := image.NewRGBA(image.Rect(0, 0, 240, 240))
white := color.RGBA{uint8(255), uint8(255), 255, 255}
black := color.RGBA{uint8(0), uint8(0), 0, 255}
drawGrid(m, black, white)
if img, err := os.Create("chessboard.jpg"); err != nil {
log.Println("unable to create img.jpg: %v", err)
} else {
jpeg.Encode(img, m, nil)
defer img.Close()
}
}
func drawGrid(m *image.RGBA, color1, color2 color.RGBA) {
size := m.Bounds().Size()
quad := size.X / 6
for x := 0; x < size.X; x++ {
val := (x / quad) % 2
for y := 0; y < size.Y; y++ {
val2 := (y / quad) % 2
if (val+val2)%2 == 0 {
m.Set(x, y, color1)
} else {
m.Set(x, y, color2)
}
}
}
}
@rmetzler
Copy link

I think you could remove the first and second time you use modulo and just use the third.

func drawGrid(m *image.RGBA, color1, color2 color.RGBA) {
    size := m.Bounds().Size()
    quad := size.X / 6
    for x := 0; x < size.X; x++ {
        val := x / quad
        for y := 0; y < size.Y; y++ {
            val2 := y / quad
            if (val+val2)%2 == 0 {
                m.Set(x, y, color1)
            } else {
                m.Set(x, y, color2)
            }
        }
    }
}

also, if your colors are stored in an array, you could rewrite the last if and just call

  m.Set(x,y, colors[ (val+val2)%2 ])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment