hybridgroup.gobot/examples/sphero_conways.go

127 lines
1.9 KiB
Go
Raw Normal View History

package main
import (
"fmt"
2014-07-11 08:21:21 +08:00
"time"
"github.com/hybridgroup/gobot"
2014-05-23 12:20:16 +08:00
"github.com/hybridgroup/gobot/platforms/sphero"
)
type conway struct {
alive bool
age int
contacts int
2014-04-29 02:29:53 +08:00
cell *sphero.SpheroDriver
}
func main() {
2014-07-09 09:36:14 +08:00
gbot := gobot.NewGobot()
spheros := []string{
"/dev/rfcomm0",
"/dev/rfcomm1",
"/dev/rfcomm2",
}
2014-07-09 09:36:14 +08:00
for _, port := range spheros {
spheroAdaptor := sphero.NewAdaptor(port)
cell := sphero.NewSpheroDriver(spheroAdaptor)
cell.SetName("Sphero" + port)
work := func() {
conway := new(conway)
2014-04-29 02:29:53 +08:00
conway.cell = cell
conway.birth()
cell.On(sphero.Collision, func(data interface{}) {
conway.contact()
})
2014-05-23 12:20:16 +08:00
gobot.Every(3*time.Second, func() {
2016-07-13 23:32:22 +08:00
if conway.alive {
conway.movement()
}
})
2014-05-23 12:20:16 +08:00
gobot.Every(10*time.Second, func() {
2016-07-13 23:32:22 +08:00
if conway.alive {
conway.birthday()
}
})
}
2014-07-09 09:36:14 +08:00
robot := gobot.NewRobot("conway",
[]gobot.Connection{spheroAdaptor},
[]gobot.Device{cell},
work,
)
gbot.AddRobot(robot)
}
2014-07-09 09:36:14 +08:00
gbot.Start()
}
func (c *conway) resetContacts() {
c.contacts = 0
}
func (c *conway) contact() {
2014-06-11 06:16:11 +08:00
c.contacts++
}
func (c *conway) rebirth() {
2014-04-29 02:29:53 +08:00
fmt.Println("Welcome back", c.cell.Name, "!")
c.life()
}
func (c *conway) birth() {
c.resetContacts()
c.age = 0
c.life()
c.movement()
}
func (c *conway) life() {
2014-04-29 02:29:53 +08:00
c.cell.SetRGB(0, 255, 0)
c.alive = true
}
func (c *conway) death() {
2014-04-29 02:29:53 +08:00
fmt.Println(c.cell.Name, "died :(")
c.alive = false
2014-04-29 02:29:53 +08:00
c.cell.SetRGB(255, 0, 0)
c.cell.Stop()
}
func (c *conway) enoughContacts() bool {
if c.contacts >= 2 && c.contacts < 7 {
return true
}
2014-06-11 06:16:11 +08:00
return false
}
func (c *conway) birthday() {
2014-06-11 06:16:11 +08:00
c.age++
2014-04-29 02:29:53 +08:00
fmt.Println("Happy birthday", c.cell.Name, "you are", c.age, "and had", c.contacts, "contacts.")
2016-07-13 23:32:22 +08:00
if c.enoughContacts() {
if !c.alive {
c.rebirth()
}
} else {
c.death()
}
c.resetContacts()
}
func (c *conway) movement() {
2016-07-13 23:32:22 +08:00
if c.alive {
2014-04-29 02:29:53 +08:00
c.cell.Roll(100, uint16(gobot.Rand(360)))
}
}