index.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package dmmo
  2. import (
  3. "encoding/json"
  4. "os"
  5. )
  6. type Index struct {
  7. Tiles []*Tile `json:"tiles"`
  8. }
  9. func NewIndex() *Index {
  10. return &Index{
  11. Tiles: []*Tile{},
  12. }
  13. }
  14. func (i *Index) Save(filename string) error {
  15. b, err := json.Marshal(i.Tiles)
  16. if err != nil {
  17. return err
  18. }
  19. err = os.WriteFile(filename+".json", b, os.ModePerm)
  20. return err
  21. }
  22. func LoadIndex(filename string) (*Index, error) {
  23. pay, err := os.ReadFile(filename + ".json")
  24. if err != nil {
  25. return nil, err
  26. }
  27. var idx *Index = &Index{
  28. Tiles: []*Tile{},
  29. }
  30. err = json.Unmarshal(pay, &idx.Tiles)
  31. return idx, err
  32. }
  33. func (i *Index) Has(name string) bool {
  34. for _, t := range i.Tiles {
  35. if t != nil && t.Name == name {
  36. return true
  37. }
  38. }
  39. return false
  40. }
  41. func (i *Index) Get(name string) *Tile {
  42. for _, t := range i.Tiles {
  43. if t != nil && t.Name == name {
  44. return t
  45. }
  46. }
  47. return nil
  48. }
  49. func (i *Index) Id(name string) (uint64, bool) {
  50. for id, t := range i.Tiles {
  51. if t != nil && t.Name == name {
  52. return uint64(id), true
  53. }
  54. }
  55. return 0, false
  56. }
  57. func (i *Index) Set(name, symbol, color string, auto ...bool) {
  58. if i.Has(name) {
  59. for id, t := range i.Tiles {
  60. if t != nil && t.Name == name {
  61. i.Tiles[id].Symbol = symbol
  62. i.Tiles[id].Color = color
  63. if len(auto) != 0 {
  64. i.Tiles[id].AutoLight = auto[0]
  65. }
  66. break
  67. }
  68. }
  69. } else {
  70. if len(auto) == 0 {
  71. i.Tiles = append(i.Tiles, NewTile(name, symbol, color, true))
  72. } else {
  73. i.Tiles = append(i.Tiles, NewTile(name, symbol, color, auto[0]))
  74. }
  75. }
  76. }
  77. func (i *Index) HasId(id uint64) bool {
  78. return len(i.Tiles) < int(id) || id > 0
  79. }
  80. func (i *Index) GetId(id uint64) *Tile {
  81. idy := int(id)
  82. for idx, t := range i.Tiles {
  83. if idx == idy {
  84. return t
  85. }
  86. }
  87. return nil
  88. }
  89. func (i *Index) SetId(id uint64, name, symbol, color string, auto ...bool) {
  90. if i.HasId(id) {
  91. i.Tiles[id].Name = name
  92. i.Tiles[id].Symbol = symbol
  93. i.Tiles[id].Color = color
  94. if len(auto) != 0 {
  95. i.Tiles[id].AutoLight = auto[0]
  96. }
  97. } else {
  98. if len(auto) == 0 {
  99. i.Tiles = append(i.Tiles, NewTile(name, symbol, color, true))
  100. } else {
  101. i.Tiles = append(i.Tiles, NewTile(name, symbol, color, auto[0]))
  102. }
  103. }
  104. }