81 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			81 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
| package wordloader
 | |
| 
 | |
| import (
 | |
| 	"gralias/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: models.WordColorBlack,
 | |
| 			}
 | |
| 			l.BlackCount--
 | |
| 			continue
 | |
| 		}
 | |
| 		if l.WhiteCount > 0 {
 | |
| 			cards[i] = models.WordCard{
 | |
| 				Word:  word,
 | |
| 				Color: models.WordColorWhite,
 | |
| 			}
 | |
| 			l.WhiteCount--
 | |
| 			continue
 | |
| 		}
 | |
| 		if l.RedCount > 0 {
 | |
| 			cards[i] = models.WordCard{
 | |
| 				Word:  word,
 | |
| 				Color: models.WordColorRed,
 | |
| 			}
 | |
| 			l.RedCount--
 | |
| 			continue
 | |
| 		}
 | |
| 		if l.BlueCount > 0 {
 | |
| 			cards[i] = models.WordCard{
 | |
| 				Word:  word,
 | |
| 				Color: models.WordColorBlue,
 | |
| 			}
 | |
| 			l.BlueCount--
 | |
| 		}
 | |
| 	}
 | |
| 	rand.Shuffle(len(cards), func(i, j int) {
 | |
| 		cards[i], cards[j] = cards[j], cards[i]
 | |
| 	})
 | |
| 	return cards, nil
 | |
| }
 | 
