feat: implement persistant configuration
This commit is contained in:
parent
30b194619f
commit
8a02249845
5 changed files with 82 additions and 0 deletions
45
game/config/config.go
Normal file
45
game/config/config.go
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
fd *os.File
|
||||
SoundVolume byte `json:"sound_volume"`
|
||||
}
|
||||
|
||||
func DefaultConfig(fd *os.File) *Config {
|
||||
cfg := Config{
|
||||
SoundVolume: 255,
|
||||
}
|
||||
cfg.fd = fd
|
||||
return &cfg
|
||||
}
|
||||
|
||||
func LoadFromFile(filename string) (*Config, error) {
|
||||
fd, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg := DefaultConfig(fd)
|
||||
err = json.NewDecoder(fd).Decode(cfg)
|
||||
return cfg, err
|
||||
}
|
||||
|
||||
func (c Config) Save() error {
|
||||
if err := c.fd.Truncate(0); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := c.fd.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
return json.NewEncoder(c.fd).Encode(c)
|
||||
}
|
||||
|
||||
func (c Config) Close() error {
|
||||
return c.fd.Close()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue