You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

76 lines
2.0 KiB

  1. package server
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "os/user"
  10. "strings"
  11. )
  12. // Config embodies the configuration for a game. These are populated in various
  13. // ways (json POSTed to server, config file, constants) and are typically owned
  14. // by a Controller.
  15. type Config struct {
  16. Tick int `json:"tick"` // ms
  17. Timescale float32 `json:"timescale"`
  18. Delta float32 `json:"delta"`
  19. Width int `json:"width"`
  20. Height int `json:"height"`
  21. Obstacles int `json:"obstacles"`
  22. MaxPoints int `json:"max_points"`
  23. Mode string `json:"mode"`
  24. }
  25. const (
  26. TICK = 60 // ms, this is how often physics is updated
  27. TIMESCALE = 1.0 // this tweaks the temporal duration of a TICK
  28. WIDTH = 800
  29. HEIGHT = 550
  30. OBSTACLES = 5
  31. MAX_POINTS = 500 // allowing for 50 pts in every category
  32. DEFAULT_MODE = "deathmatch"
  33. )
  34. // LoadConfig takes the location of a json file that contains values desired to
  35. // be used in the creation of games. Priority is given to values specified at
  36. // game cration time using control channel, followed by values in config file,
  37. // followed by constants defined above.
  38. func LoadConfig(filename string) (Config, error) {
  39. c := Config{
  40. Tick: TICK,
  41. Timescale: TIMESCALE,
  42. Width: WIDTH,
  43. Height: HEIGHT,
  44. Obstacles: OBSTACLES,
  45. MaxPoints: MAX_POINTS,
  46. Mode: DEFAULT_MODE,
  47. }
  48. u, err := user.Current()
  49. if err != nil {
  50. return c, err
  51. }
  52. if len(filename) > 1 && filename[:2] == "~/" {
  53. filename = strings.Replace(filename, "~", u.HomeDir, 1)
  54. }
  55. if _, err := os.Stat(filename); os.IsNotExist(err) {
  56. log.Printf("%+v not found, using defaults", filename)
  57. } else {
  58. log.Printf("found config file: %s", filename)
  59. f, err := ioutil.ReadFile(filename)
  60. if err != nil {
  61. return c, err
  62. }
  63. err = json.Unmarshal(f, &c)
  64. if err != nil {
  65. return c, errors.New(fmt.Sprintf("config parse error: %s", err))
  66. }
  67. }
  68. c.Delta = (float32(c.Tick) / 1000.0) * float32(c.Timescale)
  69. log.Printf("final config: %+v", c)
  70. return c, nil
  71. }