aboutsummaryrefslogtreecommitdiff
path: root/internal/model/map.go
blob: de19660d52af06a838243d1eb2debc2ed40b6b44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package model

type Point struct{ X, Y int }

type Cell struct {
	Terrain int    `yaml:"t"`
	Color   string `yaml:"c,omitempty"`
	Text    string `yaml:"x,omitempty"`
}

type TextLabel struct {
	Text  string `yaml:"text"`
	Start Point  `yaml:"start"`
	Color string `yaml:"color,omitempty"`
}

type Map struct {
	Name       string           `yaml:"name"`
	Width      int              `yaml:"width"`
	Height     int              `yaml:"height"`
	Grid       [][]Cell         `yaml:"-"`
	Palette    []Terrain        `yaml:"palette"`
	TextLabels []TextLabel      `yaml:"text_labels,omitempty"`
	Submaps    map[Point]*Map   `yaml:"-"`
	Parent     *Map             `yaml:"-"`
	Filename   string           `yaml:"-"`
}

func NewMap(name string, w, h int, palette []Terrain) *Map {
	grid := make([][]Cell, h)
	for y := range grid {
		grid[y] = make([]Cell, w)
		for x := range grid[y] {
			grid[y][x].Terrain = -1
		}
	}
	return &Map{
		Name:    name,
		Width:   w,
		Height:  h,
		Grid:    grid,
		Palette: palette,
		Submaps: make(map[Point]*Map),
	}
}

func (m *Map) Clone() *Map {
	grid := make([][]Cell, m.Height)
	for y := range grid {
		grid[y] = make([]Cell, m.Width)
		copy(grid[y], m.Grid[y])
	}
	c := &Map{
		Name:    m.Name,
		Width:   m.Width,
		Height:  m.Height,
		Grid:    grid,
		Palette: m.Palette,
		Submaps: make(map[Point]*Map),
		Parent:  m.Parent,
	}
	for _, tl := range m.TextLabels {
		c.TextLabels = append(c.TextLabels, tl)
	}
	for pt, sub := range m.Submaps {
		c.Submaps[pt] = sub
	}
	return c
}

func (m *Map) InBounds(p Point) bool {
	return p.X >= 0 && p.X < m.Width && p.Y >= 0 && p.Y < m.Height
}

func (m *Map) SetCell(p Point, terrain int, color ...string) {
	if !m.InBounds(p) {
		return
	}
	text := m.Grid[p.Y][p.X].Text
	clr := ""
	if len(color) > 0 {
		clr = color[0]
	}
	m.Grid[p.Y][p.X] = Cell{Terrain: terrain, Color: clr, Text: text}
}

func (m *Map) SetText(p Point, text string) {
	if !m.InBounds(p) {
		return
	}
	m.Grid[p.Y][p.X].Text = text
}

func (m *Map) CellAt(p Point) Cell {
	if !m.InBounds(p) {
		return Cell{Terrain: -1}
	}
	return m.Grid[p.Y][p.X]
}