feat: show random cat picture on results page based on score
This commit is contained in:
@@ -7,7 +7,9 @@ import (
|
||||
"log/slog"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -18,6 +20,9 @@ import (
|
||||
"qbank/internal/sampling"
|
||||
)
|
||||
|
||||
// happyCatThreshold is the minimum score percentage to show a happy cat.
|
||||
const happyCatThreshold = 60
|
||||
|
||||
type TestHandler struct {
|
||||
auth *auth.Manager
|
||||
repo *db.Repo
|
||||
@@ -302,11 +307,18 @@ func (h *TestHandler) ResultsGet(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
mood := "sad"
|
||||
if test.NQuestions > 0 && nCorrect*100/test.NQuestions >= happyCatThreshold {
|
||||
mood = "happy"
|
||||
}
|
||||
catURL := randomCatURL(mood)
|
||||
|
||||
data := BaseData(h.auth, r)
|
||||
data["Test"] = test
|
||||
data["Items"] = items
|
||||
data["NCorrect"] = nCorrect
|
||||
data["TimeTaken"] = timeTaken
|
||||
data["CatURL"] = catURL
|
||||
h.render.Render(w, http.StatusOK, "test_results", data)
|
||||
}
|
||||
|
||||
@@ -342,6 +354,32 @@ func (h *TestHandler) loadTestAndN(w http.ResponseWriter, r *http.Request) (int,
|
||||
return n, test, true
|
||||
}
|
||||
|
||||
// randomCatURL picks a random image from web/static/cats/<mood>/ and returns
|
||||
// its URL path, or an empty string if the folder is missing or empty.
|
||||
func randomCatURL(mood string) string {
|
||||
dir := "web/static/cats/" + mood
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var images []string
|
||||
for _, e := range entries {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
n := strings.ToLower(e.Name())
|
||||
if strings.HasSuffix(n, ".jpg") || strings.HasSuffix(n, ".jpeg") ||
|
||||
strings.HasSuffix(n, ".png") || strings.HasSuffix(n, ".gif") ||
|
||||
strings.HasSuffix(n, ".webp") {
|
||||
images = append(images, e.Name())
|
||||
}
|
||||
}
|
||||
if len(images) == 0 {
|
||||
return ""
|
||||
}
|
||||
return "/static/cats/" + mood + "/" + images[rand.Intn(len(images))]
|
||||
}
|
||||
|
||||
// deterministicShuffle returns a copy of answers shuffled by a seed derived
|
||||
// from the test ID and question ID, so the order is stable across page reloads.
|
||||
func deterministicShuffle(answers []*models.Answer, testID int64, questionID string) []*models.Answer {
|
||||
|
||||
Reference in New Issue
Block a user