select random quote and sources

This commit is contained in:
Settel 2021-09-11 14:03:44 +02:00
parent 47199bb6eb
commit f4b027d7a7
4 changed files with 42 additions and 10 deletions

View File

@ -1,6 +1,6 @@
{
"authcode": "",
"name": "Lew Nikolajewitsch Tolstoi",
"name": "Lew N. Tolstoi",
"role": "source",
"game": "067fb1b8-8303-4faa-95d2-1832770a791c"
}

View File

@ -1,6 +1,6 @@
{
"authcode": "",
"name": "Antoine de Saint-Exupéry",
"name": "A. de Saint-Exupéry",
"role": "source",
"game": "067fb1b8-8303-4faa-95d2-1832770a791c"
}

View File

@ -16,3 +16,14 @@ func (gm *Game) getQuoteById(id string) (*quote.Quote, error) {
return quote, nil
}
func (gm *Game) getAllQuotes() []*quote.Quote {
gm.mu.Lock()
defer gm.mu.Unlock()
quotes := make([]*quote.Quote, 0)
for _, quote := range gm.quotes {
quotes = append(quotes, quote)
}
return quotes
}

View File

@ -2,6 +2,9 @@ package game
import (
"fmt"
"math/rand"
"sirlab.de/go/knyt/quote"
"time"
)
func (gm *Game) setupRound() {
@ -20,16 +23,25 @@ func newRound() Round {
}
func (gm *Game) selectQuote() {
quote, err := gm.getQuoteById("455df6bc-070d-4728-83ab-481ceafa8590")
if err != nil {
fmt.Println(err)
return
}
allQuotes := gm.getAllQuotes()
sources := []Source{
gm.getSourceById(quote.GetSourceId()),
}
r := rand.New(rand.NewSource(time.Now().UnixNano()))
var quote *quote.Quote
sources := make([]Source, 0)
for idx, quoteIdx := range r.Perm(len(allQuotes)) {
if idx == 0 {
quote = allQuotes[0]
}
sourceId := allQuotes[quoteIdx].GetSourceId()
if !gm.isSourceIdInList(sources, sourceId) {
sources = append(sources, gm.getSourceById(sourceId))
}
if len(sources) == 12 {
break
}
}
gm.mu.Lock()
defer gm.mu.Unlock()
@ -49,3 +61,12 @@ func (gm *Game) getSourceById(id string) Source {
name: plInfo.name,
}
}
func (gm *Game) isSourceIdInList(sources []Source, sourceId string) bool {
for _, source := range sources {
if source.id == sourceId {
return true
}
}
return false
}