/
quiz.go
88 lines (79 loc) · 1.93 KB
/
quiz.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package models
import (
"context"
"math/rand"
"github.com/zmb3/spotify/v2"
)
type Answer struct {
Artist string `json:"artist"`
Song string `json:"song"`
AnswerID int `json:"answerId"`
}
type Question struct {
Question string `json:"question"`
Answers []Answer `json:"answers"`
Correct int `json:"correct"`
}
// ONLY CALL THIS ONCE SPOTIFY API SLOW
func (l *Lobby) GenerateQuiz(length int) []Question {
questions, answers := l.GenerateQuizSongs(length)
// Convert to questions
ret := []Question{}
for _, q := range questions {
correct := rand.Intn(3)
qanswers := []Answer{}
for i, a := range answers[:4] {
qanswers = append(qanswers, Answer{
AnswerID: i,
Song: a.Name,
Artist: a.Artists[0].Name,
})
}
qanswers[correct] = Answer{
Artist: q.Artists[0].Name,
Song: q.Name,
AnswerID: correct,
}
question := Question{
Question: q.PreviewURL,
Answers: qanswers,
Correct: correct,
}
ret = append(ret, question)
rand.Shuffle(len(answers), func(i int, j int) {
temp := answers[i]
answers[i] = answers[j]
answers[j] = temp
})
}
return ret
}
func (l *Lobby) GenerateQuizSongs(length int) ([]spotify.FullTrack, []spotify.FullTrack) {
// in honour of Stephen Piddock
songsExist := map[string]bool{}
allSongs := []spotify.FullTrack{}
l.mu.Lock()
defer l.mu.Unlock()
for _, p := range l.PlayerList {
// Fetch top songs from each player and push to map
songs, err := p.Client.CurrentUsersTopTracks(context.Background())
if err != nil {
continue
}
// Append songs
for _, s := range songs.Tracks {
if !songsExist[s.ID.String()] {
songsExist[s.ID.String()] = true
allSongs = append(allSongs, s)
}
}
}
// Shuffle the songs
length = min(length, len(allSongs))
rand.Shuffle(len(allSongs), func(i int, j int) {
temp := allSongs[i]
allSongs[i] = allSongs[j]
allSongs[j] = temp
})
return allSongs[:length], allSongs[length+1:]
}