-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
79 lines (67 loc) · 1.87 KB
/
map.go
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
// Map handles the underlying map grid, but not the image itself or drawing it
package main
import (
"image"
"image/png"
"os"
)
type mapCell struct {
isLand bool
habitability float64
}
type mapGrid struct {
area []mapCell
width int
height int
}
// Return cell at [x,y] of mapGrid (!)
func (m *mapGrid) CellAt(x, y int) *mapCell {
return &m.area[y*m.width+x]
}
func calcHabitability(colorLevel uint32) float64 {
return float64(0xffff-colorLevel) / 0xffff
}
func loadImage(path string) (image.Image, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
img, err := png.Decode(file)
defer file.Close()
if err != nil {
return nil, err
}
return img, nil
}
// Creates the mapGrid from a .png image under `path`
func NewMapGrid(path string) (*mapGrid, error) {
img, err := loadImage(path)
if err != nil {
return nil, err
}
imgWidth, imgHeight := img.Bounds().Max.X, img.Bounds().Max.Y
mGrid := &mapGrid{
area: make([]mapCell, imgWidth*imgHeight),
width: imgWidth,
height: imgHeight,
}
for y := 0; y < imgHeight; y++ {
for x := 0; x < imgWidth; x++ {
red, green, blue, _ := img.At(x, y).RGBA()
mc := mGrid.CellAt(x, y)
if blue == 0xffff && red == 0 && green == 0 { //RGB of [255, 0, 0] means water
mc.isLand = false
} else {
mc.isLand = true
//The inverse of how white the cell is determines habilability, both habitable and
//inhabitable cells have the same green value so we must use either blue or red
//to determine the "whiteness". This will probably be changed in the future as we
//have 4 values to work with which can be used to determine more things from a
//single bitmap, like maybe rare resources. It is like this for now because it
//makes the base map image clear and easy to edit with basic editing tools.
mc.habitability = calcHabitability(red)
}
}
}
return mGrid, nil
}