2018-06-17 17:29:57 +00:00
|
|
|
package level
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
2018-08-11 00:19:47 +00:00
|
|
|
"fmt"
|
2018-06-17 17:29:57 +00:00
|
|
|
"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.
|
2018-08-11 00:19:47 +00:00
|
|
|
func LoadJSON(filename string) (*Level, error) {
|
2018-06-17 17:29:57 +00:00
|
|
|
fh, err := os.Open(filename)
|
|
|
|
if err != nil {
|
2018-08-11 00:19:47 +00:00
|
|
|
return nil, err
|
2018-06-17 17:29:57 +00:00
|
|
|
}
|
|
|
|
defer fh.Close()
|
|
|
|
|
2018-08-11 00:19:47 +00:00
|
|
|
m := New()
|
2018-06-17 17:29:57 +00:00
|
|
|
decoder := json.NewDecoder(fh)
|
|
|
|
err = decoder.Decode(&m)
|
2018-08-11 00:19:47 +00:00
|
|
|
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]
|
|
|
|
}
|
2018-06-17 17:29:57 +00:00
|
|
|
return m, err
|
|
|
|
}
|