krampus19/cmd/krampus19/settings.go
Sander Schobers 11ab3fca0f Added settings in-game.
Added video settings.
Added and improved reusable controls.
Separated drawing of sprites.
Fixed bug that text was right aligned instead of left aligned.
2019-12-28 16:03:57 +01:00

99 lines
1.6 KiB
Go

package main
import (
"encoding/json"
"os"
"path/filepath"
"opslag.de/schobers/allg5"
)
func newDefaultSettings() settings {
return settings{
Controls: controls{
MoveUp: allg5.KeyUp,
MoveRight: allg5.KeyRight,
MoveDown: allg5.KeyDown,
MoveLeft: allg5.KeyLeft,
},
Video: video{
Windowed: true,
DisplayMode: "",
},
}
}
type settings struct {
Controls controls
Video video
}
func (s *settings) DefaultPath() (string, error) {
config, err := os.UserConfigDir()
if err != nil {
return "", err
}
dir := filepath.Join(config, "krampus19")
err = os.MkdirAll(dir, 0600)
if err != nil {
return "", err
}
return filepath.Join(dir, "settings.json"), nil
}
func (s *settings) Load(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
var fromFile settings
err = json.NewDecoder(f).Decode(&fromFile)
if err != nil {
return err
}
*s = fromFile
return nil
}
func (s *settings) LoadDefault() error {
path, err := s.DefaultPath()
if err != nil {
return err
}
return s.Load(path)
}
func (s *settings) Store(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(&s)
}
func (s *settings) StoreDefault() error {
path, err := s.DefaultPath()
if err != nil {
return err
}
return s.Store(path)
}
type controls struct {
MoveUp allg5.Key
MoveRight allg5.Key
MoveDown allg5.Key
MoveLeft allg5.Key
}
type video struct {
Windowed bool
DisplayMode string
}
func (c controls) MovementKeys() []allg5.Key {
return []allg5.Key{c.MoveUp, c.MoveRight, c.MoveDown, c.MoveLeft}
}