|
| 1 | +import streamlit as st |
| 2 | +import json |
| 3 | +import random |
| 4 | +import os |
| 5 | + |
| 6 | + |
| 7 | +def load_trivia_data(): |
| 8 | + base_path = os.path.dirname(__file__) # Get the directory of the current script |
| 9 | + json_path = os.path.join(base_path, "bollywood_trivia_data.json") |
| 10 | + with open(json_path, "r") as file: |
| 11 | + data = json.load(file) |
| 12 | + return data["questions"] |
| 13 | + |
| 14 | + |
| 15 | +# Initialize session state for score and current question |
| 16 | +if "score" not in st.session_state: |
| 17 | + st.session_state.score = 0 |
| 18 | +if "question_index" not in st.session_state: |
| 19 | + st.session_state.question_index = 0 |
| 20 | +if "questions" not in st.session_state: |
| 21 | + st.session_state.questions = load_trivia_data() |
| 22 | + random.shuffle(st.session_state.questions) # Shuffle questions for randomness |
| 23 | + |
| 24 | + |
| 25 | +# Display the question and options |
| 26 | +def display_question(): |
| 27 | + question = st.session_state.questions[st.session_state.question_index] |
| 28 | + st.write( |
| 29 | + f"**Question {st.session_state.question_index + 1}:** {question['question']}" |
| 30 | + ) |
| 31 | + |
| 32 | + # Create buttons for options |
| 33 | + for option in question["options"]: |
| 34 | + if st.button(option): |
| 35 | + check_answer(option, question["answer"]) |
| 36 | + |
| 37 | + |
| 38 | +# Check if the answer is correct |
| 39 | +def check_answer(selected_option, correct_answer): |
| 40 | + if selected_option == correct_answer: |
| 41 | + st.session_state.score += 1 |
| 42 | + st.success("Correct!") |
| 43 | + else: |
| 44 | + st.error(f"Wrong! The correct answer is: {correct_answer}") |
| 45 | + |
| 46 | + # Move to the next question |
| 47 | + if st.session_state.question_index < len(st.session_state.questions) - 1: |
| 48 | + st.session_state.question_index += 1 |
| 49 | + else: |
| 50 | + st.write( |
| 51 | + f"Game Over! Your final score is {st.session_state.score}/{len(st.session_state.questions)}" |
| 52 | + ) |
| 53 | + reset_game() |
| 54 | + |
| 55 | + |
| 56 | +# Reset the game |
| 57 | +def reset_game(): |
| 58 | + st.session_state.score = 0 |
| 59 | + st.session_state.question_index = 0 |
| 60 | + st.session_state.questions = load_trivia_data() |
| 61 | + random.shuffle(st.session_state.questions) |
| 62 | + |
| 63 | + |
| 64 | +# Set up the Streamlit app |
| 65 | +st.set_page_config(page_title="Bollywood Movie Trivia Game", page_icon="🎬") |
| 66 | + |
| 67 | +st.title("Bollywood Movie Trivia Game") |
| 68 | +display_question() |
0 commit comments