BilalCode's picture
Update app.py
a7187b1 verified
Raw
History Blame Contribute Delete
7.95 kB
import streamlit as st
import random
st.set_page_config(page_title="Mini Game Arcade", layout="wide")
# Initialize session state
if "score" not in st.session_state:
st.session_state.score = {}
if "guessed_letters" not in st.session_state:
st.session_state.guessed_letters = set()
if "scramble_word" not in st.session_state:
st.session_state.scramble_word = None
if "secret_number" not in st.session_state:
st.session_state.secret_number = random.randint(1, 10)
if "math_a" not in st.session_state:
st.session_state.math_a = random.randint(1, 10)
if "math_b" not in st.session_state:
st.session_state.math_b = random.randint(1, 10)
if "emoji_question" not in st.session_state:
emojis = {"🍎": "apple", "🚗": "car", "🐶": "dog", "🎸": "guitar"}
st.session_state.emoji_question = random.choice(list(emojis.items()))
if "trivia_question" not in st.session_state:
st.session_state.trivia_question = {
"question": "What is the capital of France?",
"options": ["Paris", "London", "Rome", "Berlin"],
"answer": "Paris"
}
if "hangman_word" not in st.session_state:
st.session_state.hangman_word = "apple"
# Game list
GAMES = [
"Rock Paper Scissors",
"Guess the Number",
"Word Scramble",
"Emoji Quiz",
"Math Quiz",
"Hangman",
"Coin Toss",
"Dice Roll",
"Typing Speed Test",
"Trivia"
]
# Sidebar layout
st.sidebar.title("🎮 Mini Game Arcade")
selected_game = st.sidebar.selectbox("Select a Game", GAMES)
st.sidebar.markdown("---")
if st.sidebar.button("🔄 Reset Score"):
st.session_state.score = {}
st.title(f"🕹️ {selected_game}")
# Score tracking
def update_score(game, won):
if game not in st.session_state.score:
st.session_state.score[game] = {"wins": 0, "losses": 0}
if won:
st.session_state.score[game]["wins"] += 1
else:
st.session_state.score[game]["losses"] += 1
# Game Functions
def rock_paper_scissors():
choices = ["Rock", "Paper", "Scissors"]
user = st.radio("✊ Choose your move", choices, horizontal=True)
if st.button("Play"):
comp = random.choice(choices)
st.write(f"🤖 Computer chose: **{comp}**")
if user == comp:
st.info("It's a draw!")
elif (user == "Rock" and comp == "Scissors") or (user == "Paper" and comp == "Rock") or (user == "Scissors" and comp == "Paper"):
st.success("You win!")
update_score("Rock Paper Scissors", True)
else:
st.error("You lose!")
update_score("Rock Paper Scissors", False)
def guess_the_number():
guess = st.number_input("🔢 Guess a number between 1 and 10", min_value=1, max_value=10, step=1)
if st.button("Check Guess"):
if guess == st.session_state.secret_number:
st.success("Correct!")
update_score("Guess the Number", True)
st.session_state.secret_number = random.randint(1, 10)
else:
st.error("Wrong! Try again.")
update_score("Guess the Number", False)
def word_scramble():
words = ["streamlit", "python", "arcade", "game", "guess"]
if not st.session_state.scramble_word:
word = random.choice(words)
scrambled = "".join(random.sample(word, len(word)))
st.session_state.scramble_word = (word, scrambled)
st.write(f"🔀 Unscramble this word: `{st.session_state.scramble_word[1]}`")
user_input = st.text_input("Your guess:")
if st.button("Submit"):
if user_input.lower() == st.session_state.scrble_word[0]:
st.success("Correct!")
update_score("Word Scramble", True)
st.session_state.scramble_word = None
else:
st.error("Incorrect!")
update_score("Word Scramble", False)
def emoji_quiz():
emoji, answer = st.session_state.emoji_question
st.write(f"❓ What does this emoji mean? {emoji}")
guess = st.text_input("Your answer:")
if st.button("Submit Answer"):
if guess.lower() == answer:
st.success("Correct!")
update_score("Emoji Quiz", True)
emojis = {"🍎": "apple", "🚗": "car", "🐶": "dog", "🎸": "guitar"}
st.session_state.emoji_question = random.choice(list(emojis.items()))
else:
st.error("Nope!")
update_score("Emoji Quiz", False)
def math_quiz():
a, b = st.session_state.math_a, st.session_state.math_b
st.write(f"➕ What is {a} + {b}?")
ans = st.number_input("Answer:", step=1)
if st.button("Submit Answer"):
if ans == a + b:
st.success("Correct!")
update_score("Math Quiz", True)
else:
st.error("Incorrect!")
update_score("Math Quiz", False)
st.session_state.math_a = random.randint(1, 10)
st.session_state.math_b = random.randint(1, 10)
def hangman():
word = st.session_state.hangman_word
guess = st.text_input("🔤 Guess a letter:")
if st.button("Guess"):
st.session_state.guessed_letters.add(guess.lower())
display = [c if c in st.session_state.guessed_letters else "_" for c in word]
st.write("Word: " + " ".join(display))
if "_" not in display:
st.success("You guessed the word!")
update_score("Hangman", True)
st.session_state.guessed_letters.clear()
st.session_state.hangman_word = "apple"
elif len(st.session_state.guessed_letters) > 6:
st.error("Too many wrong guesses!")
update_score("Hangman", False)
st.session_state.guessed_letters.clear()
st.session_state.hangman_word = "apple"
def coin_toss():
choice = st.radio("🪙 Heads or Tails?", ["Heads", "Tails"], horizontal=True)
if st.button("Flip Coin"):
result = random.choice(["Heads", "Tails"])
st.write(f"It was: **{result}**")
if choice == result:
st.success("You win!")
update_score("Coin Toss", True)
else:
st.error("You lose!")
update_score("Coin Toss", False)
def dice_roll():
if st.button("🎲 Roll the Dice"):
result = random.randint(1, 6)
st.write(f"You rolled a **{result}**")
if result == 6:
st.success("🎉 Jackpot!")
update_score("Dice Roll", True)
else:
update_score("Dice Roll", False)
def typing_test():
prompt = "streamlit is fun"
st.write(f"⌨️ Type this exactly: `{prompt}`")
typed = st.text_input("Start typing:")
if st.button("Submit Typing"):
if typed.strip().lower() == prompt:
st.success("Perfect!")
update_score("Typing Speed Test", True)
else:
st.error("Mismatch!")
update_score("Typing Speed Test", False)
def trivia():
q = st.session_state.trivia_question
user_ans = st.radio("🌍 " + q["question"], q["options"])
if st.button("Submit Answer"):
if user_ans == q["answer"]:
st.success("Correct!")
update_score("Trivia", True)
else:
st.error("Wrong!")
update_score("Trivia", False)
# Dispatcher
GAME_FUNCTIONS = {
"Rock Paper Scissors": rock_paper_scissors,
"Guess the Number": guess_the_number,
"Word Scramble": word_scramble,
"Emoji Quiz": emoji_quiz,
"Math Quiz": math_quiz,
"Hangman": hangman,
"Coin Toss": coin_toss,
"Dice Roll": dice_roll,
"Typing Speed Test": typing_test,
"Trivia": trivia,
}
# Run selected game
GAME_FUNCTIONS[selected_game]()
# Score summary
st.markdown("---")
with st.expander("📊 Score Summary"):
for game, result in st.session_state.score.items():
st.write(f"**{game}** — ✅ Wins: {result['wins']} | ❌ Losses: {result['losses']}")
# Footer
st.markdown("---")
st.markdown("<center><sub>🎯 Made by <strong>Muhammad Bilal Hussain</strong></sub></center>", unsafe_allow_html=True)