Spaces:
Running
Running
File size: 10,250 Bytes
f36bd3c 80ae2d2 c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 80ae2d2 c92b463 f36bd3c c92b463 80ae2d2 c92b463 80ae2d2 c92b463 f36bd3c c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 c92b463 80ae2d2 f36bd3c c92b463 80ae2d2 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c c92b463 f36bd3c b79cf82 c92b463 f36bd3c c92b463 80ae2d2 c92b463 80ae2d2 f36bd3c c92b463 f36bd3c c92b463 f36bd3c |
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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 |
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"""
<div style="text-align: center;">
<h2>๐ Winner: {first_place['name']} ๐</h2>
<p>Score: {first_place['score']}</p>
<p>Avatar: {first_place['avatar']}</p>
</div>
<div id="balloon" style="position: absolute; top: 50%; left: 50%; animation: float 2s infinite;">
๐๐
</div>
<style>
@keyframes float {{
0% {{ transform: translateY(0); }}
50% {{ transform: translateY(-50px); }}
100% {{ transform: translateY(0); }}
}}
</style>
"""
html(html_code)
# Main function to handle Streamlit app
def main():
st.title('AI Quiz Game')
mode = st.sidebar.selectbox("Select Mode", ["Home", "Create Game", "Join Game", "Leaderboard"])
if mode == "Home":
st.write("Welcome to the Game!")
st.write("You can create a new game, join an existing game, or check the leaderboard.")
display_dashboard()
elif mode == "Create Game":
create_game()
elif mode == "Join Game":
join_game()
elif mode == "Leaderboard":
display_dashboard()
# Run the Streamlit app
if __name__ == "__main__":
main()
|