go-tetris/ranking.go

76 lines
1.5 KiB
Go
Raw Normal View History

2017-03-27 15:07:29 -05:00
package main
import (
"bytes"
"io/ioutil"
"os"
"strconv"
"strings"
)
2018-10-02 20:21:08 -05:00
// NewRanking create a new ranking
2017-03-27 15:07:29 -05:00
func NewRanking() *Ranking {
ranking := &Ranking{
scores: make([]uint64, 9),
2017-03-27 15:07:29 -05:00
}
if _, err := os.Stat(baseDir + rankingFileName); os.IsNotExist(err) {
for i := 0; i < 9; i++ {
2017-03-27 15:07:29 -05:00
ranking.scores[i] = 0
}
return ranking
}
scoreBytes, err := ioutil.ReadFile(baseDir + rankingFileName)
if err != nil {
2018-06-01 10:16:36 -05:00
logger.Println("NewRanking ReadFile error:", err)
2017-03-27 15:07:29 -05:00
}
scoreStrings := strings.Split(string(scoreBytes), ",")
for index, scoreString := range scoreStrings {
if index > 8 {
break
}
2017-03-27 15:07:29 -05:00
score, err := strconv.ParseUint(scoreString, 10, 64)
if err != nil {
2018-06-01 10:16:36 -05:00
logger.Println("NewRanking ParseUint error:", err)
2017-03-27 15:07:29 -05:00
score = 0
}
ranking.scores[index] = score
}
return ranking
}
2018-10-02 20:21:08 -05:00
// Save saves the rankings to a file
2017-03-27 15:07:29 -05:00
func (ranking *Ranking) Save() {
var buffer bytes.Buffer
for i := 0; i < 9; i++ {
2017-03-27 15:07:29 -05:00
if i != 0 {
buffer.WriteRune(',')
}
buffer.WriteString(strconv.FormatUint(ranking.scores[i], 10))
}
ioutil.WriteFile(baseDir+rankingFileName, buffer.Bytes(), 0644)
}
2018-10-02 20:21:08 -05:00
// InsertScore inserts a score into the rankings
2017-03-27 15:07:29 -05:00
func (ranking *Ranking) InsertScore(newScore uint64) {
for index, score := range ranking.scores {
if newScore > score {
ranking.slideScores(index)
ranking.scores[index] = newScore
return
}
}
}
2018-10-02 20:21:08 -05:00
// slideScores slides the scores down to make room for a new score
2017-03-27 15:07:29 -05:00
func (ranking *Ranking) slideScores(index int) {
for i := len(ranking.scores) - 1; i > index; i-- {
ranking.scores[i] = ranking.scores[i-1]
}
}