티스토리 뷰

from flask import Flask, request, render_template, redirect, url_for, session
import random
import sqlite3
import os
import webbrowser

app = Flask(__name__)
app.secret_key = os.urandom(32)

DATABASE = "scores.db"
PROVERBS_FILE = 'static/사자성어.txt'

# 파일 읽기
with open(PROVERBS_FILE, 'r', encoding='utf-8') as file:
    lines = file.readlines()

# 사자성어와 설명을 분리하여 저장
proverbs = {}
for line in lines:
    parts = line.strip().split(':')
    if len(parts) == 2:
        proverbs[parts[0].strip()] = parts[1].strip()

# 데이터베이스 설정
conn = sqlite3.connect(DATABASE)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS scores (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    name TEXT, 
    score INTEGER)''')
conn.commit()
conn.close()

def get_db():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

def create_quiz(proverbs, num_choices=5):
    correct_answer = random.choice(list(proverbs.keys()))
    choices = random.sample(list(proverbs.keys()), num_choices - 1)
    if correct_answer not in choices:
        choices.append(correct_answer)
    random.shuffle(choices)
    return proverbs[correct_answer], choices, correct_answer

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/start_quiz', methods=['POST'])
def start_quiz():
    username = request.form['username']
    session['username'] = username
    session['score'] = 0
    session['correct'] = True
    return redirect(url_for('quiz'))

@app.route('/quiz')
def quiz():
    if 'username' not in session:
        return redirect(url_for('index'))
    
    description, choices, correct_answer = create_quiz(proverbs)
    session['description'] = description
    session['choices'] = choices
    session['correct_answer'] = correct_answer

    return render_template('quiz.html', description=description, choices=choices)

@app.route('/answer', methods=['POST'])
def answer():
    user_answer = request.form['choice']
    correct_answer = session['correct_answer']
    username = session['username']
    
    correct = user_answer == correct_answer
    session['correct'] = correct
    
    if correct:
        session['score'] += 1
    
    return render_template('result.html', correct=correct, correct_answer=correct_answer)

@app.route('/finish')
def finish():
    username = session.get('username', 'unknown')
    score = session.get('score', 0)

    # 스코어 데이터베이스에 저장
    conn = get_db()
    c = conn.cursor()
    c.execute("INSERT INTO scores (name, score) VALUES (?, ?)", (username, score))
    conn.commit()

    # 모든 스코어 출력
    all_scores = c.execute("SELECT name, score FROM scores").fetchall()
    highest_score = c.execute("SELECT name, score FROM scores ORDER BY score DESC LIMIT 1").fetchone()
    conn.close()

    return render_template('finish.html', username=username, score=score, all_scores=all_scores, highest_score=highest_score)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
728x90
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함