Spaces:
Sleeping
Sleeping
File size: 9,208 Bytes
0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e 0fbec67 60b006e |
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 |
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
# ๐ Game World Data (unchanged)
SITUATIONS = [ ... ] # Your existing SITUATIONS data
ACTIONS = [ ... ] # Your existing ACTIONS data
# ๐ฒ Game Mechanics (unchanged)
def generate_situation():
return random.choice(SITUATIONS)
def generate_actions():
return random.sample(ACTIONS, 3)
def evaluate_action(action, gear_strength, rider_skill, history):
base_success_chance = (gear_strength + rider_skill) / 2
if action['id'] in history:
success_chance = base_success_chance + (history[action['id']] * 2)
else:
success_chance = base_success_chance
outcome = random.randint(1, 100) <= success_chance
return outcome, success_chance
def generate_encounter_conclusion(situation, action, outcome):
# Scenario-based conclusions
if outcome:
conclusions = [
f"Your {action['name']} was successful! You've overcome the challenges of {situation['name']}. ๐",
f"Through clever use of {action['name']}, you've triumphed in the {situation['name']}! ๐",
f"Your mastery of {action['name']} led to victory in the {situation['name']}! ๐ช"
]
else:
conclusions = [
f"Despite your efforts with {action['name']}, you couldn't overcome the {situation['name']}. ๐",
f"Your attempt at {action['name']} wasn't enough in the {situation['name']}. ๐ข",
f"The challenges of {situation['name']} proved too great this time. ๐"
]
return random.choice(conclusions)
def update_character_stats(game_state, outcome):
# Improve stats only on success
if outcome:
game_state['gear_strength'] = min(10, game_state['gear_strength'] + random.uniform(0.1, 0.5))
game_state['rider_skill'] = min(10, game_state['rider_skill'] + random.uniform(0.1, 0.5))
return game_state
# ๐ณ Journey Visualization with Heterogeneous Graph Structure (unchanged)
def create_heterogeneous_graph(history_df):
# Your existing node and edge creation logic
...
# ๐ Markdown Preview (unchanged)
def create_markdown_preview(history_df):
markdown = "## ๐ณ Journey Preview\n\n"
for index, row in history_df.iterrows():
indent = " " * (index * 3)
markdown += f"{indent}๐ **{row['situation_name']}** ({row['situation_type']})\n"
markdown += f"{indent} โช {row['action_emoji']} {row['action_name']} ({row['action_type']}): "
markdown += "โ
Success\n" if row['outcome'] else "โ Failure\n"
markdown += f"{indent} ๐ {row['conclusion']}\n"
markdown += f"{indent} ๐ช Gear: {row['gear_strength']:.2f} | ๐๏ธ Skill: {row['rider_skill']:.2f}\n\n"
return markdown
# ๐ Game State Management (unchanged)
def update_game_state(game_state, situation, action, outcome, timestamp):
# Update based on encounter outcome
conclusion = generate_encounter_conclusion(situation, action, outcome)
game_state = update_character_stats(game_state, outcome)
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']]
})
game_state['history_df'] = pd.concat([game_state['history_df'], new_record], ignore_index=True)
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 (main logic with improvements)
def main():
st.title("๐ฑ Cat Rider ๐")
st.markdown("""
## Welcome to Cat Rider!
In this immersive adventure, you will explore the thrilling world of feline riders. This game sets the stage for dramatic situations and guided storytelling with engaging interactive elements.
""")
# ๐ Game Rules (unchanged)
st.markdown("""
### ๐ Game Rules
| ๐ค๏ธ Step | ๐ Description |
|---------|----------------|
| 1๏ธโฃ | Choose your Cat Rider |
| 2๏ธโฃ | Select the Riding Gear |
| 3๏ธโฃ | Set off on an Adventure |
| 4๏ธโฃ | Encounter Challenges and Make Decisions |
| 5๏ธโฃ | Complete the Quest and Grow Stronger |
""")
# ๐ Initialize game state (unchanged)
if 'game_state' not in st.session_state:
st.session_state.game_state = {
'user_id': str(uuid.uuid4()),
'score': 0,
'history': {},
'gear_strength': 5,
'rider_skill': 5,
'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'])
}
# ๐ Game Stats (unchanged)
st.sidebar.markdown("## ๐ Game Stats")
st.sidebar.markdown(f"**Score:** {st.session_state.game_state['score']}")
st.sidebar.markdown(f"**Gear Strength:** {st.session_state.game_state['gear_strength']:.2f}")
st.sidebar.markdown(f"**Rider Skill:** {st.session_state.game_state['rider_skill']:.2f}")
# ๐ญ Game Loop
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):
if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})"):
outcome, success_chance = evaluate_action(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 (unchanged)
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 (unchanged)
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 (unchanged)
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()
|