package main import ( "encoding/json" "fmt" "os" "path" "strconv" "strings" ) type World struct { Name string `json:"name"` Width uint64 `json:"width"` Height uint64 `json:"height"` TileIndex *TileIndex `json:"-"` Map []uint64 `json:"-"` } func LoadWorld(worlddir string) (*World, error) { var ( w *World = &World{} err error ) payload, err := os.ReadFile(path.Join(worlddir, "world.json")) if err != nil { return nil, err } err = json.Unmarshal(payload, &w) if err != nil { return nil, err } w.Map = make([]uint64, 0, w.Width*w.Height) ti, err := ParseTileIndex(path.Join(worlddir, "tiles.txt")) if err != nil { return nil, err } w.TileIndex = ti payload, err = os.ReadFile(path.Join(worlddir, "map.dat")) if err != nil { return nil, err } var ( line string = "" linenum int = 0 ) for _, b := range payload { if b == '\n' { linenum += 1 parts := strings.Split(line, " ") if len(parts) != int(w.Width) { return nil, fmt.Errorf("%d]: Failed parsing Map Data, not enough parts (expected=%d, got=%d), '%s'", linenum, w.Width, len(parts), line) } for segnum, p := range parts { t, err := strconv.ParseUint(p, 10, 64) if err != nil { return nil, fmt.Errorf("%d]: Failed parsing Map Data, line segment #%d errored %v, '%s'", linenum, segnum, err, line) } w.Map = append(w.Map, t) } line = "" } else { line += string(b) } } return w, nil }