doodle/pkg/scripting/scripting.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

63 lines
1.4 KiB
Go

// Package scripting manages the JavaScript VMs for Doodad
// scripts.
package scripting
import (
"errors"
"fmt"
"git.kirsle.net/apps/doodle/pkg/level"
"git.kirsle.net/apps/doodle/pkg/log"
)
// Supervisor manages the JavaScript VMs for each doodad by its
// unique ID.
type Supervisor struct {
scripts map[string]*VM
}
// NewSupervisor creates a new JavaScript Supervior.
func NewSupervisor() *Supervisor {
return &Supervisor{
scripts: map[string]*VM{},
}
}
// InstallScripts loads scripts for all actors in the level.
func (s *Supervisor) InstallScripts(level *level.Level) error {
for _, actor := range level.Actors {
id := actor.ID()
log.Debug("InstallScripts: load script from Actor %s", id)
if _, ok := s.scripts[id]; ok {
return fmt.Errorf("duplicate actor ID %s in level", id)
}
s.scripts[id] = NewVM(id)
if err := s.scripts[id].RegisterLevelHooks(); err != nil {
return err
}
}
return nil
}
// To returns the VM for a named script.
func (s *Supervisor) To(name string) *VM {
if vm, ok := s.scripts[name]; ok {
return vm
}
log.Error("scripting.Supervisor.To(%s): no such VM but returning blank VM",
name,
)
return NewVM(name)
}
// GetVM returns a script VM from the supervisor.
func (s *Supervisor) GetVM(name string) (*VM, error) {
if vm, ok := s.scripts[name]; ok {
return vm, nil
}
return nil, errors.New("not found")
}