package score import ( "encoding/json" "errors" "io/ioutil" "os" "path/filepath" "tildegit.org/jakew/wordle/game" "time" ) type Line struct { Word string `json:"word"` Correct []int `json:"correct"` Present []int `json:"present"` } type Game struct { Day int `json:"day"` Date time.Time `json:"date"` Score int `json:"score"` Lines []Line `json:"lines"` } type Scores struct { Games []Game `json:"games"` } func ToGame(b *game.Board) *Game { g := &Game{ Day: b.Day, Date: time.Now().In(time.UTC), Score: b.CurrentGuess, Lines: []Line{}, } for i := 0; i < b.CurrentGuess; i++ { g.Lines = append(g.Lines, Line{ Word: string(b.Guesses[i].Letters), Correct: b.Guesses[i].Correct, Present: b.Guesses[i].Present, }) } return g } func getSaveLocation() (string, error) { dirname, err := os.UserHomeDir() if err != nil { return "", err } return filepath.Join(dirname, "/.wordle.json"), nil } func Load() (*Scores, error) { path, err := getSaveLocation() if err != nil { return &Scores{}, err } b, err := ioutil.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return &Scores{Games: []Game{}}, nil } else if err != nil { return &Scores{}, err } var scores Scores err = json.Unmarshal(b, &scores) return &scores, err } func Save(scores *Scores) error { path, err := getSaveLocation() if err != nil { return err } b, err := json.Marshal(scores) if err != nil { return err } err = ioutil.WriteFile(path, b, 0644) return err } func SaveBoard(b *game.Board) error { scores, err := Load() if err != nil { return err } scores.Games = append(scores.Games, *ToGame(b)) err = Save(scores) return err } func GetLastGame() (*Game, error) { scores, err := Load() if err != nil { return &Game{}, err } if len(scores.Games) <= 0 { return nil, nil } return &scores.Games[len(scores.Games)-1], nil }