Spaces:
Sleeping
Sleeping
import streamlit as st | |
import pandas as pd | |
import plotly.express as px | |
import random | |
import uuid | |
from datetime import datetime | |
from streamlit_flow import streamlit_flow | |
from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge | |
from streamlit_flow.layouts import TreeLayout | |
# 🐱 Cat Rider and Gear Data | |
CAT_RIDERS = [ | |
{"name": "Whiskers", "type": "Speed", "emoji": "🐾", "strength": 3, "skill": 7}, | |
{"name": "Fluffy", "type": "Bravery", "emoji": "🦁", "strength": 5, "skill": 5}, | |
{"name": "Midnight", "type": "Stealth", "emoji": "🌑", "strength": 4, "skill": 6}, | |
{"name": "Bella", "type": "Charm", "emoji": "😺", "strength": 2, "skill": 8} | |
] | |
RIDING_GEAR = [ | |
{"name": "Feathered Boots", "type": "Agility", "strength": 2}, | |
{"name": "Golden Armor", "type": "Defense", "strength": 4}, | |
{"name": "Magic Whisker Wand", "type": "Magic", "strength": 3}, | |
{"name": "Sleek Shadow Cape", "type": "Stealth", "strength": 1} | |
] | |
# 🌍 Game World Data (Expanded to 10 Situations) | |
SITUATIONS = [ | |
{"id": "feline_escape", "name": "The Great Feline Escape", "description": "Your cat rider is trapped in an old mansion, which is about to be demolished. Using agility, wit, and bravery, orchestrate the perfect escape before the walls crumble! 🏚️", "emoji": "🚪", "type": "escape", "preferred_action": "agility"}, | |
{"id": "lost_temple", "name": "The Treasure of the Lost Temple", "description": "On a quest to retrieve an ancient artifact, your cat rider must navigate through a labyrinth filled with traps and guardian spirits. Don't let the spooky ghosts get you! 👻", "emoji": "🏛️", "type": "exploration", "preferred_action": "resourcefulness"}, | |
{"id": "royal_tournament", "name": "The Royal Tournament", "description": "Compete in a grand tournament where the finest cat riders showcase their skills and bravery to earn the title of the Royal Rider. Prepare for a showdown with noble feline adversaries! 🐱", "emoji": "👑", "type": "competition", "preferred_action": "bravery"}, | |
{"id": "sky_race", "name": "The Sky Race", "description": "Compete in the annual Sky Race, where your cat rider flies across the skies on a magical broomstick! Watch out for lightning storms and mischievous crows! 🌩️", "emoji": "☁️", "type": "competition", "preferred_action": "agility"}, | |
{"id": "cheese_heist", "name": "The Great Cheese Heist", "description": "Your cat rider must sneak into the royal pantry to steal the legendary Cheese of Destiny. Beware – the palace mice are guarding it! 🧀", "emoji": "🧀", "type": "heist", "preferred_action": "stealth"}, | |
{"id": "pirate_cove", "name": "The Pirate Cove", "description": "Sail the high seas with your trusty crew of cats and uncover the secrets of Pirate Cove. Beware of the treacherous Sea Dogs! 🏴☠️", "emoji": "🏴☠️", "type": "exploration", "preferred_action": "bravery"}, | |
{"id": "feline_moon_mission", "name": "The Feline Moon Mission", "description": "Blast off into space! Your mission is to plant the flag of Catopia on the moon. Pilot your rocket through an asteroid field! 🚀", "emoji": "🌕", "type": "exploration", "preferred_action": "resourcefulness"}, | |
{"id": "purr_summit", "name": "The Purr Summit", "description": "Join a secret gathering of the most intellectual cats in the world. Engage in a battle of wits and wisdom to become the Grand Purr! 🧠", "emoji": "📜", "type": "debate", "preferred_action": "insight"}, | |
{"id": "feline_invasion", "name": "The Feline Invasion", "description": "Aliens have invaded Earth and only your cat rider can save the planet! Use cunning strategies to repel the invaders! 👽", "emoji": "👽", "type": "battle", "preferred_action": "strategy"}, | |
{"id": "eternal_catnap", "name": "The Eternal Catnap", "description": "You've entered a sacred temple where cats nap for centuries. Can you navigate the dream world and escape before you too are lulled into eternal slumber? 🛏️", "emoji": "💤", "type": "exploration", "preferred_action": "stealth"} | |
] | |
# 🧠 Expanded Actions (10 Actions) | |
ACTIONS = [ | |
{"id": "stealth", "name": "Use Stealth", "description": "Sneak past obstacles or enemies without being detected. You're like a ninja in the shadows! 🐾", "emoji": "🤫", "type": "skill"}, | |
{"id": "agility", "name": "Showcase Agility", "description": "Perform impressive acrobatic maneuvers to overcome challenges. Cats always land on their feet, right? 🏃", "emoji": "🏃", "type": "physical"}, | |
{"id": "charm", "name": "Charm Others", "description": "Use your cat's natural charisma to win over allies or distract foes. Who could resist those cute eyes? 😻", "emoji": "😻", "type": "social"}, | |
{"id": "resourcefulness", "name": "Be Resourceful", "description": "Utilize the environment or items in creative ways to solve problems. Think on your paws! 🧠", "emoji": "🧠", "type": "mental"}, | |
{"id": "bravery", "name": "Show Bravery", "description": "Face dangers head-on with your feline courage. Not all heroes wear capes – some wear fur! 🦁", "emoji": "🦁", "type": "physical"}, | |
{"id": "strategy", "name": "Develop a Strategy", "description": "Use tactical thinking to outsmart opponents and gain the upper hand in battle. Brains over brawn! 🧠", "emoji": "🧠", "type": "mental"}, | |
{"id": "speed", "name": "Sprint Away", "description": "Run faster than you've ever run before to escape danger. Like a cat fleeing a vacuum cleaner! 🏃♀️", "emoji": "🏃♀️", "type": "physical"}, | |
{"id": "insight", "name": "Use Insight", "description": "Tap into ancient feline wisdom to solve puzzles and mysteries. A cat always knows! 🔮", "emoji": "🔮", "type": "mental"}, | |
{"id": "distraction", "name": "Create a Distraction", "description": "Use cunning tricks and diversions to draw attention away from your real goal. Look over there! 🪄", "emoji": "🪄", "type": "mental"}, | |
{"id": "negotiation", "name": "Negotiate", "description": "Use diplomacy and clever negotiation to get out of a tight spot. Every cat has their price! 💼", "emoji": "💼", "type": "social"} | |
] | |
# Expanded conclusions for outcomes - 10 items each for success and failure | |
SUCCESS_CONCLUSIONS = [ | |
"Your swift paws led you to victory! 🎉", | |
"You pounced at the perfect moment! 🏆", | |
"The stars aligned for your cat rider! 🌟", | |
"You navigated the challenge like a true feline champion! 🐱", | |
"Victory is sweet, just like a bowl of fresh milk! 🥛", | |
"Your opponents are left in awe of your skills! 😺", | |
"You’ve earned the title of Cat Commander! 🏅", | |
"All the other cats are jealous of your agility! 🏃♂️", | |
"Your strategy was flawless, and the victory is yours! 🎖️", | |
"Your cat rider is now a legend in the feline world! 👑" | |
] | |
FAILURE_CONCLUSIONS = [ | |
"You tried your best, but it just wasn’t enough. 😿", | |
"Maybe next time, kitty. Keep your tail up! 🐾", | |
"That didn’t go as planned. Time for a catnap to recover! 💤", | |
"Even the best cats have their off days. 😔", | |
"The challenge was too great this time. Better luck next time! 🍀", | |
"You might need more than nine lives to get through this. 🐈", | |
"The enemy was too clever for your plan. 🧠", | |
"You tripped over your own paws! 🐾", | |
"The cat gods were not in your favor today. 🙀", | |
"It’s okay, every cat has a learning curve. 📚" | |
] | |
# 🧠 Game Mechanics | |
def generate_situation(): | |
return random.choice(SITUATIONS) | |
def generate_actions(): | |
return random.sample(ACTIONS, min(3, len(ACTIONS))) | |
def evaluate_action(situation, action, gear_strength, rider_skill, history): | |
# Determine if the action is the preferred action | |
base_success_chance = (gear_strength + rider_skill) / 2 | |
if action['id'] == situation['preferred_action']: | |
success_chance = base_success_chance + 30 # Boost success chance for preferred action | |
else: | |
success_chance = base_success_chance | |
if action['id'] in history: | |
success_chance += history[action['id']] * 2 | |
outcome = random.randint(1, 100) <= success_chance | |
return outcome, success_chance | |
def generate_encounter_conclusion(situation, action, outcome): | |
if outcome: | |
return random.choice(SUCCESS_CONCLUSIONS) | |
else: | |
return random.choice(FAILURE_CONCLUSIONS) | |
# 🌳 Journey Visualization | |
def create_heterogeneous_graph(history_df): | |
nodes = [] | |
edges = [] | |
for index, row in history_df.iterrows(): | |
scenario_id = f"scenario-{row['situation_id']}" | |
action_id = f"action-{row['action_id']}-{index}" | |
conclusion_id = f"conclusion-{index}" | |
# Scenario node | |
scenario_node = StreamlitFlowNode(scenario_id, (0, 0), {'content': f"{row['situation_emoji']} {row['situation_name']}"}, 'output', 'bottom', 'top', shape='ellipse') | |
nodes.append(scenario_node) | |
# Action node | |
action_node = StreamlitFlowNode(action_id, (0, 0), {'content': f"{row['action_emoji']} {row['action_name']}"}, 'output', 'bottom', 'top', shape='ellipse') | |
nodes.append(action_node) | |
# Conclusion node | |
conclusion_node = StreamlitFlowNode(conclusion_id, (0, 0), {'content': f"{row['conclusion']}\n💪 Gear: {row['gear_strength']:.2f}"}, 'output', 'bottom', 'top', shape='ellipse') | |
nodes.append(conclusion_node) | |
# Edges | |
edges.append(StreamlitFlowEdge(f"{scenario_id}-{action_id}", scenario_id, action_id, animated=True)) | |
edges.append(StreamlitFlowEdge(f"{action_id}-{conclusion_id}", action_id, conclusion_id, animated=True)) | |
# Link to previous scenario | |
if index > 0: | |
prev_conclusion_id = f"conclusion-{index-1}" | |
edges.append(StreamlitFlowEdge(f"{prev_conclusion_id}-{scenario_id}", prev_conclusion_id, scenario_id, animated=True, dashed=True)) | |
return nodes, edges | |
# 📝 Markdown Preview with Single Scenario Entry and Attempts | |
def create_markdown_preview(history_df): | |
markdown = "## 🌳 Journey Preview\n\n" | |
grouped_scenarios = history_df.groupby('situation_name') | |
for situation_name, group in grouped_scenarios: | |
markdown += f"🌟 **{situation_name}**\n" | |
for _, row in group.iterrows(): | |
markdown += f" ↪ {row['action_emoji']} {row['action_name']}: " | |
markdown += "✅ Success\n" if row['outcome'] else "❌ Failure\n" | |
markdown += f" 📜 {row['conclusion']} 💪 Gear: {row['gear_strength']:.2f} | 🏋️ Skill: {row['rider_skill']:.2f}\n" | |
markdown += "\n" | |
return markdown | |
# 🔄 Update game state with the result of the action | |
def update_game_state(game_state, situation, action, outcome, timestamp): | |
# Generate the encounter conclusion (success or failure) | |
conclusion = generate_encounter_conclusion(situation, action, outcome) | |
# Update stats based on the outcome | |
game_state = update_character_stats(game_state, outcome) | |
# Create a new record for the history | |
new_record = pd.DataFrame({ | |
'user_id': [game_state['user_id']], | |
'timestamp': [timestamp], | |
'situation_id': [situation['id']], | |
'situation_name': [situation['name']], | |
'situation_emoji': [situation['emoji']], | |
'situation_type': [situation['type']], | |
'action_id': [action['id']], | |
'action_name': [action['name']], | |
'action_emoji': [action['emoji']], | |
'action_type': [action['type']], | |
'outcome': [outcome], | |
'conclusion': [conclusion], | |
'gear_strength': [game_state['gear_strength']], | |
'rider_skill': [game_state['rider_skill']], | |
'score': [game_state['score']] | |
}) | |
# Add the new record to the game history DataFrame | |
game_state['history_df'] = pd.concat([game_state['history_df'], new_record], ignore_index=True) | |
# Update the history of actions (tracking how many times each action was used) | |
if action['id'] in game_state['history']: | |
game_state['history'][action['id']] += 1 if outcome else -1 | |
else: | |
game_state['history'][action['id']] = 1 if outcome else -1 | |
return game_state | |
# 🎮 Main Game Application | |
def main(): | |
st.title("🐱 Cat Rider 🏇") | |
# 📜 Game Rules | |
st.markdown(""" | |
### 📜 Game Rules | |
| Step | Description | | |
|------|-------------| | |
| 1️⃣ | Choose your Cat Rider | | |
| 2️⃣ | Select your Riding Gear | | |
| 3️⃣ | Set off on an Adventure | | |
| 4️⃣ | Encounter Challenges and Make Decisions | | |
| 5️⃣ | Complete the Quest and Grow Stronger | | |
""") | |
# 🏁 Initialize game state | |
if 'game_state' not in st.session_state: | |
st.session_state.game_state = { | |
'user_id': str(uuid.uuid4()), | |
'score': 0, | |
'history': {}, | |
'gear_strength': 0, | |
'rider_skill': 0, | |
'cat_rider': None, | |
'riding_gear': None, | |
'history_df': pd.DataFrame(columns=['user_id', 'timestamp', 'situation_id', 'situation_name', 'situation_emoji', 'situation_type', 'action_id', 'action_name', 'action_emoji', 'action_type', 'outcome', 'conclusion', 'gear_strength', 'rider_skill', 'score']) | |
} | |
# 🐱 Cat Rider Selection | |
if st.session_state.game_state['cat_rider'] is None: | |
st.markdown("## Choose Your Cat Rider:") | |
cols = st.columns(len(CAT_RIDERS)) | |
for i, rider in enumerate(CAT_RIDERS): | |
# Adding unique key for each button | |
if cols[i].button(f"{rider['emoji']} {rider['name']} ({rider['type']})", key=f"rider_{i}"): | |
st.session_state.game_state['cat_rider'] = rider | |
st.session_state.game_state['rider_skill'] = rider['skill'] | |
# 🏇 Riding Gear Selection | |
if st.session_state.game_state['riding_gear'] is None and st.session_state.game_state['cat_rider'] is not None: | |
st.markdown("## Select Your Riding Gear:") | |
cols = st.columns(len(RIDING_GEAR)) | |
for i, gear in enumerate(RIDING_GEAR): | |
# Adding unique key for each button | |
if cols[i].button(f"{gear['name']} ({gear['type']})", key=f"gear_{i}"): | |
st.session_state.game_state['riding_gear'] = gear | |
st.session_state.game_state['gear_strength'] = gear['strength'] | |
# 🎭 Game Loop | |
if st.session_state.game_state['cat_rider'] is not None and st.session_state.game_state['riding_gear'] is not None: | |
situation = generate_situation() | |
actions = generate_actions() | |
st.markdown(f"## {situation['emoji']} Current Situation: {situation['name']} ({situation['type']})") | |
st.markdown(situation['description']) | |
st.markdown("### 🎭 Choose your action:") | |
cols = st.columns(3) | |
for i, action in enumerate(actions): | |
# Adding unique key for each button | |
if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})", key=f"action_{i}"): | |
outcome, success_chance = evaluate_action(situation, action, st.session_state.game_state['gear_strength'], st.session_state.game_state['rider_skill'], st.session_state.game_state['history']) | |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
st.markdown(f"You decided to: **{action['name']}** ({action['type']})") | |
st.markdown(action['description']) | |
st.markdown(f"**Outcome:** {'✅ Success!' if outcome else '❌ Failure.'}") | |
st.markdown(f"**Success Chance:** {success_chance:.2f}%") | |
if outcome: | |
st.session_state.game_state['score'] += 1 | |
# 🔄 Update game state | |
st.session_state.game_state = update_game_state( | |
st.session_state.game_state, | |
situation, | |
action, | |
outcome, | |
timestamp | |
) | |
# Display conclusion | |
conclusion = st.session_state.game_state['history_df'].iloc[-1]['conclusion'] | |
st.markdown(f"**Encounter Conclusion:** {conclusion}") | |
# Display updated stats | |
st.markdown(f"**Updated Stats:**") | |
st.markdown(f"💪 Gear Strength: {st.session_state.game_state['gear_strength']:.2f}") | |
st.markdown(f"🏋️ Rider Skill: {st.session_state.game_state['rider_skill']:.2f}") | |
# 📝 Display Markdown Preview | |
if not st.session_state.game_state['history_df'].empty: | |
st.markdown(create_markdown_preview(st.session_state.game_state['history_df'])) | |
# 🌳 Display Heterogeneous Journey Graph | |
if not st.session_state.game_state['history_df'].empty: | |
st.markdown("## 🌳 Your Journey (Heterogeneous Graph)") | |
nodes, edges = create_heterogeneous_graph(st.session_state.game_state['history_df']) | |
try: | |
streamlit_flow('cat_rider_flow', | |
nodes, | |
edges, | |
layout=TreeLayout(direction='down'), | |
fit_view=True, | |
height=600) | |
except Exception as e: | |
st.error(f"An error occurred while rendering the journey graph: {str(e)}") | |
st.markdown("Please try refreshing the page if the graph doesn't appear.") | |
# 📊 Character Stats Visualization | |
data = {"Stat": ["Gear Strength 🛡️", "Rider Skill 🏇"], | |
"Value": [st.session_state.game_state['gear_strength'], st.session_state.game_state['rider_skill']]} | |
df = pd.DataFrame(data) | |
fig = px.bar(df, x='Stat', y='Value', title="Cat Rider Stats 📊") | |
st.plotly_chart(fig) | |
if __name__ == "__main__": | |
main() | |