بتل کد Battle Codeدارد باز می‌شود…

جواب «Step 2: The Top Three» چالش 5 از جلسه‌ی 20

سؤال

(سخت‌تر) قدم ۲: مسیر GET /top/<game> را اضافه کن. اگر game در GAMES نبود، 404 با {"error": "no game called Chess"} (با همان اسم). وگرنه با MAX(points) AS best، WHERE game = ?، GROUP BY player و LIMIT 3 سه بازیکنی را برگردان که بهترین امتیاز آن بازی را دارند (هر کدام player و best)، از بیشترین، و برای امتیاز برابر به ترتیب اسم. این سه درخواست را بعد از سه درخواست قدم ۱ اضافه کن:
``
ask("GET /top/Snake")
ask("GET /top/Pong")
ask("GET /top/Chess")
`
خروجی قدم ۱ همان می‌ماند و بعد از آن این می‌آید:
`
GET /top/Snake → 200 OK
[
{"player": "Sara", "best": 150},
{"player": "Kian", "best": 140},
{"player": "Mina", "best": 140}
]
GET /top/Pong → 200 OK
[
{"player": "Reza", "best": 160},
{"player": "Leila", "best": 45},
{"player": "Omid", "best": 38}
]
GET /top/Chess → 404 Not Found
{"error": "no game called Chess"}
``

راهنما

db.all("SELECT player, MAX(points) AS best FROM scores WHERE game = ? GROUP BY player ORDER BY best DESC, player LIMIT 3", (game,)). بررسی game not in GAMES را قبلش بگذار.

یک جواب درست

from server import app, ask, db, request, abort

db.script('''
CREATE TABLE scores (id INTEGER PRIMARY KEY, player TEXT, game TEXT, points INTEGER);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Snake', 145), ('Ali', 'Snake', 95), ('Mina', 'Snake', 140);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Pong', 30), ('Reza', 'Pong', 160), ('Kian', 'Snake', 140);
INSERT INTO scores (player, game, points) VALUES ('Sara', 'Snake', 150), ('Omid', 'Pong', 38);
''')

GAMES = ["Snake", "Pong"]

@app.post("/scores")
def add_score():
    data = request.json or {}
    player = data.get("player")
    game = data.get("game")
    points = data.get("points")
    problems = []
    if not isinstance(player, str) or player == "":
        problems.append("player is required")
    if game not in GAMES:
        problems.append("game must be Snake or Pong")
    if not isinstance(points, int) or points < 0 or points > 1000:
        problems.append("points must be a whole number from 0 to 1000")
    if problems:
        return {"errors": problems}, 400
    done = db.run("INSERT INTO scores (player, game, points) VALUES (?, ?, ?)", (player, game, points))
    return db.one("SELECT * FROM scores WHERE id = ?", (done.id,)), 201

@app.get("/top/<game>")
def top_players(game):
    if game not in GAMES:
        abort(404, "no game called " + game)
    return db.all("SELECT player, MAX(points) AS best FROM scores WHERE game = ? GROUP BY player ORDER BY best DESC, player LIMIT 3", (game,))

ask("POST /scores", {"player": "Leila", "game": "Pong", "points": 45})
ask("POST /scores", {"player": "", "game": "Chess", "points": 5000})
ask("POST /scores", {"player": "Nima", "game": "Snake", "points": "lots"})
ask("GET /top/Snake")
ask("GET /top/Pong")
ask("GET /top/Chess")

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن