answer/main.py

173 lines
5.5 KiB
Python

from flask import Flask, render_template, request, redirect, url_for, session
import random
app = Flask(__name__)
app.secret_key = 'supersecretkey' # 用于 session 加密
class db_base():
# 存储多个问题和答案
ask_answer = [
{"问题": """
面向对象的三大特点?
A.无序,唯一,封装 B.继承,多态,封装 C.继承,无序,多态
"""
, "答案": "B"},
{"问题": """
程序的运行结果?
a=5
def solve(a):
if a==2:
return 0
print(a)
for i in range(1,a+1):
sol = solve(i)
return sol
print(solve(a))
"""
, "答案": ""},
{"问题": "问题3", "答案": "C"}
]
table1_db = [{"name": "战神战无不胜", "password": "123456", "score": 0}] # 初始用户数据
def __init__(self, name="数据库"):
self.name = name
def add(self, name, password, score=0):
""" 添加新用户 """
self.table1_db.append({"name": name, "password": password, "score": score})
def show(self):
""" 返回所有用户信息 """
return self.table1_db
def change(self, name, score):
""" 修改用户的分数 """
for i in self.table1_db:
if i["name"] == name:
i["score"] = score
return
def fliter(self):
""" 排序并返回按分数降序排列的用户列表 """
score_list = sorted(self.table1_db, key=lambda x: x["score"], reverse=True)
return score_list
def ask_question(self, name, answers):
""" 用户答题并更新分数 """
score = 0
# 遍历所有问题,检查答案
for i, question in enumerate(self.ask_answer):
correct_answer = question["答案"]
if answers[i] == correct_answer:
score += 3 # 每个问题答对得10分
self.change(name, score)
def authenticate(self, name, password):
""" 验证用户名和密码 """
for user in self.table1_db:
if user["name"] == name and user["password"] == password:
return True
return False
# 初始化数据库
db = db_base()
# 常见的昵称词汇
adjectives = ["快乐", "微笑", "", "", "甜美", "阳光", "", "萌萌", "幸福", "自由", "聪明", "勇敢", "帅气", "", "", "安静", "甜蜜"]
nouns = ["小猫", "", "", "星星", "月亮", "飞鸟", "星辰", "玫瑰", "蓝天", "", "海洋", "沙滩", "", "苹果", "橙子", "草地", "心情"]
colors = ["", "", "", "绿", "", "", "", "", "", "", "", ""]
# 组合生成昵称
def generate_random_nickname():
adj = random.choice(adjectives) # 从形容词中选择
noun = random.choice(nouns) # 从名词中选择
color = random.choice(colors) # 从颜色中选择
nickname = adj + color + noun # 组合成昵称
return nickname
# 添加10个随机用户
for i in range(9):
name = str(generate_random_nickname())
password = str(random.randint(111111, 999999))
score = random.randint(0, 100)*3
db.add(name, password, score)
# 首页,展示问题和表单
@app.route('/')
def index():
# 检查用户是否登录
if 'username' not in session:
return redirect(url_for('login')) # 未登录则跳转到登录页面
# 提供所有问题
question_list = db.ask_answer
return render_template('index.html', question_list=question_list)
# 登录页面
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
name = request.form['name']
password = request.form['password']
# 验证用户名和密码
if db.authenticate(name, password):
session['username'] = name # 将用户名存入 session
return redirect(url_for('index')) # 登录成功后跳转到首页
else:
return "登录失败,用户名或密码错误!" # 登录失败提示
return render_template('login.html')
# 提交答案
@app.route('/submit_answer', methods=['POST'])
def submit_answer():
if 'username' not in session:
return redirect(url_for('login')) # 用户未登录时跳转到登录页面
name = session['username'] # 获取当前登录的用户名
answers = []
# 获取所有问题的答案
for i in range(1, len(db.ask_answer) + 1):
answer = request.form.get(f"answer{i}")
answers.append(answer)
# 用户回答所有问题
db.ask_question(name, answers)
# 跳转到排行榜页面
return redirect(url_for('ranking'))
# 排行榜页面
@app.route('/ranking')
def ranking():
if 'username' not in session:
return redirect(url_for('login')) # 用户未登录时跳转到登录页面
# 获取排序后的成绩
sorted_users = db.fliter()
return render_template('ranking.html', users=sorted_users)
# 添加随机用户
@app.route('/add_users')
def add_users():
for _ in range(10):
name = str(random.randint(10, 100))
password = str(random.randint(111111, 999999))
score = random.randint(1, 40)
db.add(name, password, score)
return redirect(url_for('index'))
# 注销登录
@app.route('/logout')
def logout():
session.pop('username', None) # 删除 session 中的用户名
return redirect(url_for('login')) # 跳转到登录页面
if __name__ == '__main__':
app.run(debug=True)