doodle/pkg/scripting/events.go
Noah Petherbridge 1e80304061 Initial Doodad JavaScript System
* Add the JavaScript system for Doodads to run their scripts in levels,
  and wire initial OnCollide() handler support.
* CLI: Add a `doodad install-script` command to the doodad tool.
  * Usage: `doodad install-script <index.js> <filename.doodad>`
* Add dev-assets folder for storing source files for the official
  default doodads, sprites, levels, etc. and for now add a JavaScript
  for the first test doodad.
2019-04-15 23:07:40 -07:00

54 lines
1.0 KiB
Go

package scripting
import (
"github.com/robertkrimen/otto"
)
// Events API for Doodad scripts.
type Events struct {
registry map[string][]otto.Value
}
// NewEvents initializes the Events API.
func NewEvents() *Events {
return &Events{
registry: map[string][]otto.Value{},
}
}
// OnCollide fires when another actor collides with yours.
func (e *Events) OnCollide(call otto.FunctionCall) otto.Value {
callback := call.Argument(0)
if !callback.IsFunction() {
return otto.Value{} // TODO
}
if _, ok := e.registry[CollideEvent]; !ok {
e.registry[CollideEvent] = []otto.Value{}
}
e.registry[CollideEvent] = append(e.registry[CollideEvent], callback)
return otto.Value{}
}
// RunCollide invokes the OnCollide handler function.
func (e *Events) RunCollide() error {
if _, ok := e.registry[CollideEvent]; !ok {
return nil
}
for _, callback := range e.registry[CollideEvent] {
_, err := callback.Call(otto.Value{}, "test argument")
if err != nil {
return err
}
}
return nil
}
// Event name constants.
const (
CollideEvent = "collide"
)