@@ -0,0 +1,279 @@
|
||||
from decimal import Decimal
|
||||
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from accounts.models import User
|
||||
from .models import (
|
||||
CheatFlag,
|
||||
Contest,
|
||||
ContestAnswer,
|
||||
ContestAttempt,
|
||||
RatingHistory,
|
||||
RealtimeMatch,
|
||||
)
|
||||
|
||||
|
||||
def normalize_answer(value):
|
||||
text = str(value).strip().lower().replace(" ", "")
|
||||
try:
|
||||
return str(Decimal(text).normalize())
|
||||
except Exception:
|
||||
return text
|
||||
|
||||
|
||||
def attempt_payload(attempt, include_results=False):
|
||||
questions = []
|
||||
answers = {answer.contest_question_id: answer for answer in attempt.answers.all()}
|
||||
for item in attempt.contest.contest_questions.select_related("question_version").all():
|
||||
question = {
|
||||
"order": item.order,
|
||||
"prompt": item.question_version.prompt,
|
||||
"metadata": item.question_version.metadata,
|
||||
"points": item.points,
|
||||
}
|
||||
if include_results and item.id in answers:
|
||||
answer = answers[item.id]
|
||||
question.update(
|
||||
{
|
||||
"submitted_answer": answer.submitted_answer,
|
||||
"is_correct": answer.is_correct,
|
||||
"correct_answer": item.question_version.answer,
|
||||
"explanation": item.question_version.explanation,
|
||||
}
|
||||
)
|
||||
questions.append(question)
|
||||
return {
|
||||
"attempt_id": attempt.id,
|
||||
"contest": attempt.contest.title,
|
||||
"kind": attempt.contest.kind,
|
||||
"status": attempt.status,
|
||||
"duration_seconds": attempt.contest.duration_seconds,
|
||||
"server_started_at": attempt.started_at,
|
||||
"score": attempt.score,
|
||||
"correct_count": attempt.correct_count,
|
||||
"answer_count": attempt.answer_count,
|
||||
"duration_ms": attempt.duration_ms,
|
||||
"questions": questions,
|
||||
}
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def start_attempt(user, contest):
|
||||
now = timezone.now()
|
||||
if contest.status != Contest.Status.PUBLISHED:
|
||||
raise ValidationError("比赛尚未发布")
|
||||
if contest.starts_at and contest.starts_at > now:
|
||||
raise ValidationError("比赛尚未开始")
|
||||
if contest.ends_at and contest.ends_at <= now:
|
||||
raise ValidationError("比赛已经结束")
|
||||
if contest.kind == Contest.Kind.DAILY:
|
||||
existing = ContestAttempt.objects.filter(user=user, contest=contest).first()
|
||||
if existing:
|
||||
return attempt_payload(
|
||||
existing,
|
||||
include_results=existing.status != ContestAttempt.Status.ACTIVE,
|
||||
)
|
||||
attempt = ContestAttempt.objects.create(contest=contest, user=user)
|
||||
return attempt_payload(attempt)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def submit_attempt(user, attempt_id, raw_answers, submission_key):
|
||||
attempt = (
|
||||
ContestAttempt.objects.select_for_update()
|
||||
.select_related("contest")
|
||||
.get(id=attempt_id, user=user)
|
||||
)
|
||||
if attempt.status != ContestAttempt.Status.ACTIVE:
|
||||
if submission_key and attempt.submission_key == submission_key:
|
||||
return attempt_payload(attempt, include_results=True)
|
||||
raise ValidationError("该答题记录已经结算")
|
||||
if not submission_key:
|
||||
raise ValidationError({"Idempotency-Key": "正式提交必须提供幂等键"})
|
||||
|
||||
now = timezone.now()
|
||||
duration_ms = max(0, int((now - attempt.started_at).total_seconds() * 1000))
|
||||
limit_ms = attempt.contest.duration_seconds * 1000
|
||||
items = list(
|
||||
attempt.contest.contest_questions.select_related("question_version").all()
|
||||
)
|
||||
if not isinstance(raw_answers, list):
|
||||
raise ValidationError({"answers": "答案必须是数组"})
|
||||
by_order = {}
|
||||
try:
|
||||
for item in raw_answers:
|
||||
order = int(item["order"])
|
||||
if order <= 0 or order in by_order:
|
||||
raise ValueError
|
||||
by_order[order] = item.get("answer", "")
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValidationError({"answers": "答案题号无效或重复"}) from exc
|
||||
score = 0
|
||||
correct_count = 0
|
||||
for contest_question in items:
|
||||
submitted = str(by_order.get(contest_question.order, ""))[:200]
|
||||
correct = normalize_answer(submitted) == normalize_answer(
|
||||
contest_question.question_version.answer
|
||||
)
|
||||
if correct and duration_ms <= limit_ms:
|
||||
score += contest_question.points
|
||||
correct_count += 1
|
||||
ContestAnswer.objects.create(
|
||||
attempt=attempt,
|
||||
contest_question=contest_question,
|
||||
submitted_answer=submitted,
|
||||
is_correct=correct and duration_ms <= limit_ms,
|
||||
elapsed_ms=min(duration_ms, limit_ms + 60_000),
|
||||
)
|
||||
|
||||
attempt.status = (
|
||||
ContestAttempt.Status.SUBMITTED
|
||||
if duration_ms <= limit_ms
|
||||
else ContestAttempt.Status.EXPIRED
|
||||
)
|
||||
attempt.score = score
|
||||
attempt.correct_count = correct_count
|
||||
attempt.answer_count = len(raw_answers)
|
||||
attempt.duration_ms = duration_ms
|
||||
attempt.submission_key = submission_key
|
||||
attempt.submitted_at = now
|
||||
attempt.save()
|
||||
|
||||
if raw_answers and duration_ms / len(raw_answers) < 150:
|
||||
CheatFlag.objects.create(
|
||||
attempt=attempt,
|
||||
reason="extreme_answer_speed",
|
||||
evidence={
|
||||
"duration_ms": duration_ms,
|
||||
"answer_count": len(raw_answers),
|
||||
},
|
||||
)
|
||||
if attempt.match_id:
|
||||
finalize_match(attempt.match_id)
|
||||
return attempt_payload(attempt, include_results=True)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def find_match(user, contest):
|
||||
if contest.kind != Contest.Kind.REALTIME or contest.status != Contest.Status.PUBLISHED:
|
||||
raise ValidationError("实时比赛不可用")
|
||||
existing = (
|
||||
RealtimeMatch.objects.filter(
|
||||
Q(player_one=user) | Q(player_two=user),
|
||||
contest=contest,
|
||||
status__in=[RealtimeMatch.Status.WAITING, RealtimeMatch.Status.ACTIVE],
|
||||
)
|
||||
.order_by("-created_at")
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
waiting = (
|
||||
RealtimeMatch.objects.select_for_update(skip_locked=True)
|
||||
.filter(
|
||||
contest=contest,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
player_one_rating__gte=max(0, user.rating - 300),
|
||||
player_one_rating__lte=user.rating + 300,
|
||||
)
|
||||
.exclude(player_one=user)
|
||||
.order_by("created_at")
|
||||
.first()
|
||||
)
|
||||
if waiting is None:
|
||||
return RealtimeMatch.objects.create(
|
||||
contest=contest,
|
||||
player_one=user,
|
||||
player_one_rating=user.rating,
|
||||
)
|
||||
|
||||
waiting.player_two = user
|
||||
waiting.player_two_rating = user.rating
|
||||
waiting.status = RealtimeMatch.Status.ACTIVE
|
||||
waiting.started_at = timezone.now()
|
||||
waiting.save(
|
||||
update_fields=["player_two", "player_two_rating", "status", "started_at"]
|
||||
)
|
||||
ContestAttempt.objects.bulk_create(
|
||||
[
|
||||
ContestAttempt(contest=contest, user=waiting.player_one, match=waiting),
|
||||
ContestAttempt(contest=contest, user=user, match=waiting),
|
||||
]
|
||||
)
|
||||
return waiting
|
||||
|
||||
|
||||
def match_payload(match, user):
|
||||
attempt = match.attempts.filter(user=user).first()
|
||||
opponent = match.player_two if match.player_one_id == user.id else match.player_one
|
||||
return {
|
||||
"match_id": match.id,
|
||||
"status": match.status,
|
||||
"opponent": (
|
||||
{"nickname": opponent.nickname, "rating": opponent.rating}
|
||||
if opponent
|
||||
else None
|
||||
),
|
||||
"attempt": attempt_payload(attempt) if attempt else None,
|
||||
"websocket_path": f"/ws/v1/contest/matches/{match.id}/",
|
||||
}
|
||||
|
||||
|
||||
def _elo_delta(rating, opponent_rating, score, k=32):
|
||||
expected = 1 / (1 + 10 ** ((opponent_rating - rating) / 400))
|
||||
return round(k * (score - expected))
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def finalize_match(match_id):
|
||||
match = RealtimeMatch.objects.select_for_update().get(id=match_id)
|
||||
if match.status != RealtimeMatch.Status.ACTIVE:
|
||||
return match
|
||||
attempts = list(match.attempts.select_related("user").order_by("user_id"))
|
||||
if len(attempts) != 2 or any(
|
||||
attempt.status == ContestAttempt.Status.ACTIVE for attempt in attempts
|
||||
):
|
||||
return match
|
||||
|
||||
first = next(item for item in attempts if item.user_id == match.player_one_id)
|
||||
second = next(item for item in attempts if item.user_id == match.player_two_id)
|
||||
if first.score > second.score:
|
||||
first_result, second_result = 1.0, 0.0
|
||||
match.winner_id = first.user_id
|
||||
elif second.score > first.score:
|
||||
first_result, second_result = 0.0, 1.0
|
||||
match.winner_id = second.user_id
|
||||
else:
|
||||
first_result = second_result = 0.5
|
||||
|
||||
users = {
|
||||
user.id: user
|
||||
for user in User.objects.select_for_update().filter(
|
||||
id__in=[match.player_one_id, match.player_two_id]
|
||||
)
|
||||
}
|
||||
player_one = users[match.player_one_id]
|
||||
player_two = users[match.player_two_id]
|
||||
deltas = (
|
||||
_elo_delta(player_one.rating, player_two.rating, first_result),
|
||||
_elo_delta(player_two.rating, player_one.rating, second_result),
|
||||
)
|
||||
for user, delta in zip((player_one, player_two), deltas):
|
||||
before = user.rating
|
||||
user.rating = max(0, before + delta)
|
||||
user.save(update_fields=["rating"])
|
||||
RatingHistory.objects.create(
|
||||
user=user,
|
||||
match=match,
|
||||
rating_before=before,
|
||||
rating_after=user.rating,
|
||||
delta=delta,
|
||||
)
|
||||
match.status = RealtimeMatch.Status.COMPLETED
|
||||
match.completed_at = timezone.now()
|
||||
match.save(update_fields=["winner", "status", "completed_at"])
|
||||
return match
|
||||
Reference in New Issue
Block a user