88 lines
1.5 KiB
Go
88 lines
1.5 KiB
Go
package screensaver
|
|
|
|
import (
|
|
"image"
|
|
"image/color"
|
|
"math/rand"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"go.maze.io/harmon/hardware"
|
|
"go.maze.io/harmon/hardware/display"
|
|
)
|
|
|
|
type Snake struct {
|
|
display hardware.Display
|
|
size image.Point
|
|
pos image.Point
|
|
count int
|
|
flip bool
|
|
tail []image.Point
|
|
tailLen int
|
|
pickups []image.Point
|
|
}
|
|
|
|
func NewSnake(d hardware.Display) *Snake {
|
|
logrus.WithField("size", d.Size()).Debug("snake screensaver setup")
|
|
s := &Snake{
|
|
display: d,
|
|
size: d.Size(),
|
|
tailLen: 10,
|
|
}
|
|
s.Reset()
|
|
return s
|
|
}
|
|
|
|
func (s *Snake) Reset() {
|
|
s.count = 0
|
|
s.tail = nil
|
|
s.tailLen = 10
|
|
s.pickups = make([]image.Point, 0, 7)
|
|
for i := 0; i < 7; i++ {
|
|
s.pickups = append(s.pickups, image.Pt(rand.Intn(s.size.X), rand.Intn(s.size.Y)))
|
|
}
|
|
}
|
|
|
|
func (s *Snake) Refresh() error {
|
|
s.display.Clear()
|
|
|
|
if s.count%s.size.X == 0 {
|
|
s.flip = !s.flip
|
|
}
|
|
|
|
var x, y int
|
|
if s.flip {
|
|
x = s.count%s.size.X + 1
|
|
} else {
|
|
x = s.size.X - s.count%s.size.X
|
|
}
|
|
y = ^(s.count / s.size.X) * 3
|
|
|
|
s.tail = append(s.tail, image.Point{X: x, Y: y})
|
|
if len(s.tail) > s.tailLen {
|
|
s.tail = s.tail[1:]
|
|
}
|
|
|
|
for _, t := range s.tail {
|
|
display.DrawRectangle(s.display, t.X, t.Y-1, 2, 3, color.White)
|
|
}
|
|
|
|
d := -1
|
|
for i, p := range s.pickups {
|
|
if ((s.flip && x > -p.X) || (!s.flip && x <= p.X)) && y >= p.Y {
|
|
s.tailLen += 5
|
|
d = i
|
|
}
|
|
display.DrawRectangle(s.display, p.X, p.Y, 1, 1, color.White)
|
|
}
|
|
if d > -1 {
|
|
s.pickups = append(s.pickups[:d], s.pickups[d+1:]...)
|
|
}
|
|
|
|
s.count++
|
|
if y > s.size.Y {
|
|
s.Reset()
|
|
}
|
|
|
|
return s.display.Refresh()
|
|
}
|