Files
golias/wordloader/wordloader.go
2025-05-13 07:49:16 +03:00

81 lines
1.4 KiB
Go

package wordloader
import (
"golias/models"
"math/rand/v2"
"os"
"strings"
)
type Loader struct {
FilePath string
BlackCount uint8
WhiteCount uint8
RedCount uint8
BlueCount uint8
}
func InitDefaultLoader(fpath string) *Loader {
return &Loader{
FilePath: fpath,
BlackCount: 1,
WhiteCount: 7,
RedCount: 8,
BlueCount: 9,
}
}
func (l *Loader) WholeCount() uint8 {
return l.BlackCount + l.WhiteCount + l.RedCount + l.BlueCount
}
func (l *Loader) Load() ([]models.WordCard, error) {
data, err := os.ReadFile(l.FilePath)
if err != nil {
return nil, err
}
lines := strings.Split(string(data), "\n")
rand.Shuffle(len(lines), func(i, j int) {
lines[i], lines[j] = lines[j], lines[i]
})
words := lines[:int(l.WholeCount())]
cards := make([]models.WordCard, l.WholeCount())
for i, word := range words {
if l.BlackCount > 0 {
cards[i] = models.WordCard{
Word: word,
Color: "black",
}
l.BlackCount--
continue
}
if l.WhiteCount > 0 {
cards[i] = models.WordCard{
Word: word,
Color: "white",
}
l.WhiteCount--
continue
}
if l.RedCount > 0 {
cards[i] = models.WordCard{
Word: word,
Color: "red",
}
l.RedCount--
continue
}
if l.BlueCount > 0 {
cards[i] = models.WordCard{
Word: word,
Color: "blue",
}
l.BlueCount--
}
}
rand.Shuffle(len(cards), func(i, j int) {
cards[i], cards[j] = cards[j], cards[i]
})
return cards, nil
}