feat: add math engine and puzzle services
This commit is contained in:
@@ -7,6 +7,7 @@ from .models import (
|
||||
ContestAttempt,
|
||||
ContestQuestion,
|
||||
LeaderboardSnapshot,
|
||||
MathGameAttempt,
|
||||
Question,
|
||||
QuestionVersion,
|
||||
RatingHistory,
|
||||
@@ -64,3 +65,21 @@ admin.site.register(ContestAnswer)
|
||||
admin.site.register(RealtimeMatch)
|
||||
admin.site.register(RatingHistory)
|
||||
admin.site.register(LeaderboardSnapshot)
|
||||
|
||||
|
||||
@admin.register(MathGameAttempt)
|
||||
class MathGameAttemptAdmin(admin.ModelAdmin):
|
||||
list_display = (
|
||||
"id",
|
||||
"user",
|
||||
"kind",
|
||||
"difficulty",
|
||||
"status",
|
||||
"score",
|
||||
"hints_used",
|
||||
"started_at",
|
||||
)
|
||||
list_filter = ("kind", "difficulty", "status")
|
||||
search_fields = ("user__username", "user__nickname")
|
||||
readonly_fields = ("puzzle", "solution", "submission", "started_at", "submitted_at")
|
||||
ordering = ("-started_at",)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import ast
|
||||
import secrets
|
||||
from collections import Counter
|
||||
from fractions import Fraction
|
||||
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from .models import MathGameAttempt
|
||||
|
||||
SUDOKU_PUZZLES = {
|
||||
MathGameAttempt.Difficulty.EASY: [
|
||||
(
|
||||
"530070000600195000098000060800060003400803001700020006060000280000419005000080079",
|
||||
"534678912672195348198342567859761423426853791713924856961537284287419635345286179",
|
||||
),
|
||||
],
|
||||
MathGameAttempt.Difficulty.STANDARD: [
|
||||
(
|
||||
"000260701680070090190004500820100040004602900050003028009300074040050036703018000",
|
||||
"435269781682571493197834562826195347374682915951743628519326874248957136763418259",
|
||||
),
|
||||
],
|
||||
MathGameAttempt.Difficulty.HARD: [
|
||||
(
|
||||
"000000010400000000020000000000050407008000300001090000300400200050100000000806000",
|
||||
"693784512487512936125963874932651487568247391741398625319475268856129743274836159",
|
||||
),
|
||||
],
|
||||
}
|
||||
|
||||
TWENTY_FOUR_PUZZLES = {
|
||||
MathGameAttempt.Difficulty.EASY: [(3, 3, 8, 8), (1, 3, 4, 6), (4, 4, 10, 10)],
|
||||
MathGameAttempt.Difficulty.STANDARD: [(2, 3, 4, 9), (3, 5, 7, 13), (4, 7, 8, 8)],
|
||||
MathGameAttempt.Difficulty.HARD: [(1, 5, 5, 5), (3, 3, 7, 7), (5, 5, 7, 11)],
|
||||
}
|
||||
|
||||
|
||||
def _grid_from_text(value):
|
||||
return [[int(value[row * 9 + column]) for column in range(9)] for row in range(9)]
|
||||
|
||||
|
||||
def game_payload(attempt):
|
||||
return {
|
||||
"attempt_id": attempt.id,
|
||||
"kind": attempt.kind,
|
||||
"difficulty": attempt.difficulty,
|
||||
"status": attempt.status,
|
||||
"puzzle": attempt.puzzle,
|
||||
"score": attempt.score,
|
||||
"duration_ms": attempt.duration_ms,
|
||||
"hints_used": attempt.hints_used,
|
||||
"started_at": attempt.started_at,
|
||||
}
|
||||
|
||||
|
||||
def start_game(user, kind, difficulty):
|
||||
if kind not in MathGameAttempt.Kind.values:
|
||||
raise ValidationError({"kind": "不支持的数学玩法"})
|
||||
if difficulty not in MathGameAttempt.Difficulty.values:
|
||||
raise ValidationError({"difficulty": "不支持的难度"})
|
||||
if kind == MathGameAttempt.Kind.SUDOKU:
|
||||
puzzle_text, solution_text = secrets.choice(SUDOKU_PUZZLES[difficulty])
|
||||
puzzle = {"grid": _grid_from_text(puzzle_text), "hints": []}
|
||||
solution = {"grid": _grid_from_text(solution_text)}
|
||||
else:
|
||||
numbers = list(secrets.choice(TWENTY_FOUR_PUZZLES[difficulty]))
|
||||
secrets.SystemRandom().shuffle(numbers)
|
||||
puzzle = {"numbers": numbers}
|
||||
solution = {"target": 24}
|
||||
attempt = MathGameAttempt.objects.create(
|
||||
user=user,
|
||||
kind=kind,
|
||||
difficulty=difficulty,
|
||||
puzzle=puzzle,
|
||||
solution=solution,
|
||||
)
|
||||
return game_payload(attempt)
|
||||
|
||||
|
||||
def _validate_twenty_four_expression(source, numbers):
|
||||
source = str(source or "").strip()
|
||||
if not source or len(source) > 120:
|
||||
raise ValidationError({"expression": "请输入不超过 120 个字符的表达式"})
|
||||
try:
|
||||
tree = ast.parse(source, mode="eval")
|
||||
except SyntaxError as exc:
|
||||
raise ValidationError({"expression": "表达式语法无效"}) from exc
|
||||
used = []
|
||||
|
||||
def evaluate(node):
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, int):
|
||||
used.append(node.value)
|
||||
return Fraction(node.value)
|
||||
if isinstance(node, ast.BinOp) and isinstance(
|
||||
node.op,
|
||||
(ast.Add, ast.Sub, ast.Mult, ast.Div),
|
||||
):
|
||||
left = evaluate(node.left)
|
||||
right = evaluate(node.right)
|
||||
if isinstance(node.op, ast.Add):
|
||||
return left + right
|
||||
if isinstance(node.op, ast.Sub):
|
||||
return left - right
|
||||
if isinstance(node.op, ast.Mult):
|
||||
return left * right
|
||||
if right == 0:
|
||||
raise ValidationError({"expression": "不能除以零"})
|
||||
return left / right
|
||||
raise ValidationError({"expression": "只允许题目数字、括号和 + - * /"})
|
||||
|
||||
result = evaluate(tree.body)
|
||||
if Counter(used) != Counter(numbers):
|
||||
raise ValidationError({"expression": "必须且只能使用题目给出的四个数字各一次"})
|
||||
if result != 24:
|
||||
raise ValidationError({"expression": f"当前结果是 {result},还没有得到 24"})
|
||||
return source
|
||||
|
||||
|
||||
def _validate_sudoku_grid(raw_grid, puzzle, solution):
|
||||
if (
|
||||
not isinstance(raw_grid, list)
|
||||
or len(raw_grid) != 9
|
||||
or any(not isinstance(row, list) or len(row) != 9 for row in raw_grid)
|
||||
):
|
||||
raise ValidationError({"grid": "数独答案必须是 9×9 网格"})
|
||||
try:
|
||||
grid = [[int(value) for value in row] for row in raw_grid]
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError({"grid": "每个格子必须填写 1 到 9"}) from exc
|
||||
if any(value < 1 or value > 9 for row in grid for value in row):
|
||||
raise ValidationError({"grid": "每个格子必须填写 1 到 9"})
|
||||
givens = puzzle["grid"]
|
||||
for row in range(9):
|
||||
for column in range(9):
|
||||
if givens[row][column] and grid[row][column] != givens[row][column]:
|
||||
raise ValidationError({"grid": "不能修改题目给出的数字"})
|
||||
if grid != solution["grid"]:
|
||||
raise ValidationError({"grid": "答案尚未满足全部行、列和九宫格"})
|
||||
return grid
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def submit_game(user, attempt_id, submission, submission_key):
|
||||
attempt = MathGameAttempt.objects.select_for_update().get(id=attempt_id, user=user)
|
||||
if attempt.status == MathGameAttempt.Status.COMPLETED:
|
||||
if submission_key and attempt.submission_key == submission_key:
|
||||
return game_payload(attempt)
|
||||
raise ValidationError("这局游戏已经完成")
|
||||
if not submission_key:
|
||||
raise ValidationError({"Idempotency-Key": "提交必须提供幂等键"})
|
||||
|
||||
if attempt.kind == MathGameAttempt.Kind.SUDOKU:
|
||||
normalized = {
|
||||
"grid": _validate_sudoku_grid(
|
||||
submission.get("grid"),
|
||||
attempt.puzzle,
|
||||
attempt.solution,
|
||||
)
|
||||
}
|
||||
else:
|
||||
normalized = {
|
||||
"expression": _validate_twenty_four_expression(
|
||||
submission.get("expression"),
|
||||
attempt.puzzle["numbers"],
|
||||
)
|
||||
}
|
||||
|
||||
now = timezone.now()
|
||||
duration_ms = max(0, int((now - attempt.started_at).total_seconds() * 1000))
|
||||
base_score = 1800 if attempt.kind == MathGameAttempt.Kind.SUDOKU else 1000
|
||||
time_penalty = duration_ms // (2000 if attempt.kind == MathGameAttempt.Kind.SUDOKU else 1000)
|
||||
attempt.submission = normalized
|
||||
attempt.status = MathGameAttempt.Status.COMPLETED
|
||||
attempt.duration_ms = duration_ms
|
||||
attempt.score = max(100, base_score - time_penalty - attempt.hints_used * 150)
|
||||
attempt.submission_key = submission_key
|
||||
attempt.submitted_at = now
|
||||
attempt.save(
|
||||
update_fields=[
|
||||
"submission",
|
||||
"status",
|
||||
"duration_ms",
|
||||
"score",
|
||||
"submission_key",
|
||||
"submitted_at",
|
||||
]
|
||||
)
|
||||
return game_payload(attempt)
|
||||
|
||||
|
||||
@transaction.atomic
|
||||
def request_sudoku_hint(user, attempt_id):
|
||||
attempt = MathGameAttempt.objects.select_for_update().get(id=attempt_id, user=user)
|
||||
if attempt.kind != MathGameAttempt.Kind.SUDOKU:
|
||||
raise ValidationError("只有数独支持提示")
|
||||
if attempt.status != MathGameAttempt.Status.ACTIVE:
|
||||
raise ValidationError("这局游戏已经结束")
|
||||
hints = list(attempt.puzzle.get("hints", []))
|
||||
if len(hints) >= 3:
|
||||
raise ValidationError("每局最多使用 3 次提示")
|
||||
candidates = [
|
||||
(row, column)
|
||||
for row in range(9)
|
||||
for column in range(9)
|
||||
if attempt.puzzle["grid"][row][column] == 0
|
||||
and not any(item["row"] == row and item["column"] == column for item in hints)
|
||||
]
|
||||
row, column = secrets.choice(candidates)
|
||||
hint = {
|
||||
"row": row,
|
||||
"column": column,
|
||||
"value": attempt.solution["grid"][row][column],
|
||||
}
|
||||
hints.append(hint)
|
||||
attempt.puzzle = {**attempt.puzzle, "hints": hints}
|
||||
attempt.hints_used = len(hints)
|
||||
attempt.save(update_fields=["puzzle", "hints_used"])
|
||||
return {**hint, "hints_used": attempt.hints_used}
|
||||
@@ -0,0 +1,44 @@
|
||||
# Generated by Django 4.2.23 on 2026-08-08 17:26
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('contest', '0002_realtimematch_matchmaking_lookup_idx'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='MathGameAttempt',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('kind', models.CharField(choices=[('sudoku', '数独'), ('twenty_four', '24 点')], max_length=20)),
|
||||
('difficulty', models.CharField(choices=[('easy', '入门'), ('standard', '标准'), ('hard', '进阶')], default='standard', max_length=16)),
|
||||
('puzzle', models.JSONField(default=dict)),
|
||||
('solution', models.JSONField(default=dict)),
|
||||
('submission', models.JSONField(blank=True, default=dict)),
|
||||
('status', models.CharField(choices=[('active', '进行中'), ('completed', '已完成'), ('failed', '未通过')], default='active', max_length=16)),
|
||||
('score', models.PositiveIntegerField(default=0)),
|
||||
('duration_ms', models.PositiveIntegerField(default=0)),
|
||||
('hints_used', models.PositiveSmallIntegerField(default=0)),
|
||||
('submission_key', models.CharField(blank=True, max_length=80, null=True)),
|
||||
('started_at', models.DateTimeField(auto_now_add=True)),
|
||||
('submitted_at', models.DateTimeField(blank=True, null=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='math_game_attempts', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ['-started_at'],
|
||||
'indexes': [models.Index(fields=['kind', 'status', '-score', 'duration_ms'], name='math_game_ranking_idx')],
|
||||
},
|
||||
),
|
||||
migrations.AddConstraint(
|
||||
model_name='mathgameattempt',
|
||||
constraint=models.UniqueConstraint(fields=('user', 'submission_key'), name='unique_user_math_game_submission'),
|
||||
),
|
||||
]
|
||||
@@ -192,3 +192,57 @@ class CheatFlag(models.Model):
|
||||
evidence = models.JSONField(default=dict)
|
||||
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
|
||||
class MathGameAttempt(models.Model):
|
||||
class Kind(models.TextChoices):
|
||||
SUDOKU = "sudoku", "数独"
|
||||
TWENTY_FOUR = "twenty_four", "24 点"
|
||||
|
||||
class Difficulty(models.TextChoices):
|
||||
EASY = "easy", "入门"
|
||||
STANDARD = "standard", "标准"
|
||||
HARD = "hard", "进阶"
|
||||
|
||||
class Status(models.TextChoices):
|
||||
ACTIVE = "active", "进行中"
|
||||
COMPLETED = "completed", "已完成"
|
||||
FAILED = "failed", "未通过"
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL,
|
||||
on_delete=models.CASCADE,
|
||||
related_name="math_game_attempts",
|
||||
)
|
||||
kind = models.CharField(max_length=20, choices=Kind.choices)
|
||||
difficulty = models.CharField(
|
||||
max_length=16,
|
||||
choices=Difficulty.choices,
|
||||
default=Difficulty.STANDARD,
|
||||
)
|
||||
puzzle = models.JSONField(default=dict)
|
||||
solution = models.JSONField(default=dict)
|
||||
submission = models.JSONField(default=dict, blank=True)
|
||||
status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
|
||||
score = models.PositiveIntegerField(default=0)
|
||||
duration_ms = models.PositiveIntegerField(default=0)
|
||||
hints_used = models.PositiveSmallIntegerField(default=0)
|
||||
submission_key = models.CharField(max_length=80, null=True, blank=True)
|
||||
started_at = models.DateTimeField(auto_now_add=True)
|
||||
submitted_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=("user", "submission_key"),
|
||||
name="unique_user_math_game_submission",
|
||||
)
|
||||
]
|
||||
indexes = [
|
||||
models.Index(
|
||||
fields=("kind", "status", "-score", "duration_ms"),
|
||||
name="math_game_ranking_idx",
|
||||
)
|
||||
]
|
||||
ordering = ["-started_at"]
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import pytest
|
||||
from rest_framework.exceptions import ValidationError
|
||||
|
||||
from accounts.models import User
|
||||
from contest.game_services import (
|
||||
SUDOKU_PUZZLES,
|
||||
request_sudoku_hint,
|
||||
start_game,
|
||||
submit_game,
|
||||
)
|
||||
from contest.models import MathGameAttempt
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def game_user(db):
|
||||
return User.objects.create_user(
|
||||
username="game_user",
|
||||
password="StrongPass_2026",
|
||||
nickname="游戏玩家",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_twenty_four_服务端校验数字使用与幂等提交(game_user):
|
||||
attempt = MathGameAttempt.objects.create(
|
||||
user=game_user,
|
||||
kind=MathGameAttempt.Kind.TWENTY_FOUR,
|
||||
puzzle={"numbers": [1, 3, 4, 6]},
|
||||
solution={"target": 24},
|
||||
)
|
||||
|
||||
result = submit_game(
|
||||
game_user,
|
||||
attempt.id,
|
||||
{"expression": "6 / (1 - 3 / 4)"},
|
||||
"game-submit-1",
|
||||
)
|
||||
replay = submit_game(
|
||||
game_user,
|
||||
attempt.id,
|
||||
{"expression": "1 + 3 + 4 + 6"},
|
||||
"game-submit-1",
|
||||
)
|
||||
|
||||
assert result["status"] == MathGameAttempt.Status.COMPLETED
|
||||
assert result["score"] >= 100
|
||||
assert replay["score"] == result["score"]
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_twenty_four_拒绝额外数字和非四则表达式(game_user):
|
||||
attempt = MathGameAttempt.objects.create(
|
||||
user=game_user,
|
||||
kind=MathGameAttempt.Kind.TWENTY_FOUR,
|
||||
puzzle={"numbers": [1, 3, 4, 6]},
|
||||
solution={"target": 24},
|
||||
)
|
||||
|
||||
with pytest.raises(ValidationError, match="四个数字"):
|
||||
submit_game(
|
||||
game_user,
|
||||
attempt.id,
|
||||
{"expression": "6 / (1 - 3 / 4) + 24 - 24"},
|
||||
"invalid-extra-number",
|
||||
)
|
||||
with pytest.raises(ValidationError, match="只允许"):
|
||||
submit_game(
|
||||
game_user,
|
||||
attempt.id,
|
||||
{"expression": "pow(2, 3) * 3"},
|
||||
"invalid-function",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_sudoku_提示受限并由服务端校验完整答案(game_user):
|
||||
payload = start_game(
|
||||
game_user,
|
||||
MathGameAttempt.Kind.SUDOKU,
|
||||
MathGameAttempt.Difficulty.EASY,
|
||||
)
|
||||
attempt = MathGameAttempt.objects.get(id=payload["attempt_id"])
|
||||
hint = request_sudoku_hint(game_user, attempt.id)
|
||||
solution_text = SUDOKU_PUZZLES[MathGameAttempt.Difficulty.EASY][0][1]
|
||||
solution = [
|
||||
[int(solution_text[row * 9 + column]) for column in range(9)]
|
||||
for row in range(9)
|
||||
]
|
||||
|
||||
result = submit_game(
|
||||
game_user,
|
||||
attempt.id,
|
||||
{"grid": solution},
|
||||
"sudoku-submit-1",
|
||||
)
|
||||
|
||||
assert hint["value"] == solution[hint["row"]][hint["column"]]
|
||||
assert result["status"] == MathGameAttempt.Status.COMPLETED
|
||||
assert result["hints_used"] == 1
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
def test_math_game_api_目录公开但开局需要登录(client, game_user):
|
||||
catalog = client.get("/api/v1/contests/games/")
|
||||
anonymous_start = client.post(
|
||||
"/api/v1/contests/games/twenty_four/start/",
|
||||
{"difficulty": "easy"},
|
||||
content_type="application/json",
|
||||
)
|
||||
client.force_login(game_user)
|
||||
authenticated_start = client.post(
|
||||
"/api/v1/contests/games/twenty_four/start/",
|
||||
{"difficulty": "easy"},
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
assert catalog.status_code == 200
|
||||
assert {item["kind"] for item in catalog.json()} == {"sudoku", "twenty_four"}
|
||||
assert anonymous_start.status_code in {401, 403}
|
||||
assert authenticated_start.status_code == 201
|
||||
assert "solution" not in authenticated_start.json()
|
||||
@@ -7,6 +7,11 @@ from .views import (
|
||||
LeaderboardView,
|
||||
MatchmakingView,
|
||||
MatchStateView,
|
||||
MathGameCatalogView,
|
||||
MathGameHistoryView,
|
||||
MathGameStartView,
|
||||
MathGameSubmitView,
|
||||
SudokuHintView,
|
||||
)
|
||||
|
||||
urlpatterns = [
|
||||
@@ -16,4 +21,17 @@ urlpatterns = [
|
||||
path("<slug:slug>/leaderboard/", LeaderboardView.as_view(), name="leaderboard"),
|
||||
path("attempts/<uuid:attempt_id>/submit/", AttemptSubmitView.as_view(), name="attempt-submit"),
|
||||
path("matches/<uuid:match_id>/", MatchStateView.as_view(), name="match-state"),
|
||||
path("games/", MathGameCatalogView.as_view(), name="math-game-catalog"),
|
||||
path("games/history/", MathGameHistoryView.as_view(), name="math-game-history"),
|
||||
path("games/<str:kind>/start/", MathGameStartView.as_view(), name="math-game-start"),
|
||||
path(
|
||||
"games/attempts/<uuid:attempt_id>/submit/",
|
||||
MathGameSubmitView.as_view(),
|
||||
name="math-game-submit",
|
||||
),
|
||||
path(
|
||||
"games/attempts/<uuid:attempt_id>/hint/",
|
||||
SudokuHintView.as_view(),
|
||||
name="sudoku-hint",
|
||||
),
|
||||
]
|
||||
|
||||
@@ -3,7 +3,8 @@ from rest_framework import permissions, status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
from .models import Contest, ContestAttempt, RealtimeMatch
|
||||
from .game_services import game_payload, request_sudoku_hint, start_game, submit_game
|
||||
from .models import Contest, ContestAttempt, MathGameAttempt, RealtimeMatch
|
||||
from .services import (
|
||||
find_match,
|
||||
match_payload,
|
||||
@@ -98,3 +99,59 @@ class LeaderboardView(APIView):
|
||||
for index, attempt in enumerate(attempts, start=1)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class MathGameCatalogView(APIView):
|
||||
permission_classes = [permissions.AllowAny]
|
||||
|
||||
def get(self, request):
|
||||
return Response(
|
||||
[
|
||||
{
|
||||
"kind": MathGameAttempt.Kind.TWENTY_FOUR,
|
||||
"title": "24 点",
|
||||
"summary": "四个数字各用一次,只用四则运算得到 24。",
|
||||
"ability": "connection",
|
||||
"estimated_minutes": 3,
|
||||
},
|
||||
{
|
||||
"kind": MathGameAttempt.Kind.SUDOKU,
|
||||
"title": "数独",
|
||||
"summary": "在行、列和九宫格约束中完成 9×9 数字推理。",
|
||||
"ability": "detection",
|
||||
"estimated_minutes": 8,
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class MathGameStartView(APIView):
|
||||
def post(self, request, kind):
|
||||
payload = start_game(
|
||||
request.user,
|
||||
kind,
|
||||
request.data.get("difficulty", MathGameAttempt.Difficulty.STANDARD),
|
||||
)
|
||||
return Response(payload, status=status.HTTP_201_CREATED)
|
||||
|
||||
|
||||
class MathGameSubmitView(APIView):
|
||||
def post(self, request, attempt_id):
|
||||
payload = submit_game(
|
||||
request.user,
|
||||
attempt_id,
|
||||
request.data,
|
||||
request.headers.get("Idempotency-Key"),
|
||||
)
|
||||
return Response(payload)
|
||||
|
||||
|
||||
class SudokuHintView(APIView):
|
||||
def post(self, request, attempt_id):
|
||||
return Response(request_sudoku_hint(request.user, attempt_id))
|
||||
|
||||
|
||||
class MathGameHistoryView(APIView):
|
||||
def get(self, request):
|
||||
attempts = MathGameAttempt.objects.filter(user=request.user)[:20]
|
||||
return Response([game_payload(attempt) for attempt in attempts])
|
||||
|
||||
Reference in New Issue
Block a user