generated from VLADIMIR/template
add AnswerService
This commit is contained in:
@@ -1,33 +0,0 @@
|
||||
package game_service
|
||||
|
||||
import (
|
||||
"evening_detective_server/internal/modules/game_model"
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
)
|
||||
|
||||
// Answer — ответ команды на вопрос дела (для публичного API команды).
|
||||
type Answer struct {
|
||||
QuestionCode string
|
||||
Text string
|
||||
}
|
||||
|
||||
// AnswerScore — ответ команды с баллом организатора (для панели оценки).
|
||||
type AnswerScore struct {
|
||||
QuestionCode string
|
||||
Text string
|
||||
// Score — балл; nil — ещё не оценено.
|
||||
Score *int
|
||||
}
|
||||
|
||||
// TeamAnswers — ответы одной команды игры.
|
||||
type TeamAnswers struct {
|
||||
Team *game_model.Team
|
||||
Answers []AnswerScore
|
||||
}
|
||||
|
||||
// GameAnswers — полная картина для оценки организатором: вопросы сценария
|
||||
// (с правильными ответами) и ответы всех команд с баллами.
|
||||
type GameAnswers struct {
|
||||
Questions []*storytelling.Question
|
||||
Teams []TeamAnswers
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
package game_service
|
||||
|
||||
import (
|
||||
"evening_detective_server/internal/modules/game_model"
|
||||
"sort"
|
||||
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
)
|
||||
|
||||
// TeamResult — строка итоговой таблицы: команда, баллы по вопросам (в порядке
|
||||
// сценария), сумма баллов и место.
|
||||
type TeamResult struct {
|
||||
Team *game_model.Team
|
||||
Answers []AnswerScore
|
||||
// TotalScore — сумма баллов по всем вопросам сценария; неоценённые
|
||||
// вопросы считаются как 0.
|
||||
TotalScore int
|
||||
// Place — место в итоговой таблице. Команды с одинаковой суммой баллов
|
||||
// и одинаковым числом ходов занимают одно место (следующее место
|
||||
// пропускается); проставляется функцией rankTeams.
|
||||
Place int
|
||||
}
|
||||
|
||||
// GameResults — итоговая таблица игры: вопросы сценария (шапка таблицы) и
|
||||
// результаты команд, отсортированные по сумме баллов.
|
||||
type GameResults struct {
|
||||
Questions []*storytelling.Question
|
||||
Teams []TeamResult
|
||||
}
|
||||
|
||||
// buildTeamResults собирает строки итоговой таблицы по командам: баллы в
|
||||
// порядке вопросов сценария (неотвеченный/неоценённый вопрос — с пустым
|
||||
// текстом и Score=nil), сумма баллов (nil считается как 0). Команды в
|
||||
// результате — в порядке переданного списка; сортировку и места делает
|
||||
// rankTeams.
|
||||
func buildTeamResults(
|
||||
questions []*storytelling.Question,
|
||||
teams []*game_model.Team,
|
||||
answerByTeamAndCode map[int]map[string]AnswerScore,
|
||||
) []TeamResult {
|
||||
res := make([]TeamResult, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
byCode := answerByTeamAndCode[team.ID]
|
||||
answers := make([]AnswerScore, 0, len(questions))
|
||||
total := 0
|
||||
for _, question := range questions {
|
||||
answer, ok := byCode[question.Code]
|
||||
if !ok {
|
||||
answers = append(answers, AnswerScore{QuestionCode: question.Code})
|
||||
continue
|
||||
}
|
||||
answers = append(answers, answer)
|
||||
if answer.Score != nil {
|
||||
total += *answer.Score
|
||||
}
|
||||
}
|
||||
res = append(res, TeamResult{
|
||||
Team: team,
|
||||
Answers: answers,
|
||||
TotalScore: total,
|
||||
})
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// rankTeams сортирует строки итоговой таблицы по сумме баллов (убывание);
|
||||
// при равенстве суммы выше команда с меньшим числом ходов. Команды с
|
||||
// одинаковой суммой баллов И одинаковым числом ходов занимают одно место
|
||||
// (следующее место пропускается — схема 1,2,2,4 по ключу (сумма, ходы)).
|
||||
// id команды влияет только на порядок показа внутри группы (меньший id
|
||||
// первым), не на место. Входной срез не изменяется.
|
||||
func rankTeams(rows []TeamResult) []TeamResult {
|
||||
sorted := make([]TeamResult, len(rows))
|
||||
copy(sorted, rows)
|
||||
sort.SliceStable(sorted, func(i, j int) bool {
|
||||
a, b := sorted[i], sorted[j]
|
||||
if a.TotalScore != b.TotalScore {
|
||||
return a.TotalScore > b.TotalScore
|
||||
}
|
||||
if a.Team.ActionsCount != b.Team.ActionsCount {
|
||||
return a.Team.ActionsCount < b.Team.ActionsCount
|
||||
}
|
||||
return a.Team.ID < b.Team.ID
|
||||
})
|
||||
place := 0
|
||||
for i := range sorted {
|
||||
row := sorted[i]
|
||||
if i == 0 || row.TotalScore != sorted[i-1].TotalScore || row.Team.ActionsCount != sorted[i-1].Team.ActionsCount {
|
||||
place = i + 1
|
||||
}
|
||||
sorted[i].Place = place
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
package game_service
|
||||
|
||||
import (
|
||||
"evening_detective_server/internal/modules/game_model"
|
||||
"testing"
|
||||
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
)
|
||||
|
||||
func intPtr(v int) *int { return &v }
|
||||
|
||||
func teamResult(id, actions, total int) TeamResult {
|
||||
return TeamResult{
|
||||
Team: &game_model.Team{ID: id, ActionsCount: actions},
|
||||
TotalScore: total,
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSortsByTotalThenActions(t *testing.T) {
|
||||
// У всех команд разный ключ (сумма, ходы) — места идут подряд 1..N.
|
||||
rows := []TeamResult{
|
||||
teamResult(3, 5, 10),
|
||||
teamResult(1, 3, 10),
|
||||
teamResult(2, 1, 12),
|
||||
teamResult(4, 7, 8),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
wantIDs := []int{2, 1, 3, 4}
|
||||
wantPlaces := []int{1, 2, 3, 4}
|
||||
for i, id := range wantIDs {
|
||||
if got[i].Team.ID != id {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d (порядок: total desc, actions asc)", i, got[i].Team.ID, id)
|
||||
}
|
||||
if got[i].Place != wantPlaces[i] {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want %d", i, got[i].Place, wantPlaces[i])
|
||||
}
|
||||
}
|
||||
// Команды 1 и 3 имеют одинаковую сумму (10), но разные ходы — разные места.
|
||||
if got[1].Place == got[2].Place {
|
||||
t.Fatalf("равные суммы при разных ходах должны давать разные места: places = %d, %d", got[1].Place, got[2].Place)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSharesPlaceOnEqualTotalAndActions(t *testing.T) {
|
||||
// Одинаковая сумма И одинаковое число ходов — одно место у всех трёх.
|
||||
rows := []TeamResult{
|
||||
teamResult(5, 4, 9),
|
||||
teamResult(2, 4, 9),
|
||||
teamResult(7, 4, 9),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
// Внутри группы порядок показа — по id asc (детерминированный).
|
||||
wantIDs := []int{2, 5, 7}
|
||||
for i, id := range wantIDs {
|
||||
if got[i].Team.ID != id {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d (порядок показа внутри группы — id asc)", i, got[i].Team.ID, id)
|
||||
}
|
||||
if got[i].Place != 1 {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want 1 (одно место у равных по сумме и ходам)", i, got[i].Place)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsSkipsPlaceAfterSharedTie(t *testing.T) {
|
||||
// Две команды делят 1-е место, следующая получает 3-е (схема 1,1,3).
|
||||
rows := []TeamResult{
|
||||
teamResult(3, 2, 7),
|
||||
teamResult(1, 5, 10),
|
||||
teamResult(2, 5, 10),
|
||||
teamResult(4, 9, 5),
|
||||
}
|
||||
got := rankTeams(rows)
|
||||
|
||||
wantIDs := []int{1, 2, 3, 4}
|
||||
wantPlaces := []int{1, 1, 3, 4}
|
||||
for i := range wantIDs {
|
||||
if got[i].Team.ID != wantIDs[i] {
|
||||
t.Fatalf("rankTeams[%d].Team.ID = %d, want %d", i, got[i].Team.ID, wantIDs[i])
|
||||
}
|
||||
if got[i].Place != wantPlaces[i] {
|
||||
t.Fatalf("rankTeams[%d].Place = %d, want %d (места 1,1,3,4)", i, got[i].Place, wantPlaces[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRankTeamsDoesNotMutateInput(t *testing.T) {
|
||||
rows := []TeamResult{
|
||||
teamResult(1, 1, 5),
|
||||
teamResult(2, 1, 5),
|
||||
}
|
||||
rankTeams(rows)
|
||||
|
||||
if rows[0].Place != 0 || rows[1].Place != 0 {
|
||||
t.Fatalf("rankTeams изменил входной срез: places = %d, %d; want 0, 0", rows[0].Place, rows[1].Place)
|
||||
}
|
||||
if rows[0].Team.ID != 1 || rows[1].Team.ID != 2 {
|
||||
t.Fatalf("rankTeams изменил порядок входного среза: ids = %d, %d; want 1, 2", rows[0].Team.ID, rows[1].Team.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildTeamResultsScenarioOrderAndNilScores(t *testing.T) {
|
||||
questions := []*storytelling.Question{
|
||||
{Code: "q1", Text: "Вопрос 1"},
|
||||
{Code: "q2", Text: "Вопрос 2"},
|
||||
{Code: "q3", Text: "Вопрос 3"},
|
||||
}
|
||||
teams := []*game_model.Team{
|
||||
{ID: 1, Name: "А", ActionsCount: 4},
|
||||
{ID: 2, Name: "Б", ActionsCount: 2},
|
||||
}
|
||||
answerByTeamAndCode := map[int]map[string]AnswerScore{
|
||||
1: {
|
||||
"q1": {QuestionCode: "q1", Text: "ответ 1", Score: intPtr(5)},
|
||||
"q3": {QuestionCode: "q3", Text: "ответ 3", Score: intPtr(-1)},
|
||||
},
|
||||
2: {
|
||||
"q2": {QuestionCode: "q2", Text: "ответ 2"}, // балл не выставлен
|
||||
},
|
||||
}
|
||||
|
||||
got := buildTeamResults(questions, teams, answerByTeamAndCode)
|
||||
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("len(buildTeamResults) = %d, want 2", len(got))
|
||||
}
|
||||
|
||||
// Команда 1: q1(5), q2 не отвечен, q3(-1) → сумма 4.
|
||||
first := got[0]
|
||||
if first.Team.ID != 1 || first.TotalScore != 4 {
|
||||
t.Fatalf("команда 1: Team.ID = %d, TotalScore = %d; want ID 1, Total 4", first.Team.ID, first.TotalScore)
|
||||
}
|
||||
if len(first.Answers) != 3 {
|
||||
t.Fatalf("команда 1: len(Answers) = %d, want 3 (порядок сценария)", len(first.Answers))
|
||||
}
|
||||
for i, wantCode := range []string{"q1", "q2", "q3"} {
|
||||
if first.Answers[i].QuestionCode != wantCode {
|
||||
t.Fatalf("команда 1: Answers[%d].QuestionCode = %q, want %q", i, first.Answers[i].QuestionCode, wantCode)
|
||||
}
|
||||
}
|
||||
if first.Answers[1].Score != nil || first.Answers[1].Text != "" {
|
||||
t.Fatalf("команда 1: неотвеченный q2 = %+v, want Score=nil и Text=\"\"", first.Answers[1])
|
||||
}
|
||||
|
||||
// Команда 2: все не оценены → сумма 0.
|
||||
second := got[1]
|
||||
if second.Team.ID != 2 || second.TotalScore != 0 {
|
||||
t.Fatalf("команда 2: Team.ID = %d, TotalScore = %d; want ID 2, Total 0", second.Team.ID, second.TotalScore)
|
||||
}
|
||||
if second.Answers[1].Score != nil {
|
||||
t.Fatalf("команда 2: неоценённый q2: Score = %v, want nil", second.Answers[1].Score)
|
||||
}
|
||||
}
|
||||
@@ -6,12 +6,10 @@ import (
|
||||
"evening_detective_server/internal/modules/cleaner"
|
||||
"evening_detective_server/internal/modules/game_model"
|
||||
"evening_detective_server/internal/modules/storytelling"
|
||||
"evening_detective_server/internal/repos"
|
||||
"evening_detective_server/internal/repos/actions_repo"
|
||||
"evening_detective_server/internal/repos/applications_repo"
|
||||
"evening_detective_server/internal/repos/games_repo"
|
||||
"evening_detective_server/internal/repos/scenarios_repo"
|
||||
"evening_detective_server/internal/repos/team_answers_repo"
|
||||
"evening_detective_server/internal/repos/teams_repo"
|
||||
"evening_detective_server/internal/services/scenarios_service"
|
||||
"time"
|
||||
@@ -26,7 +24,6 @@ type GameService struct {
|
||||
storyteller storytelling.IStory
|
||||
actionsRepo *actions_repo.ActionsRepo
|
||||
applicationsRepo *applications_repo.ApplicationsRepo
|
||||
answersRepo *team_answers_repo.TeamAnswersRepo
|
||||
cleaner cleaner.ICleaner
|
||||
}
|
||||
|
||||
@@ -39,7 +36,6 @@ func NewGameService(
|
||||
storyteller storytelling.IStory,
|
||||
actionsRepo *actions_repo.ActionsRepo,
|
||||
applicationsRepo *applications_repo.ApplicationsRepo,
|
||||
answersRepo *team_answers_repo.TeamAnswersRepo,
|
||||
cleaner cleaner.ICleaner,
|
||||
) *GameService {
|
||||
return &GameService{
|
||||
@@ -51,7 +47,6 @@ func NewGameService(
|
||||
storyteller: storyteller,
|
||||
actionsRepo: actionsRepo,
|
||||
applicationsRepo: applicationsRepo,
|
||||
answersRepo: answersRepo,
|
||||
cleaner: cleaner,
|
||||
}
|
||||
}
|
||||
@@ -334,258 +329,3 @@ func (s *GameService) DeleteLastTeamAction(ctx context.Context, teamId int) erro
|
||||
|
||||
return s.actionsRepo.DeleteLastActionByTeamId(ctx, teamId)
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrGameFinished — после завершения игры ответы команд больше нельзя
|
||||
// изменять: организатор оценивает их в панели игры.
|
||||
ErrGameFinished = errors.New("Игра завершена, ответы больше нельзя изменять")
|
||||
// ErrGameNotStarted — игра ещё не начата, отвечать на вопросы нельзя.
|
||||
ErrGameNotStarted = errors.New("Игра не начата, отвечать на вопросы нельзя")
|
||||
// ErrQuestionNotFound — вопрос с таким кодом отсутствует в сценарии игры.
|
||||
ErrQuestionNotFound = errors.New("Вопрос не найден")
|
||||
// ErrGameNotFinished — итоги игры доступны только после её завершения.
|
||||
ErrGameNotFinished = errors.New("Итоги доступны после завершения игры")
|
||||
)
|
||||
|
||||
// getTeamAndGame проверяет команду по паролю и возвращает её вместе с игрой.
|
||||
func (s *GameService) getTeamAndGame(ctx context.Context, teamId int, password string) (*repos.Team, *repos.Game, error) {
|
||||
team, err := s.teamsRepo.GetTeamByID(ctx, teamId)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if team.Password != password || team.ParticipationStatus == "cancelled" {
|
||||
return nil, nil, teams_repo.ErrTeamNotFound
|
||||
}
|
||||
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return team, game, nil
|
||||
}
|
||||
|
||||
// getScenarioQuestionsByCode возвращает вопросы сценария игры с индексацией по коду.
|
||||
func (s *GameService) getScenarioQuestionsByCode(ctx context.Context, scenarioId int) ([]*storytelling.Question, map[string]*storytelling.Question, error) {
|
||||
scenario, err := s.scenarioService.GetFullScenarioByID(ctx, scenarioId)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
byCode := make(map[string]*storytelling.Question, len(scenario.Story.Questions))
|
||||
for _, question := range scenario.Story.Questions {
|
||||
byCode[question.Code] = question
|
||||
}
|
||||
return scenario.Story.Questions, byCode, nil
|
||||
}
|
||||
|
||||
// GetTeamAnswers возвращает ответы команды на вопросы дела (без баллов:
|
||||
// баллы видны только организаторам). Ответы на удалённые из сценария
|
||||
// вопросы не возвращаются.
|
||||
func (s *GameService) GetTeamAnswers(ctx context.Context, teamId int, password string) ([]Answer, error) {
|
||||
_, game, err := s.getTeamAndGame(ctx, teamId, password)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if game.Format == "offline" {
|
||||
return nil, nil
|
||||
}
|
||||
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teamAnswers, err := s.answersRepo.GetAnswersByTeamID(ctx, teamId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
answers := make([]Answer, 0, len(teamAnswers))
|
||||
for _, teamAnswer := range teamAnswers {
|
||||
if _, ok := byCode[teamAnswer.QuestionCode]; !ok {
|
||||
continue
|
||||
}
|
||||
answers = append(answers, Answer{
|
||||
QuestionCode: teamAnswer.QuestionCode,
|
||||
Text: teamAnswer.Text,
|
||||
})
|
||||
}
|
||||
return answers, nil
|
||||
}
|
||||
|
||||
// SubmitTeamAnswers сохраняет ответы команды на вопросы дела (upsert).
|
||||
// Доступно только пока игра идёт (статусы run/pause): после завершения
|
||||
// ответы фиксируются для оценки организатором. Переданные коды должны
|
||||
// существовать в сценарии игры; пустая строка очищает ответ.
|
||||
func (s *GameService) SubmitTeamAnswers(ctx context.Context, teamId int, password string, answers []Answer) error {
|
||||
_, game, err := s.getTeamAndGame(ctx, teamId, password)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if game.Format == "offline" {
|
||||
return errors.New("В offline-игре ответы через сайт недоступны")
|
||||
}
|
||||
switch game.Status {
|
||||
case "run", "pause":
|
||||
// игра идёт — можно отвечать
|
||||
default:
|
||||
if game.Status == "finish" {
|
||||
return ErrGameFinished
|
||||
}
|
||||
return ErrGameNotStarted
|
||||
}
|
||||
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows := make([]repos.TeamAnswer, 0, len(answers))
|
||||
for _, answer := range answers {
|
||||
if _, ok := byCode[answer.QuestionCode]; !ok {
|
||||
return ErrQuestionNotFound
|
||||
}
|
||||
rows = append(rows, repos.TeamAnswer{
|
||||
QuestionCode: answer.QuestionCode,
|
||||
Text: answer.Text,
|
||||
})
|
||||
}
|
||||
return s.answersRepo.UpsertAnswers(ctx, teamId, rows)
|
||||
}
|
||||
|
||||
// GetGameAnswers возвращает полную картину для оценки организатором:
|
||||
// вопросы сценария с правильными ответами и ответы всех команд с баллами.
|
||||
// Команда может не дать ответ на вопрос — такой вопрос попадает в список
|
||||
// ответов команды с пустым текстом и без балла (организатор видит его и
|
||||
// может выставить балл, в т.ч. штрафной). Ответы на удалённые из сценария
|
||||
// вопросы не возвращаются (как в GetTeamAnswers).
|
||||
func (s *GameService) GetGameAnswers(ctx context.Context, gameId int) (*GameAnswers, error) {
|
||||
game, err := s.gamesRepo.GetGameByID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
answerByTeamAndCode := make(map[int]map[string]AnswerScore, len(teams))
|
||||
for _, row := range rows {
|
||||
if _, ok := byCode[row.QuestionCode]; !ok {
|
||||
continue
|
||||
}
|
||||
score := row.Score
|
||||
if answerByTeamAndCode[row.TeamId] == nil {
|
||||
answerByTeamAndCode[row.TeamId] = make(map[string]AnswerScore, len(questions))
|
||||
}
|
||||
answerByTeamAndCode[row.TeamId][row.QuestionCode] = AnswerScore{
|
||||
QuestionCode: row.QuestionCode,
|
||||
Text: row.Text,
|
||||
Score: score,
|
||||
}
|
||||
}
|
||||
teamAnswers := make([]TeamAnswers, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
byCode := answerByTeamAndCode[team.ID]
|
||||
// Все вопросы сценария в порядке сценария; неотвеченные — с пустым
|
||||
// текстом и без балла, чтобы организатор видел пропуски.
|
||||
answers := make([]AnswerScore, 0, len(questions))
|
||||
for _, question := range questions {
|
||||
if answer, ok := byCode[question.Code]; ok {
|
||||
answers = append(answers, answer)
|
||||
continue
|
||||
}
|
||||
answers = append(answers, AnswerScore{QuestionCode: question.Code})
|
||||
}
|
||||
teamAnswers = append(teamAnswers, TeamAnswers{
|
||||
Team: game_model.MapTeam(team),
|
||||
Answers: answers,
|
||||
})
|
||||
}
|
||||
return &GameAnswers{
|
||||
Questions: questions,
|
||||
Teams: teamAnswers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// SetTeamAnswerScore выставляет балл команде за ответ на вопрос дела;
|
||||
// score == nil сбрасывает балл. Балл может быть любым целым числом
|
||||
// (в т.ч. отрицательным — штрафные баллы). Вопрос должен существовать
|
||||
// в сценарии игры.
|
||||
func (s *GameService) SetTeamAnswerScore(ctx context.Context, teamId int, questionCode string, score *int) error {
|
||||
team, err := s.teamsRepo.GetTeamByID(ctx, teamId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
game, err := s.gamesRepo.GetGameByID(ctx, team.GameId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := byCode[questionCode]; !ok {
|
||||
return ErrQuestionNotFound
|
||||
}
|
||||
return s.answersRepo.SetAnswerScore(ctx, teamId, questionCode, score)
|
||||
}
|
||||
|
||||
// GetGameResults возвращает итоговую таблицу игры: вопросы сценария (шапка
|
||||
// таблицы, без правильных ответов) и команды, отсортированные по сумме
|
||||
// баллов, с баллами по каждому вопросу (в порядке сценария), числом ходов и
|
||||
// местом. Доступно только после завершения игры (статус finish); неоценённые
|
||||
// вопросы в сумме считаются как 0.
|
||||
func (s *GameService) GetGameResults(ctx context.Context, gameId int) (*GameResults, error) {
|
||||
game, err := s.gamesRepo.GetGameByID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if game.Status != "finish" {
|
||||
return nil, ErrGameNotFinished
|
||||
}
|
||||
questions, byCode, err := s.getScenarioQuestionsByCode(ctx, game.ScenarioId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teams, err := s.teamsRepo.GetActiveTeamsByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
teamIds := make([]int, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
teamIds = append(teamIds, team.ID)
|
||||
}
|
||||
actionsCountByTeamIDs, err := s.actionsRepo.GetActionsCountByTeamIDs(ctx, teamIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows, err := s.answersRepo.GetAnswersByGameID(ctx, gameId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
answerByTeamAndCode := make(map[int]map[string]AnswerScore, len(teams))
|
||||
for _, row := range rows {
|
||||
if _, ok := byCode[row.QuestionCode]; !ok {
|
||||
continue
|
||||
}
|
||||
if answerByTeamAndCode[row.TeamId] == nil {
|
||||
answerByTeamAndCode[row.TeamId] = make(map[string]AnswerScore, len(questions))
|
||||
}
|
||||
answerByTeamAndCode[row.TeamId][row.QuestionCode] = AnswerScore{
|
||||
QuestionCode: row.QuestionCode,
|
||||
Text: row.Text,
|
||||
Score: row.Score,
|
||||
}
|
||||
}
|
||||
mappedTeams := make([]*game_model.Team, 0, len(teams))
|
||||
for _, team := range teams {
|
||||
mapped := game_model.MapTeam(team)
|
||||
mapped.ActionsCount = actionsCountByTeamIDs[team.ID]
|
||||
mappedTeams = append(mappedTeams, mapped)
|
||||
}
|
||||
return &GameResults{
|
||||
Questions: questions,
|
||||
Teams: rankTeams(buildTeamResults(questions, mappedTeams, answerByTeamAndCode)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user