Noah Petherbridge
e25869644c
* Edit Mode now uses the Level object itself to keep the drawing data rather than pull its Palette and Chunks out, so it can hang on to more information. The Canvas widget is given references to the Level.Palette and Level.Chunker via Canvas.LoadLevel() * Fix the handoff between Edit Mode and Play Mode. They pass the Level object back and forth and the Filename, because it's not part of the Level. You can save the map with its original settings after returning from Play Mode. * Fix the collision detection in Play Mode. It broke previously when palettes were added because of the difference between a render.Point and a level.Pixel and it couldn't easily look up coordinates. The new Chunker system provides a render.Point lookup API. * All pixels are solid for collision right now, TODO is to return Swatch information from the pixels touching the player character and react accordingly (non-solid, fire flag, etc.) * Remove the level.Grid type as it has been replaced by the Chunker. * Clean up some unused variables and functions.
64 lines
1.4 KiB
Go
64 lines
1.4 KiB
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
|
|
}
|
|
|
|
// WriteJSON writes a level to JSON on disk.
|
|
func (m *Level) WriteJSON(filename string) error {
|
|
fh, err := os.Create(filename)
|
|
if err != nil {
|
|
return fmt.Errorf("Level.WriteJSON(%s): failed to create file: %s", filename, err)
|
|
}
|
|
defer fh.Close()
|
|
|
|
_ = fh
|
|
|
|
return nil
|
|
}
|
|
|
|
// 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()
|
|
|
|
// Decode the JSON file from disk.
|
|
m := New()
|
|
decoder := json.NewDecoder(fh)
|
|
err = decoder.Decode(&m)
|
|
if err != nil {
|
|
return m, fmt.Errorf("level.LoadJSON: JSON decode error: %s", err)
|
|
}
|
|
|
|
// Inflate the chunk metadata to map the pixels to their palette indexes.
|
|
m.Chunker.Inflate(m.Palette)
|
|
|
|
// Inflate the private instance values.
|
|
m.Palette.Inflate()
|
|
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.Swatch = m.Palette.Swatches[px.PaletteIndex]
|
|
}
|
|
return m, err
|
|
}
|