feat: add unified contest pool and realtime game modes
This commit is contained in:
+243
-70
@@ -16,12 +16,14 @@ from .models import (
|
||||
Contest,
|
||||
ContestAnswer,
|
||||
ContestAttempt,
|
||||
MathGameAttempt,
|
||||
RatingHistory,
|
||||
RealtimeMatch,
|
||||
)
|
||||
|
||||
CHALLENGE_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
WAITING_MATCH_TTL = timedelta(minutes=10)
|
||||
ATTEMPT_QUESTION_COUNT = 8
|
||||
|
||||
|
||||
def _broadcast_match(match_id, reason):
|
||||
@@ -54,6 +56,13 @@ def _validate_realtime_contest(contest):
|
||||
raise ValidationError("实时比赛不可用")
|
||||
|
||||
|
||||
def _validate_game_kind(game_kind):
|
||||
value = str(game_kind or RealtimeMatch.GameKind.QUIZ)
|
||||
if value not in RealtimeMatch.GameKind.values:
|
||||
raise ValidationError({"game_kind": "不支持的实时比赛玩法"})
|
||||
return value
|
||||
|
||||
|
||||
def _cancel_expired_waiting_matches():
|
||||
RealtimeMatch.objects.filter(status=RealtimeMatch.Status.WAITING).filter(
|
||||
Q(expires_at__isnull=True) | Q(expires_at__lte=timezone.now())
|
||||
@@ -71,13 +80,13 @@ def _active_match_for(user):
|
||||
)
|
||||
|
||||
|
||||
def _cancel_other_waiting_matches(user, match_type):
|
||||
def _cancel_other_waiting_matches(user, match_type, game_kind):
|
||||
matches = list(
|
||||
RealtimeMatch.objects.filter(
|
||||
player_one=user,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
)
|
||||
.exclude(match_type=match_type)
|
||||
.exclude(match_type=match_type, game_kind=game_kind)
|
||||
.values_list("id", flat=True)
|
||||
)
|
||||
if matches:
|
||||
@@ -88,7 +97,29 @@ def _cancel_other_waiting_matches(user, match_type):
|
||||
notify_match_on_commit(match_id, "cancelled")
|
||||
|
||||
|
||||
def _select_question_order(contest):
|
||||
question_ids = list(
|
||||
contest.contest_questions.filter(question_version__question__is_active=True)
|
||||
.order_by("id")
|
||||
.values_list("id", flat=True)
|
||||
)
|
||||
if not question_ids:
|
||||
raise ValidationError("比赛题库为空")
|
||||
count = min(ATTEMPT_QUESTION_COUNT, len(question_ids))
|
||||
return secrets.SystemRandom().sample(question_ids, count)
|
||||
|
||||
|
||||
def _attempt_questions(attempt):
|
||||
queryset = attempt.contest.contest_questions.select_related("question_version")
|
||||
if attempt.question_order:
|
||||
items = {item.id: item for item in queryset.filter(id__in=attempt.question_order)}
|
||||
return [items[item_id] for item_id in attempt.question_order if item_id in items]
|
||||
return list(queryset.all())
|
||||
|
||||
|
||||
def _activate_match(match, user):
|
||||
from .game_services import build_game
|
||||
|
||||
now = timezone.now()
|
||||
match.player_two = user
|
||||
match.player_two_rating = user.rating
|
||||
@@ -97,13 +128,49 @@ def _activate_match(match, user):
|
||||
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)
|
||||
if match.game_kind == RealtimeMatch.GameKind.QUIZ:
|
||||
question_order = _select_question_order(match.contest)
|
||||
ContestAttempt.objects.bulk_create(
|
||||
[
|
||||
ContestAttempt(
|
||||
contest=match.contest,
|
||||
user=match.player_one,
|
||||
match=match,
|
||||
question_order=question_order,
|
||||
),
|
||||
ContestAttempt(
|
||||
contest=match.contest,
|
||||
user=user,
|
||||
match=match,
|
||||
question_order=question_order,
|
||||
),
|
||||
]
|
||||
)
|
||||
match.attempts.update(started_at=now)
|
||||
else:
|
||||
puzzle, solution = build_game(
|
||||
match.game_kind,
|
||||
MathGameAttempt.Difficulty.STANDARD,
|
||||
)
|
||||
MathGameAttempt.objects.bulk_create(
|
||||
[
|
||||
MathGameAttempt(
|
||||
user=match.player_one,
|
||||
match=match,
|
||||
kind=match.game_kind,
|
||||
puzzle=puzzle,
|
||||
solution=solution,
|
||||
),
|
||||
MathGameAttempt(
|
||||
user=user,
|
||||
match=match,
|
||||
kind=match.game_kind,
|
||||
puzzle=puzzle,
|
||||
solution=solution,
|
||||
),
|
||||
]
|
||||
)
|
||||
match.game_attempts.update(started_at=now)
|
||||
notify_match_on_commit(match.id, "matched")
|
||||
return match
|
||||
|
||||
@@ -119,9 +186,9 @@ def normalize_answer(value):
|
||||
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():
|
||||
for display_order, item in enumerate(_attempt_questions(attempt), start=1):
|
||||
question = {
|
||||
"order": item.order,
|
||||
"order": display_order,
|
||||
"prompt": item.question_version.prompt,
|
||||
"metadata": item.question_version.metadata,
|
||||
"points": item.points,
|
||||
@@ -169,7 +236,11 @@ def start_attempt(user, contest):
|
||||
existing,
|
||||
include_results=existing.status != ContestAttempt.Status.ACTIVE,
|
||||
)
|
||||
attempt = ContestAttempt.objects.create(contest=contest, user=user)
|
||||
attempt = ContestAttempt.objects.create(
|
||||
contest=contest,
|
||||
user=user,
|
||||
question_order=_select_question_order(contest),
|
||||
)
|
||||
return attempt_payload(attempt)
|
||||
|
||||
|
||||
@@ -193,9 +264,7 @@ def submit_attempt(user, attempt_id, raw_answers, submission_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()
|
||||
)
|
||||
items = _attempt_questions(attempt)
|
||||
if not isinstance(raw_answers, list):
|
||||
raise ValidationError({"answers": "答案必须是数组"})
|
||||
by_order = {}
|
||||
@@ -209,8 +278,8 @@ def submit_attempt(user, attempt_id, raw_answers, submission_key):
|
||||
raise ValidationError({"answers": "答案题号无效或重复"}) from exc
|
||||
score = 0
|
||||
correct_count = 0
|
||||
for contest_question in items:
|
||||
submitted = str(by_order.get(contest_question.order, ""))[:200]
|
||||
for display_order, contest_question in enumerate(items, start=1):
|
||||
submitted = str(by_order.get(display_order, ""))[:200]
|
||||
correct = normalize_answer(submitted) == normalize_answer(
|
||||
contest_question.question_version.answer
|
||||
)
|
||||
@@ -260,20 +329,26 @@ def submit_attempt(user, attempt_id, raw_answers, submission_key):
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def find_match(user, contest):
|
||||
def find_match(user, contest, game_kind=RealtimeMatch.GameKind.QUIZ):
|
||||
_validate_realtime_contest(contest)
|
||||
game_kind = _validate_game_kind(game_kind)
|
||||
_cancel_expired_waiting_matches()
|
||||
active = _active_match_for(user)
|
||||
if active:
|
||||
if active.contest_id == contest.id:
|
||||
if active.contest_id == contest.id and active.game_kind == game_kind:
|
||||
return active
|
||||
raise ValidationError("你已有一场进行中的实时比赛")
|
||||
_cancel_other_waiting_matches(user, RealtimeMatch.MatchType.RANDOM)
|
||||
_cancel_other_waiting_matches(
|
||||
user,
|
||||
RealtimeMatch.MatchType.RANDOM,
|
||||
game_kind,
|
||||
)
|
||||
existing = (
|
||||
RealtimeMatch.objects.filter(
|
||||
Q(player_one=user) | Q(player_two=user),
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
game_kind=game_kind,
|
||||
status__in=[RealtimeMatch.Status.WAITING, RealtimeMatch.Status.ACTIVE],
|
||||
).filter(Q(status=RealtimeMatch.Status.ACTIVE) | Q(expires_at__gt=timezone.now()))
|
||||
.order_by("-created_at")
|
||||
@@ -287,6 +362,7 @@ def find_match(user, contest):
|
||||
.filter(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
game_kind=game_kind,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
expires_at__gt=timezone.now(),
|
||||
player_one_rating__gte=max(0, user.rating - 300),
|
||||
@@ -300,6 +376,7 @@ def find_match(user, contest):
|
||||
return RealtimeMatch.objects.create(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.RANDOM,
|
||||
game_kind=game_kind,
|
||||
player_one=user,
|
||||
player_one_rating=user.rating,
|
||||
expires_at=timezone.now() + WAITING_MATCH_TTL,
|
||||
@@ -309,18 +386,24 @@ def find_match(user, contest):
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def create_challenge(user, contest):
|
||||
def create_challenge(user, contest, game_kind=RealtimeMatch.GameKind.QUIZ):
|
||||
_validate_realtime_contest(contest)
|
||||
game_kind = _validate_game_kind(game_kind)
|
||||
_cancel_expired_waiting_matches()
|
||||
active = _active_match_for(user)
|
||||
if active:
|
||||
raise ValidationError("你已有一场进行中的实时比赛")
|
||||
_cancel_other_waiting_matches(user, RealtimeMatch.MatchType.CHALLENGE)
|
||||
_cancel_other_waiting_matches(
|
||||
user,
|
||||
RealtimeMatch.MatchType.CHALLENGE,
|
||||
game_kind,
|
||||
)
|
||||
existing = (
|
||||
RealtimeMatch.objects.filter(
|
||||
player_one=user,
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.CHALLENGE,
|
||||
game_kind=game_kind,
|
||||
status=RealtimeMatch.Status.WAITING,
|
||||
expires_at__gt=timezone.now(),
|
||||
)
|
||||
@@ -332,6 +415,7 @@ def create_challenge(user, contest):
|
||||
return RealtimeMatch.objects.create(
|
||||
contest=contest,
|
||||
match_type=RealtimeMatch.MatchType.CHALLENGE,
|
||||
game_kind=game_kind,
|
||||
challenge_code=_new_challenge_code(),
|
||||
player_one=user,
|
||||
player_one_rating=user.rating,
|
||||
@@ -396,11 +480,19 @@ def cancel_waiting_match(user, match_id):
|
||||
|
||||
|
||||
def match_payload(match, user):
|
||||
from .game_services import game_payload
|
||||
|
||||
reveal_results = match.status == RealtimeMatch.Status.COMPLETED
|
||||
attempts = {
|
||||
attempt.user_id: attempt
|
||||
for attempt in match.attempts.select_related("user", "contest").all()
|
||||
}
|
||||
if match.game_kind == RealtimeMatch.GameKind.QUIZ:
|
||||
attempts = {
|
||||
attempt.user_id: attempt
|
||||
for attempt in match.attempts.select_related("user", "contest").all()
|
||||
}
|
||||
else:
|
||||
attempts = {
|
||||
attempt.user_id: attempt
|
||||
for attempt in match.game_attempts.select_related("user").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
|
||||
@@ -409,9 +501,18 @@ def match_payload(match, user):
|
||||
if reveal_results
|
||||
else None
|
||||
)
|
||||
attempt_data = None
|
||||
if attempt:
|
||||
attempt_data = (
|
||||
attempt_payload(attempt, include_results=reveal_results)
|
||||
if match.game_kind == RealtimeMatch.GameKind.QUIZ
|
||||
else game_payload(attempt)
|
||||
)
|
||||
return {
|
||||
"match_id": match.id,
|
||||
"match_type": match.match_type,
|
||||
"game_kind": match.game_kind,
|
||||
"game_label": match.get_game_kind_display(),
|
||||
"is_owner": match.player_one_id == user.id,
|
||||
"challenge_code": (
|
||||
match.challenge_code
|
||||
@@ -420,7 +521,11 @@ def match_payload(match, user):
|
||||
else None
|
||||
),
|
||||
"status": match.status,
|
||||
"contest": match.contest.title,
|
||||
"contest": (
|
||||
match.contest.title
|
||||
if match.game_kind == RealtimeMatch.GameKind.QUIZ
|
||||
else match.get_game_kind_display()
|
||||
),
|
||||
"duration_seconds": match.contest.duration_seconds,
|
||||
"expires_at": match.expires_at,
|
||||
"started_at": match.started_at,
|
||||
@@ -432,7 +537,9 @@ def match_payload(match, user):
|
||||
"score": opponent_attempt.score if reveal_results and opponent_attempt else None,
|
||||
"correct_count": (
|
||||
opponent_attempt.correct_count
|
||||
if reveal_results and opponent_attempt
|
||||
if reveal_results
|
||||
and opponent_attempt
|
||||
and match.game_kind == RealtimeMatch.GameKind.QUIZ
|
||||
else None
|
||||
),
|
||||
"duration_ms": (
|
||||
@@ -444,11 +551,7 @@ def match_payload(match, user):
|
||||
if opponent
|
||||
else None
|
||||
),
|
||||
"attempt": (
|
||||
attempt_payload(attempt, include_results=reveal_results)
|
||||
if attempt
|
||||
else None
|
||||
),
|
||||
"attempt": attempt_data,
|
||||
"result": (
|
||||
{
|
||||
"winner": (
|
||||
@@ -487,13 +590,34 @@ def refresh_match_state(match_id):
|
||||
deadline = match.started_at + timedelta(seconds=match.contest.duration_seconds)
|
||||
if timezone.now() >= deadline:
|
||||
now = timezone.now()
|
||||
for attempt in match.attempts.filter(status=ContestAttempt.Status.ACTIVE):
|
||||
elapsed_ms = max(0, int((now - attempt.started_at).total_seconds() * 1000))
|
||||
attempt.status = ContestAttempt.Status.EXPIRED
|
||||
attempt.duration_ms = elapsed_ms
|
||||
attempt.submitted_at = now
|
||||
attempt.save(update_fields=["status", "duration_ms", "submitted_at"])
|
||||
match = finalize_match(match.id)
|
||||
if match.game_kind == RealtimeMatch.GameKind.QUIZ:
|
||||
for attempt in match.attempts.filter(
|
||||
status=ContestAttempt.Status.ACTIVE
|
||||
):
|
||||
elapsed_ms = max(
|
||||
0,
|
||||
int((now - attempt.started_at).total_seconds() * 1000),
|
||||
)
|
||||
attempt.status = ContestAttempt.Status.EXPIRED
|
||||
attempt.duration_ms = elapsed_ms
|
||||
attempt.submitted_at = now
|
||||
attempt.save(
|
||||
update_fields=["status", "duration_ms", "submitted_at"]
|
||||
)
|
||||
match = finalize_match(match.id)
|
||||
else:
|
||||
elapsed_ms = max(
|
||||
0,
|
||||
int((now - match.started_at).total_seconds() * 1000),
|
||||
)
|
||||
match.game_attempts.filter(
|
||||
status=MathGameAttempt.Status.ACTIVE
|
||||
).update(
|
||||
status=MathGameAttempt.Status.FAILED,
|
||||
duration_ms=elapsed_ms,
|
||||
submitted_at=now,
|
||||
)
|
||||
match = finalize_game_match(match.id)
|
||||
return match
|
||||
|
||||
|
||||
@@ -502,36 +626,7 @@ def _elo_delta(rating, opponent_rating, score, k=32):
|
||||
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:
|
||||
diff = first.duration_ms - second.duration_ms
|
||||
if abs(diff) <= 100:
|
||||
first_result = second_result = 0.5
|
||||
elif diff < 0:
|
||||
first_result, second_result = 1.0, 0.0
|
||||
match.winner_id = first.user_id
|
||||
else:
|
||||
first_result, second_result = 0.0, 1.0
|
||||
match.winner_id = second.user_id
|
||||
|
||||
def _settle_match(match, first_result, second_result, winner_id):
|
||||
users = {
|
||||
user.id: user
|
||||
for user in User.objects.select_for_update().filter(
|
||||
@@ -555,8 +650,86 @@ def finalize_match(match_id):
|
||||
rating_after=user.rating,
|
||||
delta=delta,
|
||||
)
|
||||
match.winner_id = winner_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
|
||||
|
||||
|
||||
@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
|
||||
winner_id = first.user_id
|
||||
elif second.score > first.score:
|
||||
first_result, second_result = 0.0, 1.0
|
||||
winner_id = second.user_id
|
||||
else:
|
||||
diff = first.duration_ms - second.duration_ms
|
||||
if abs(diff) <= 100:
|
||||
first_result = second_result = 0.5
|
||||
winner_id = None
|
||||
elif diff < 0:
|
||||
first_result, second_result = 1.0, 0.0
|
||||
winner_id = first.user_id
|
||||
else:
|
||||
first_result, second_result = 0.0, 1.0
|
||||
winner_id = second.user_id
|
||||
return _settle_match(
|
||||
match,
|
||||
first_result,
|
||||
second_result,
|
||||
winner_id,
|
||||
)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def finalize_game_match(match_id):
|
||||
match = RealtimeMatch.objects.select_for_update().get(id=match_id)
|
||||
if match.status != RealtimeMatch.Status.ACTIVE:
|
||||
return match
|
||||
attempts = list(match.game_attempts.select_related("user").order_by("user_id"))
|
||||
if len(attempts) != 2 or any(
|
||||
attempt.status == MathGameAttempt.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)
|
||||
first_completed = first.status == MathGameAttempt.Status.COMPLETED
|
||||
second_completed = second.status == MathGameAttempt.Status.COMPLETED
|
||||
if first_completed and not second_completed:
|
||||
first_result, second_result, winner_id = 1.0, 0.0, first.user_id
|
||||
elif second_completed and not first_completed:
|
||||
first_result, second_result, winner_id = 0.0, 1.0, second.user_id
|
||||
elif not first_completed and not second_completed:
|
||||
first_result = second_result = 0.5
|
||||
winner_id = None
|
||||
else:
|
||||
diff = first.duration_ms - second.duration_ms
|
||||
if abs(diff) <= 100:
|
||||
first_result = second_result = 0.5
|
||||
winner_id = None
|
||||
elif diff < 0:
|
||||
first_result, second_result, winner_id = 1.0, 0.0, first.user_id
|
||||
else:
|
||||
first_result, second_result, winner_id = 0.0, 1.0, second.user_id
|
||||
return _settle_match(
|
||||
match,
|
||||
first_result,
|
||||
second_result,
|
||||
winner_id,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user