generated from technolyceum/ai6-m2
151 lines
5.1 KiB
Python
151 lines
5.1 KiB
Python
from flask import Flask, render_template, request, jsonify, session
|
|
import json
|
|
import random
|
|
from pymongo import MongoClient # Added MongoDB support
|
|
|
|
# MongoDB connection
|
|
MONGO_URI = "mongodb://ai6s3:Student123!@localhost:27017/student_db"
|
|
client = MongoClient(MONGO_URI)
|
|
db = client.student_db # Connect to student_db database
|
|
questions_collection = db.questions # Use questions collection
|
|
|
|
app = Flask(__name__)
|
|
app.secret_key = 'quizimoto_secret_key'
|
|
|
|
# Load questions from MongoDB
|
|
try:
|
|
questions_data = list(questions_collection.find({}))
|
|
except Exception as e:
|
|
print(f"Error loading questions from MongoDB: {e}")
|
|
questions_data = [] # Fallback to empty list if database connection fails
|
|
|
|
# Prize structure (15 levels)
|
|
PRIZE_LEVELS = [
|
|
100, 200, 300, 500, 1000,
|
|
2000, 4000, 8000, 16000, 32000,
|
|
64000, 125000, 250000, 500000, 1000000
|
|
]
|
|
|
|
GUARANTEED_LEVELS = [5, 10] # First and second guaranteed levels
|
|
|
|
def get_current_question():
|
|
"""Get current question data from session"""
|
|
current_q_index = session.get('current_question', 0)
|
|
questions = session.get('questions', [])
|
|
|
|
if current_q_index >= len(questions):
|
|
return None
|
|
|
|
return questions[current_q_index], current_q_index
|
|
|
|
def calculate_guaranteed_prize(current_index):
|
|
"""Calculate the guaranteed prize based on current question index"""
|
|
final_score = 0
|
|
for level in sorted(GUARANTEED_LEVELS, reverse=True):
|
|
if current_index + 1 >= level:
|
|
final_score = PRIZE_LEVELS[level - 1] if level <= len(PRIZE_LEVELS) else 0
|
|
break
|
|
return final_score
|
|
|
|
@app.route('/')
|
|
def index():
|
|
return render_template('index.html')
|
|
|
|
@app.route('/start')
|
|
def start_game():
|
|
# Initialize game session
|
|
session['score'] = 0
|
|
session['current_question'] = 0
|
|
session['lifelines'] = ['fifty_fifty']
|
|
session['questions'] = random.sample(questions_data, min(15, len(questions_data))) # Select up to 15 random questions
|
|
return render_template('game.html')
|
|
|
|
@app.route('/get_question')
|
|
def get_question():
|
|
current_q_index = session.get('current_question', 0)
|
|
|
|
# Check if game is over (15 questions answered or no more questions)
|
|
if current_q_index >= len(session.get('questions', [])) or current_q_index >= 15:
|
|
return jsonify({
|
|
"game_over": True,
|
|
"final_score": session.get('score', 0)
|
|
})
|
|
|
|
question_data = session['questions'][current_q_index]
|
|
|
|
return jsonify({
|
|
"question_number": current_q_index + 1,
|
|
"question": question_data['question'],
|
|
"options": question_data['options'],
|
|
"current_prize": PRIZE_LEVELS[current_q_index] if current_q_index < len(PRIZE_LEVELS) else 1000000,
|
|
"game_over": False
|
|
})
|
|
|
|
@app.route('/answer', methods=['POST'])
|
|
def check_answer():
|
|
data = request.get_json()
|
|
answer = data.get('answer', '')
|
|
|
|
question_info = get_current_question()
|
|
if not question_info:
|
|
return jsonify({"error": "No more questions"})
|
|
|
|
question_data, current_q_index = question_info
|
|
correct = answer == question_data['correct_answer']
|
|
|
|
if correct:
|
|
session['current_q_index'] = current_q_index + 1
|
|
session['score'] = PRIZE_LEVELS[current_q_index] if current_q_index < len(PRIZE_LEVELS) else session.get('score', 0)
|
|
|
|
# Check if game is won (15th question answered correctly)
|
|
game_won = session['current_question'] >= min(15, len(session.get('questions', [])))
|
|
|
|
return jsonify({
|
|
"correct": True,
|
|
"correct_answer": question_data['correct_answer'],
|
|
"final_score": session['score'],
|
|
"game_over": game_won
|
|
})
|
|
else:
|
|
# Game over with last guaranteed prize
|
|
final_score = calculate_guaranteed_prize(current_q_index)
|
|
|
|
return jsonify({
|
|
"correct": False,
|
|
"correct_answer": question_data['correct_answer'],
|
|
"final_score": final_score,
|
|
"game_over": True
|
|
})
|
|
|
|
@app.route('/lifeline/<lifeline_name>')
|
|
def use_lifeline(lifeline_name):
|
|
if lifeline_name != 'fifty_fifty':
|
|
return jsonify({"error": "Unknown lifeline"})
|
|
|
|
if 'fifty_fifty' not in session.get('lifelines', []):
|
|
return jsonify({"error": "Lifeline already used"})
|
|
|
|
question_info = get_current_question()
|
|
if not question_info:
|
|
return jsonify({"error": "No current question"})
|
|
|
|
# Remove the lifeline from available lifelines
|
|
session['lifelines'].remove('fifty_fifty')
|
|
|
|
question_data, _ = question_info
|
|
correct_answer = question_data['correct_answer']
|
|
options = question_data['options']
|
|
|
|
# Find indices of wrong answers to remove (we need to remove 2)
|
|
wrong_indices = [i for i, option in enumerate(options) if option != correct_answer]
|
|
|
|
# Randomly select 2 wrong indices to remove
|
|
indices_to_remove = random.sample(wrong_indices, min(2, len(wrong_indices)))
|
|
indices_to_remove.sort(reverse=True) # Sort in descending order for safe removal
|
|
|
|
return jsonify({
|
|
"remove_indices": indices_to_remove
|
|
})
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True) |