card_id/common/game/game.go

69 lines
1.5 KiB
Go
Raw Normal View History

2022-04-13 07:48:22 +00:00
package game
import (
"log"
"path"
"strconv"
"git.tuxpa.in/a/card_id/common/data"
"git.tuxpa.in/a/card_id/common/game/level"
"git.tuxpa.in/a/card_id/common/game/table"
"lukechampine.com/frand"
)
type Game struct {
Levels map[string]*level.Level
TotalProbability float64
}
func NewFromRoot(datadir string) (*Game, error) {
out := &Game{
Levels: make(map[string]*level.Level, 12),
}
if datadir == "" {
datadir = "./data"
}
grades, err := data.NewGradesFromFile(path.Join(datadir, "GradeInfo.yaml"))
if err != nil {
return nil, err
}
for _, v := range grades {
lvl := &level.Level{}
lvl.Name = strconv.Itoa(v.Grade)
out.Levels[lvl.Name] = lvl
lvl.SelectionWeight = v.Rate
out.TotalProbability = out.TotalProbability + v.Rate
rres, err := data.NewResultsFromFile(path.Join(datadir, "ResultTable", lvl.Name+".yaml"))
if err != nil {
return nil, err
}
lvl.RewardTable = table.New(rres)
if v.SpecialRate > 0 {
lvl.SpecialChance = v.SpecialRate
sres, err := data.NewResultsFromFile(path.Join(datadir, "SpecialTable", lvl.Name+".yaml"))
if err != nil {
return nil, err
}
lvl.SpecialTable = table.New(sres)
}
}
return out, nil
}
func (g *Game) RandomLevel() *level.Level {
selector := frand.Float64() * g.TotalProbability
sofar := 0.0
if len(g.Levels) == 0 {
return nil
}
for _, v := range g.Levels {
sofar = sofar + v.SelectionWeight
if sofar >= selector-0.000000001 {
return v
}
}
log.Println("BAD BAD BAD BAD BAD BAD PLEASE REPORT OH NO OH NO OH FISJAFIJNSAF")
return g.RandomLevel()
}