64 lines
2.3 KiB
Python
64 lines
2.3 KiB
Python
"""小游戏服务"""
|
|
import random
|
|
import logging
|
|
from datetime import datetime
|
|
|
|
from db.models import GameScore
|
|
|
|
logger = logging.getLogger("spam_guard")
|
|
|
|
# 简单题库
|
|
TRIVIA_QUESTIONS = [
|
|
{"q": "收割机项目的 GitHub 地址是?", "a": "github.com/ngfchl/go-harvest", "opts": ["github.com/ngfchl/go-harvest", "github.com/ngfchl/harvest", "github.com/harvest/go-harvest"]},
|
|
{"q": "以下哪个不是 PT 站的常见等级?", "a": "Diamond", "opts": ["User", "Power User", "Diamond", "Elite"]},
|
|
{"q": "Docker 默认的日志驱动是?", "a": "json-file", "opts": ["json-file", "syslog", "journald", "fluentd"]},
|
|
]
|
|
|
|
|
|
async def get_or_create_score(user_id: int, username: str, game_type: str) -> GameScore:
|
|
score, _ = await GameScore.get_or_create(
|
|
user_id=user_id, game_type=game_type,
|
|
defaults={"username": username},
|
|
)
|
|
return score
|
|
|
|
|
|
async def get_trivia_question() -> dict:
|
|
return random.choice(TRIVIA_QUESTIONS)
|
|
|
|
|
|
async def check_trivia_answer(user_id: int, username: str, answer: str, correct_answer: str) -> dict:
|
|
score = await get_or_create_score(user_id, username, "trivia")
|
|
score.total += 1
|
|
is_correct = answer.strip().lower() in correct_answer.strip().lower()
|
|
if is_correct:
|
|
score.score += 10
|
|
score.wins += 1
|
|
score.streak += 1
|
|
if score.streak > 1:
|
|
score.score += 5 # 连击奖励
|
|
else:
|
|
score.streak = 0
|
|
score.last_played = datetime.now()
|
|
await score.save()
|
|
return {"correct": is_correct, "score": score.score, "streak": score.streak}
|
|
|
|
|
|
async def get_leaderboard(game_type: str = "trivia", limit: int = 10) -> list:
|
|
return await GameScore.filter(game_type=game_type).order_by("-score").limit(limit).all()
|
|
|
|
|
|
async def daily_checkin(user_id: int, username: str) -> dict:
|
|
score = await get_or_create_score(user_id, username, "checkin")
|
|
today = datetime.now().strftime("%Y-%m-%d")
|
|
if score.last_played and score.last_played.strftime("%Y-%m-%d") == today:
|
|
return {"ok": False, "reason": "already_checked"}
|
|
score.total += 1
|
|
score.score += 5
|
|
score.streak += 1
|
|
bonus = min(score.streak, 7) # 连续签到最多 +7
|
|
score.score += bonus
|
|
score.last_played = datetime.now()
|
|
await score.save()
|
|
return {"ok": True, "score": score.score, "streak": score.streak, "bonus": bonus}
|