File size: 4,935 Bytes
cdfb731
 
a2274a8
0bcd8e4
 
 
cdfb731
 
 
 
 
 
a2274a8
 
0bcd8e4
cdfb731
 
 
 
19abad4
cdfb731
 
 
 
 
 
 
a2274a8
cdfb731
 
 
 
a2274a8
0bcd8e4
cdfb731
0bcd8e4
 
cdfb731
 
 
 
0bcd8e4
cdfb731
 
0bcd8e4
cdfb731
 
a2274a8
 
 
 
 
 
 
 
 
9d9efff
 
a2274a8
9d9efff
a2274a8
9d9efff
0bcd8e4
 
cdfb731
a2274a8
 
0bcd8e4
a2274a8
cdfb731
 
 
0bcd8e4
cdfb731
 
0bcd8e4
 
 
 
 
 
a2274a8
 
0bcd8e4
 
 
 
 
 
 
 
 
 
 
 
 
cdfb731
 
 
 
 
a2274a8
 
 
cdfb731
 
0bcd8e4
98960e8
 
 
 
 
 
0bcd8e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98960e8
 
0bcd8e4
 
a2274a8
0bcd8e4
 
 
cdfb731
 
a2274a8
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, join_room, leave_room
import backend  # Import backend functions
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import random

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
socketio = SocketIO(app)

exams = backend.load_question_sets()  # Load available exams
selected_questions = []  # Global variable to store the selected questions
current_question = {"index": 0, "answers": {}, "started": False}
participants = {}

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

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

@app.route('/host')
def host():
    return render_template('host.html', exams=exams)

@socketio.on('join')
def on_join(data):
    username = data['username']
    user_id_number = random.randint(1000, 9999)
    participants[request.sid] = {"user_id_number": user_id_number, "username": username, "score": 0}
    join_room('quiz')
    emit('update_participants', {"participants": participants, "count": len(participants)}, room='quiz')
    print(f"{username} (ID: {user_id_number}) joined the quiz.")

@socketio.on('disconnect')
def on_leave():
    if request.sid in participants:
        username = participants[request.sid]["username"]
        leave_room('quiz')
        del participants[request.sid]
        emit('update_participants', {"participants": participants, "count": len(participants)}, room='quiz')
        print(f"{username} left the quiz.")

@socketio.on('select_exam')
def select_exam(exam_name):
    global selected_questions
    selected_questions = backend.select_exam(exam_name)
    if selected_questions:
        emit('exam_loaded', {"success": True, "exam_name": exam_name}, room=request.sid)
    else:
        emit('exam_loaded', {"success": False, "exam_name": exam_name}, room=request.sid)

@socketio.on('restart_quiz')
def restart_quiz():
    reset_quiz()
    emit('quiz_reset', room='quiz')
    start_quiz()

def start_quiz():
    current_question['started'] = True
    index = current_question['index']
    if index < len(selected_questions):
        question = selected_questions[index]
        emit('new_question', question, room='quiz')
        emit('enable_end_quiz', room='quiz')

@socketio.on('submit_answer')
def receive_answer(data):
    username = participants[request.sid]["username"]
    answer = data['answer']
    current_question['answers'][username] = answer
    if len(current_question['answers']) == len(participants):
        emit('all_answers_received', room='quiz')

@socketio.on('check_answers')
def check_answers():
    index = current_question['index']
    if index < len(selected_questions):
        question = selected_questions[index]
        correct_answer = question['correct']
        results = {
            "question": question["question"],
            "answers": current_question["answers"],
            "correct_answer": correct_answer
        }

        chart_base64 = generate_chart(current_question["answers"], question["options"])
        emit('display_results', {"results": results, "chart": chart_base64}, room='quiz')

        for sid, participant in participants.items():
            if current_question['answers'].get(participant["username"]) == correct_answer:
                participants[sid]["score"] += 1

@socketio.on('next_question')
def next_question():
    current_question['index'] += 1
    current_question['answers'] = {}
    if current_question['index'] < len(selected_questions):
        question = selected_questions[current_question['index']]
        emit('clear_results', room='quiz')
        emit('new_question', question, room='quiz')
    else:
        final_results = calculate_final_results()
        emit('display_final_results', final_results, room='quiz')

@socketio.on('end_quiz')
def end_quiz():
    final_results = calculate_final_results()
    emit('display_final_results', final_results, room='quiz')

def generate_chart(answers, options):
    counts = [list(answers.values()).count(option) for option in options]
    plt.figure(figsize=(6, 4))
    plt.bar(options, counts)
    plt.xlabel('Options')
    plt.ylabel('Number of Votes')
    plt.title('Results')
    buf = BytesIO()
    plt.savefig(buf, format='png')
    buf.seek(0)
    chart_base64 = base64.b64encode(buf.read()).decode('utf-8')
    buf.close()
    plt.close()
    return chart_base64

def calculate_final_results():
    sorted_scores = sorted(participants.values(), key=lambda x: x['score'], reverse=True)
    return [{"username": p["username"], "score": p["score"]} for p in sorted_scores]

def reset_quiz():
    global selected_questions, current_question
    current_question = {"index": 0, "answers": {}, "started": False}
    for participant in participants.values():
        participant["score"] = 0

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