File size: 1,635 Bytes
9a82c5c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from flask import Flask, render_template, request, redirect, url_for, session
import json
import random
import os

app = Flask(__name__)
app.secret_key = 'supersecretkey'

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

@app.route('/start', methods=['POST'])
def start():
    session['name'] = request.form['name']
    session['questions'] = load_questions(request.files['questions'])
    session['current_question'] = 0
    session['answers'] = []
    return redirect(url_for('quiz'))

@app.route('/quiz', methods=['GET', 'POST'])
def quiz():
    if request.method == 'POST':
        session['answers'].append(request.form.get('answer'))
        session['current_question'] += 1
        if session['current_question'] >= len(session['questions']):
            return redirect(url_for('results'))
        return redirect(url_for('quiz'))

    question = session['questions'][session['current_question']]
    return render_template('quiz.html', question=question)

@app.route('/results')
def results():
    questions = session['questions']
    answers = session['answers']
    score = calculate_score(questions, answers)
    return render_template('results.html', score=score, questions=questions, answers=answers)

def load_questions(file):
    questions = json.load(file)
    random.shuffle(questions)
    return questions

def calculate_score(questions, answers):
    correct_count = 0
    for i, question in enumerate(questions):
        if answers[i] in question['correct']:
            correct_count += 1
    return (correct_count / len(questions)) * 100

if __name__ == '__main__':
    app.run(debug=True)