import os import pandas as pd import streamlit as st import random import uuid import json import time import requests # For calling the Groq API import plotly.express as px import plotly.graph_objects as go from streamlit.components.v1 import html # Define file paths LEADERBOARD_FILE = "leaderboard.csv" GAME_DATA_FILE = "game_data.json" PLAYERS_FILE = "players.json" # Groq API Configuration GROQ_API_KEY = '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' GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" # Define questions for multiple topics with at least 20 questions each questions_db = { "Geography": [ ("What is the capital of France?", ["Paris", "London", "Berlin", "Madrid"], "Paris"), ("What is the largest country in the world by land area?", ["Canada", "United States", "Russia", "China"], "Russia"), ("Which river flows through Egypt?", ["Nile", "Amazon", "Ganges", "Yangtze"], "Nile"), ("What is the capital of Japan?", ["Tokyo", "Kyoto", "Osaka", "Sapporo"], "Tokyo"), ("Which is the smallest country in the world?", ["Monaco", "Vatican City", "San Marino", "Liechtenstein"], "Vatican City"), # Add more questions... ], "Science": [ ("What is the chemical symbol for water?", ["H2O", "CO2", "O2", "H2"], "H2O"), ("What is the powerhouse of the cell?", ["Nucleus", "Mitochondria", "Ribosome", "Endoplasmic Reticulum"], "Mitochondria"), ("What planet is known as the Red Planet?", ["Venus", "Mars", "Jupiter", "Saturn"], "Mars"), ("Who developed the theory of relativity?", ["Isaac Newton", "Albert Einstein", "Nikola Tesla", "Marie Curie"], "Albert Einstein"), ("What is the largest organ in the human body?", ["Heart", "Skin", "Lungs", "Brain"], "Skin"), # Add more questions... ], "Math": [ ("What is 5 * 12?", ["50", "60", "55", "70"], "60"), ("What is the square root of 64?", ["6", "7", "8", "9"], "8"), ("What is 15 + 25?", ["35", "40", "45", "50"], "40"), ("What is the value of pi?", ["3.14", "3.15", "3.16", "3.17"], "3.14"), ("What is 20 / 4?", ["5", "6", "7", "8"], "5"), # Add more questions... ], "IPL": [ ("Which IPL team won the 2020 IPL season?", ["Mumbai Indians", "Delhi Capitals", "Royal Challengers Bangalore", "Chennai Super Kings"], "Mumbai Indians"), ("Who is the all-time highest run-scorer in IPL history?", ["Virat Kohli", "Rohit Sharma", "Suresh Raina", "Chris Gayle"], "Virat Kohli"), ("Who won the first-ever IPL match?", ["Kolkata Knight Riders", "Royal Challengers Bangalore", "Chennai Super Kings", "Mumbai Indians"], "Kolkata Knight Riders"), ("Which IPL team is known as the 'Yellow Army'?", ["Chennai Super Kings", "Mumbai Indians", "Delhi Capitals", "Sunrisers Hyderabad"], "Chennai Super Kings"), ("Who hit the most sixes in the 2020 IPL season?", ["Shivam Dube", "AB de Villiers", "Ishan Kishan", "Kieron Pollard"], "Ishan Kishan"), # Add more questions... ] } # Function to load leaderboard from CSV file def load_leaderboard(): if os.path.exists(LEADERBOARD_FILE): leaderboard_df = pd.read_csv(LEADERBOARD_FILE, names=['name', 'score', 'question', 'answer', 'correct', 'topic', 'avatar'], header=0) return leaderboard_df return pd.DataFrame(columns=['name', 'score', 'question', 'answer', 'correct', 'topic', 'avatar']) # Function to save leaderboard data to CSV def save_leaderboard(leaderboard_df): leaderboard_df.to_csv(LEADERBOARD_FILE, index=False) # Function to create a new game def create_game(): game_id = str(uuid.uuid4())[:8] # Generate a unique Game ID selected_topics = st.multiselect("Choose Topics", list(questions_db.keys())) # Topic selection num_questions = st.selectbox("Select the number of questions", [5, 10, 15, 20]) if selected_topics: # Collect questions from the selected topics questions = [] for topic in selected_topics: questions.extend(random.sample(questions_db[topic], num_questions // len(selected_topics))) random.shuffle(questions) # Shuffle questions game_data = {'game_id': game_id, 'topics': selected_topics, 'questions': questions} # Store the game data to a JSON file if os.path.exists(GAME_DATA_FILE): with open(GAME_DATA_FILE, "r") as file: all_games = json.load(file) else: all_games = {} all_games[game_id] = game_data with open(GAME_DATA_FILE, "w") as file: json.dump(all_games, file) st.success(f"Game created successfully! Game ID: {game_id}") return game_id, selected_topics, questions else: st.error("Please select at least one topic.") # Function to join a game def join_game(): game_id = st.text_input("Enter Game ID to join:") if game_id: with open(GAME_DATA_FILE, "r") as file: all_games = json.load(file) if game_id in all_games: game_data = all_games[game_id] st.session_state['game_data'] = game_data st.success(f"Joined game with ID: {game_id}") start_game(game_data) # Start the game with the joined data else: st.error("Invalid Game ID. Please check and try again.") # Function to start the game def start_game(game_data): topics = game_data['topics'] questions = game_data['questions'] username = st.text_input("Enter your name:") avatar = st.selectbox("Choose your Avatar", ["🐱", "🐶", "🦄", "👽", "🎮"]) st.session_state['avatar'] = avatar if username: if 'answers' not in st.session_state: st.session_state['answers'] = [""] * len(questions) score = 0 current_question = 0 while current_question < len(questions): question, options, correct_answer = questions[current_question] topic = next(topic for topic in topics if any(q[0] == question for q in questions_db[topic])) if current_question not in st.session_state.get('options', {}): st.session_state['options'] = {current_question: options} options = st.session_state['options'][current_question] answer = st.radio(f"Question {current_question+1}: {question}", options, key=f"q{current_question}") st.session_state['answers'][current_question] = answer with st.empty(): timer_text = st.empty() for time_left in range(10, 0, -1): timer_text.text(f"Time left for this question: {time_left} seconds") time.sleep(1) # Display Correct or Incorrect after the timer ends if answer == correct_answer: st.write("Correct!") score += 10 else: st.write(f"Incorrect! The correct answer is: {correct_answer}") current_question += 1 submit_button = st.button("Submit Answers") if submit_button: leaderboard_df = load_leaderboard() new_row = pd.DataFrame({ 'name': [username], 'score': [score], 'question': [', '.join([q[0] for q in questions])], 'answer': [', '.join(st.session_state['answers'])], 'correct': [', '.join(['Yes' if st.session_state['answers'][i].strip().lower() == questions[i][2].lower() else 'No' for i in range(len(st.session_state['answers']))])], 'topic': [', '.join(topics)], 'avatar': [avatar] }) leaderboard_df = pd.concat([leaderboard_df, new_row], ignore_index=True) leaderboard_df = leaderboard_df.sort_values(by='score', ascending=False).reset_index(drop=True) save_leaderboard(leaderboard_df) st.success(f"Game Over! Your final score is {score}") # Function to display the leaderboard def display_dashboard(): leaderboard_df = load_leaderboard() st.subheader("Top 3 Players") top_3 = leaderboard_df.head(3) for index, row in top_3.iterrows(): st.write(f"{row['name']} ({row['score']} points) {row['avatar']}") # Pie chart for the distribution of player scores fig = go.Figure(data=[go.Pie(labels=leaderboard_df['name'], values=leaderboard_df['score'], hole=0.3)]) fig.update_layout(title="Score Distribution") st.plotly_chart(fig) # Bar chart of leaderboard rankings fig = px.bar( leaderboard_df, x='name', y='score', color='name', title="Leaderboard", labels={'name': 'Player', 'score': 'Score'}, hover_data=["avatar"] ) st.plotly_chart(fig) # Animation for first-place winner (balloon effect) first_place = leaderboard_df.iloc[0] if not leaderboard_df.empty else None if first_place is not None: html_code = f"""
Score: {first_place['score']}
Avatar: {first_place['avatar']}