doodle/level/json.go
Noah Petherbridge e1cbff8c3f Add Palette Window and Palette Support to Edit Mode
* Add ui.Window to easily create reusable windows with titles.
* Add a palette window (panel) to the right edge of the Edit Mode.
  * Has Radio Buttons listing the colors available in the palette.
* Add palette support to Edit Mode so when you draw pixels, they take
  on the color and attributes of the currently selected Swatch in your
  palette.
* Revise the on-disk format to better serialize the Palette object to
  JSON.
* Break Play Mode: collision detection fails because the Grid key
  elements are now full Pixel objects (which retain their Palette and
  Swatch properties).
  * The Grid will need to be re-worked to separate X,Y coordinates from
    the Pixel metadata to just test "is something there, and what is
    it?"
2018-08-10 17:19:47 -07:00

47 lines
979 B
Go

package level
import (
"bytes"
"encoding/json"
"fmt"
"os"
)
// ToJSON serializes the level as JSON.
func (m *Level) ToJSON() ([]byte, error) {
out := bytes.NewBuffer([]byte{})
encoder := json.NewEncoder(out)
encoder.SetIndent("", "\t")
err := encoder.Encode(m)
return out.Bytes(), err
}
// LoadJSON loads a map from JSON file.
func LoadJSON(filename string) (*Level, error) {
fh, err := os.Open(filename)
if err != nil {
return nil, err
}
defer fh.Close()
m := New()
decoder := json.NewDecoder(fh)
err = decoder.Decode(&m)
if err != nil {
return m, err
}
// Inflate the private instance values.
for _, px := range m.Pixels {
if int(px.PaletteIndex) > len(m.Palette.Swatches) {
return nil, fmt.Errorf(
"pixel %s references palette index %d but there are only %d swatches in the palette",
px, px.PaletteIndex, len(m.Palette.Swatches),
)
}
px.Palette = m.Palette
px.Swatch = m.Palette.Swatches[px.PaletteIndex]
}
return m, err
}