feat: complete realtime challenge matchmaking
This commit is contained in:
+292
-24
@@ -1,5 +1,9 @@
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from asgiref.sync import async_to_sync
|
||||
from channels.layers import get_channel_layer
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
@@ -16,6 +20,93 @@ from .models import (
|
||||
RealtimeMatch,
|
||||
)
|
||||
|
||||
CHALLENGE_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
WAITING_MATCH_TTL = timedelta(minutes=10)
|
||||
|
||||
|
||||
def _broadcast_match(match_id, reason):
|
||||
channel_layer = get_channel_layer()
|
||||
if channel_layer is None:
|
||||
return
|
||||
async_to_sync(channel_layer.group_send)(
|
||||
f"match_{match_id}",
|
||||
{
|
||||
"type": "match.state",
|
||||
"reason": reason,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def notify_match_on_commit(match_id, reason):
|
||||
transaction.on_commit(lambda: _broadcast_match(match_id, reason))
|
||||
|
||||
|
||||
def _new_challenge_code():
|
||||
for _ in range(20):
|
||||
code = "".join(secrets.choice(CHALLENGE_CODE_ALPHABET) for _ in range(6))
|
||||
if not RealtimeMatch.objects.filter(challenge_code=code).exists():
|
||||
return code
|
||||
raise ValidationError("暂时无法生成联机码,请稍后重试")
|
||||
|
||||
|
||||
def _validate_realtime_contest(contest):
|
||||
if contest.kind != Contest.Kind.REALTIME or contest.status != Contest.Status.PUBLISHED:
|
||||
raise ValidationError("实时比赛不可用")
|
||||
|
||||
|
||||
def _cancel_expired_waiting_matches():
|
||||
RealtimeMatch.objects.filter(status=RealtimeMatch.Status.WAITING).filter(
|
||||
Q(expires_at__isnull=True) | Q(expires_at__lte=timezone.now())
|
||||
).update(status=RealtimeMatch.Status.CANCELLED)
|
||||
|
||||
|
||||
def _active_match_for(user):
|
||||
return (
|
||||
RealtimeMatch.objects.filter(
|
||||
Q(player_one=user) | Q(player_two=user),
|
||||
status=RealtimeMatch.Status.ACTIVE,
|
||||
)
|
||||
.select_related("contest", "player_one", "player_two")
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _cancel_other_waiting_matches(user, match_type):
|
||||
matches = list(
|
||||
RealtimeMatch.objects.filter(
|
||||
player_one=user,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
)
|
||||
.exclude(match_type=match_type)
|
||||
.values_list("id", flat=True)
|
||||
)
|
||||
if matches:
|
||||
RealtimeMatch.objects.filter(id__in=matches).update(
|
||||
status=RealtimeMatch.Status.CANCELLED
|
||||
)
|
||||
for match_id in matches:
|
||||
notify_match_on_commit(match_id, "cancelled")
|
||||
|
||||
|
||||
def _activate_match(match, user):
|
||||
now = timezone.now()
|
||||
match.player_two = user
|
||||
match.player_two_rating = user.rating
|
||||
match.status = RealtimeMatch.Status.ACTIVE
|
||||
match.started_at = now
|
||||
match.save(
|
||||
update_fields=["player_two", "player_two_rating", "status", "started_at"]
|
||||
)
|
||||
ContestAttempt.objects.bulk_create(
|
||||
[
|
||||
ContestAttempt(contest=match.contest, user=match.player_one, match=match),
|
||||
ContestAttempt(contest=match.contest, user=user, match=match),
|
||||
]
|
||||
)
|
||||
match.attempts.update(started_at=now)
|
||||
notify_match_on_commit(match.id, "matched")
|
||||
return match
|
||||
|
||||
|
||||
def normalize_answer(value):
|
||||
text = str(value).strip().lower().replace(" ", "")
|
||||
@@ -35,12 +126,12 @@ def attempt_payload(attempt, include_results=False):
|
||||
"metadata": item.question_version.metadata,
|
||||
"points": item.points,
|
||||
}
|
||||
if include_results and item.id in answers:
|
||||
answer = answers[item.id]
|
||||
if include_results:
|
||||
answer = answers.get(item.id)
|
||||
question.update(
|
||||
{
|
||||
"submitted_answer": answer.submitted_answer,
|
||||
"is_correct": answer.is_correct,
|
||||
"submitted_answer": answer.submitted_answer if answer else "",
|
||||
"is_correct": answer.is_correct if answer else False,
|
||||
"correct_answer": item.question_version.answer,
|
||||
"explanation": item.question_version.explanation,
|
||||
}
|
||||
@@ -48,6 +139,7 @@ def attempt_payload(attempt, include_results=False):
|
||||
questions.append(question)
|
||||
return {
|
||||
"attempt_id": attempt.id,
|
||||
"match_id": attempt.match_id,
|
||||
"contest": attempt.contest.title,
|
||||
"kind": attempt.contest.kind,
|
||||
"status": attempt.status,
|
||||
@@ -90,7 +182,10 @@ def submit_attempt(user, attempt_id, raw_answers, submission_key):
|
||||
)
|
||||
if attempt.status != ContestAttempt.Status.ACTIVE:
|
||||
if submission_key and attempt.submission_key == submission_key:
|
||||
return attempt_payload(attempt, include_results=True)
|
||||
include_results = not attempt.match_id or (
|
||||
attempt.match.status == RealtimeMatch.Status.COMPLETED
|
||||
)
|
||||
return attempt_payload(attempt, include_results=include_results)
|
||||
raise ValidationError("该答题记录已经结算")
|
||||
if not submission_key:
|
||||
raise ValidationError({"Idempotency-Key": "正式提交必须提供幂等键"})
|
||||
@@ -153,20 +248,34 @@ def submit_attempt(user, attempt_id, raw_answers, submission_key):
|
||||
},
|
||||
)
|
||||
if attempt.match_id:
|
||||
finalize_match(attempt.match_id)
|
||||
match = finalize_match(attempt.match_id)
|
||||
if match.status != RealtimeMatch.Status.COMPLETED:
|
||||
notify_match_on_commit(attempt.match_id, "submitted")
|
||||
attempt.match.refresh_from_db()
|
||||
return attempt_payload(
|
||||
attempt,
|
||||
include_results=attempt.match.status == RealtimeMatch.Status.COMPLETED,
|
||||
)
|
||||
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("实时比赛不可用")
|
||||
_validate_realtime_contest(contest)
|
||||
_cancel_expired_waiting_matches()
|
||||
active = _active_match_for(user)
|
||||
if active:
|
||||
if active.contest_id == contest.id:
|
||||
return active
|
||||
raise ValidationError("你已有一场进行中的实时比赛")
|
||||
_cancel_other_waiting_matches(user, RealtimeMatch.MatchType.RANDOM)
|
||||
existing = (
|
||||
RealtimeMatch.objects.filter(
|
||||
Q(player_one=user) | Q(player_two=user),
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
status__in=[RealtimeMatch.Status.WAITING, RealtimeMatch.Status.ACTIVE],
|
||||
)
|
||||
).filter(Q(status=RealtimeMatch.Status.ACTIVE) | Q(expires_at__gt=timezone.now()))
|
||||
.order_by("-created_at")
|
||||
.first()
|
||||
)
|
||||
@@ -177,7 +286,9 @@ def find_match(user, contest):
|
||||
RealtimeMatch.objects.select_for_update(skip_locked=True)
|
||||
.filter(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
expires_at__gt=timezone.now(),
|
||||
player_one_rating__gte=max(0, user.rating - 300),
|
||||
player_one_rating__lte=user.rating + 300,
|
||||
)
|
||||
@@ -188,42 +299,198 @@ def find_match(user, contest):
|
||||
if waiting is None:
|
||||
return RealtimeMatch.objects.create(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
player_one=user,
|
||||
player_one_rating=user.rating,
|
||||
expires_at=timezone.now() + WAITING_MATCH_TTL,
|
||||
)
|
||||
|
||||
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"]
|
||||
return _activate_match(waiting, user)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def create_challenge(user, contest):
|
||||
_validate_realtime_contest(contest)
|
||||
_cancel_expired_waiting_matches()
|
||||
active = _active_match_for(user)
|
||||
if active:
|
||||
raise ValidationError("你已有一场进行中的实时比赛")
|
||||
_cancel_other_waiting_matches(user, RealtimeMatch.MatchType.CHALLENGE)
|
||||
existing = (
|
||||
RealtimeMatch.objects.filter(
|
||||
player_one=user,
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.CHALLENGE,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
expires_at__gt=timezone.now(),
|
||||
)
|
||||
.order_by("-created_at")
|
||||
.first()
|
||||
)
|
||||
ContestAttempt.objects.bulk_create(
|
||||
[
|
||||
ContestAttempt(contest=contest, user=waiting.player_one, match=waiting),
|
||||
ContestAttempt(contest=contest, user=user, match=waiting),
|
||||
]
|
||||
if existing:
|
||||
return existing
|
||||
return RealtimeMatch.objects.create(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.CHALLENGE,
|
||||
challenge_code=_new_challenge_code(),
|
||||
player_one=user,
|
||||
player_one_rating=user.rating,
|
||||
expires_at=timezone.now() + WAITING_MATCH_TTL,
|
||||
)
|
||||
return waiting
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def join_challenge(user, challenge_code):
|
||||
_cancel_expired_waiting_matches()
|
||||
code = str(challenge_code or "").strip().upper()
|
||||
if len(code) != 6 or any(character not in CHALLENGE_CODE_ALPHABET for character in code):
|
||||
raise ValidationError({"challenge_code": "联机码应为 6 位大写字母或数字"})
|
||||
try:
|
||||
match = (
|
||||
RealtimeMatch.objects.select_for_update()
|
||||
.select_related("contest", "player_one")
|
||||
.get(
|
||||
challenge_code=code,
|
||||
match_type=RealtimeMatch.MatchType.CHALLENGE,
|
||||
)
|
||||
)
|
||||
except RealtimeMatch.DoesNotExist as exc:
|
||||
raise ValidationError({"challenge_code": "联机码不存在"}) from exc
|
||||
if match.player_one_id == user.id:
|
||||
raise ValidationError({"challenge_code": "不能加入自己创建的约战"})
|
||||
if match.status != RealtimeMatch.Status.WAITING or (
|
||||
match.expires_at and match.expires_at <= timezone.now()
|
||||
):
|
||||
raise ValidationError({"challenge_code": "联机码已失效或已被使用"})
|
||||
active = _active_match_for(user)
|
||||
if active and active.id != match.id:
|
||||
raise ValidationError("你已有一场进行中的实时比赛")
|
||||
own_waiting_ids = list(
|
||||
RealtimeMatch.objects.filter(
|
||||
player_one=user,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
)
|
||||
.exclude(id=match.id)
|
||||
.values_list("id", flat=True)
|
||||
)
|
||||
if own_waiting_ids:
|
||||
RealtimeMatch.objects.filter(id__in=own_waiting_ids).update(
|
||||
status=RealtimeMatch.Status.CANCELLED
|
||||
)
|
||||
for match_id in own_waiting_ids:
|
||||
notify_match_on_commit(match_id, "cancelled")
|
||||
return _activate_match(match, user)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def cancel_waiting_match(user, match_id):
|
||||
match = RealtimeMatch.objects.select_for_update().get(id=match_id)
|
||||
if match.player_one_id != user.id:
|
||||
raise ValidationError("只有创建者可以取消等待")
|
||||
if match.status != RealtimeMatch.Status.WAITING:
|
||||
raise ValidationError("只能取消等待中的比赛")
|
||||
match.status = RealtimeMatch.Status.CANCELLED
|
||||
match.save(update_fields=["status"])
|
||||
notify_match_on_commit(match.id, "cancelled")
|
||||
return match
|
||||
|
||||
|
||||
def match_payload(match, user):
|
||||
attempt = match.attempts.filter(user=user).first()
|
||||
reveal_results = match.status == RealtimeMatch.Status.COMPLETED
|
||||
attempts = {
|
||||
attempt.user_id: attempt
|
||||
for attempt in match.attempts.select_related("user", "contest").all()
|
||||
}
|
||||
attempt = attempts.get(user.id)
|
||||
opponent = match.player_two if match.player_one_id == user.id else match.player_one
|
||||
opponent_attempt = attempts.get(opponent.id) if opponent else None
|
||||
rating_change = (
|
||||
match.rating_changes.filter(user=user).values("delta", "rating_after").first()
|
||||
if reveal_results
|
||||
else None
|
||||
)
|
||||
return {
|
||||
"match_id": match.id,
|
||||
"match_type": match.match_type,
|
||||
"is_owner": match.player_one_id == user.id,
|
||||
"challenge_code": (
|
||||
match.challenge_code
|
||||
if match.match_type == RealtimeMatch.MatchType.CHALLENGE
|
||||
and match.status == RealtimeMatch.Status.WAITING
|
||||
else None
|
||||
),
|
||||
"status": match.status,
|
||||
"contest": match.contest.title,
|
||||
"duration_seconds": match.contest.duration_seconds,
|
||||
"expires_at": match.expires_at,
|
||||
"started_at": match.started_at,
|
||||
"opponent": (
|
||||
{"nickname": opponent.nickname, "rating": opponent.rating}
|
||||
{
|
||||
"nickname": opponent.nickname,
|
||||
"rating": opponent.rating,
|
||||
"status": opponent_attempt.status if opponent_attempt else None,
|
||||
"score": opponent_attempt.score if reveal_results and opponent_attempt else None,
|
||||
"correct_count": (
|
||||
opponent_attempt.correct_count
|
||||
if reveal_results and opponent_attempt
|
||||
else None
|
||||
),
|
||||
}
|
||||
if opponent
|
||||
else None
|
||||
),
|
||||
"attempt": attempt_payload(attempt) if attempt else None,
|
||||
"attempt": (
|
||||
attempt_payload(attempt, include_results=reveal_results)
|
||||
if attempt
|
||||
else None
|
||||
),
|
||||
"result": (
|
||||
{
|
||||
"winner": (
|
||||
"draw"
|
||||
if match.winner_id is None
|
||||
else "self"
|
||||
if match.winner_id == user.id
|
||||
else "opponent"
|
||||
),
|
||||
"rating_delta": rating_change["delta"] if rating_change else 0,
|
||||
"rating_after": rating_change["rating_after"] if rating_change else user.rating,
|
||||
}
|
||||
if reveal_results
|
||||
else None
|
||||
),
|
||||
"websocket_path": f"/ws/v1/contest/matches/{match.id}/",
|
||||
}
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def refresh_match_state(match_id):
|
||||
match = (
|
||||
RealtimeMatch.objects.select_for_update()
|
||||
.select_related("contest", "player_one", "player_two")
|
||||
.get(id=match_id)
|
||||
)
|
||||
if (
|
||||
match.status == RealtimeMatch.Status.WAITING
|
||||
and match.expires_at
|
||||
and match.expires_at <= timezone.now()
|
||||
):
|
||||
match.status = RealtimeMatch.Status.CANCELLED
|
||||
match.save(update_fields=["status"])
|
||||
notify_match_on_commit(match.id, "expired")
|
||||
elif match.status == RealtimeMatch.Status.ACTIVE and match.started_at:
|
||||
deadline = match.started_at + timedelta(seconds=match.contest.duration_seconds)
|
||||
if timezone.now() >= deadline:
|
||||
elapsed_ms = match.contest.duration_seconds * 1000
|
||||
match.attempts.filter(status=ContestAttempt.Status.ACTIVE).update(
|
||||
status=ContestAttempt.Status.EXPIRED,
|
||||
duration_ms=elapsed_ms,
|
||||
submitted_at=timezone.now(),
|
||||
)
|
||||
match = finalize_match(match.id)
|
||||
return match
|
||||
|
||||
|
||||
def _elo_delta(rating, opponent_rating, score, k=32):
|
||||
expected = 1 / (1 + 10 ** ((opponent_rating - rating) / 400))
|
||||
return round(k * (score - expected))
|
||||
@@ -277,4 +544,5 @@ def finalize_match(match_id):
|
||||
match.status = RealtimeMatch.Status.COMPLETED
|
||||
match.completed_at = timezone.now()
|
||||
match.save(update_fields=["winner", "status", "completed_at"])
|
||||
notify_match_on_commit(match.id, "completed")
|
||||
return match
|
||||
|
||||
Reference in New Issue
Block a user