awacke1 commited on
Commit
f44d20e
ยท
verified ยท
1 Parent(s): d221f27

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +300 -0
app.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ import random
5
+ import uuid
6
+ from datetime import datetime
7
+ from streamlit_flow import streamlit_flow
8
+ from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge
9
+ from streamlit_flow.layouts import TreeLayout
10
+
11
+ # ๐ŸŒ Game World Data
12
+ SITUATIONS = [
13
+ {
14
+ "id": "feline_escape",
15
+ "name": "The Great Feline Escape",
16
+ "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.",
17
+ "emoji": "๐Ÿšช",
18
+ "type": "escape"
19
+ },
20
+ {
21
+ "id": "lost_temple",
22
+ "name": "The Treasure of the Lost Temple",
23
+ "description": "On a quest to retrieve an ancient artifact, your cat rider must navigate through a labyrinth filled with traps and guardian spirits.",
24
+ "emoji": "๐Ÿ›๏ธ",
25
+ "type": "exploration"
26
+ },
27
+ {
28
+ "id": "royal_tournament",
29
+ "name": "The Royal Tournament",
30
+ "description": "Compete in a grand tournament where the finest cat riders showcase their skills and bravery to earn the title of the Royal Rider.",
31
+ "emoji": "๐Ÿ‘‘",
32
+ "type": "competition"
33
+ }
34
+ ]
35
+
36
+ ACTIONS = [
37
+ {
38
+ "id": "stealth",
39
+ "name": "Use Stealth",
40
+ "description": "Sneak past obstacles or enemies without being detected.",
41
+ "emoji": "๐Ÿคซ",
42
+ "type": "skill"
43
+ },
44
+ {
45
+ "id": "agility",
46
+ "name": "Showcase Agility",
47
+ "description": "Perform impressive acrobatic maneuvers to overcome challenges.",
48
+ "emoji": "๐Ÿƒ",
49
+ "type": "physical"
50
+ },
51
+ {
52
+ "id": "charm",
53
+ "name": "Charm Others",
54
+ "description": "Use your cat's natural charisma to win over allies or distract foes.",
55
+ "emoji": "๐Ÿ˜ป",
56
+ "type": "social"
57
+ },
58
+ {
59
+ "id": "resourcefulness",
60
+ "name": "Be Resourceful",
61
+ "description": "Utilize the environment or items in creative ways to solve problems.",
62
+ "emoji": "๐Ÿง ",
63
+ "type": "mental"
64
+ }
65
+ ]
66
+
67
+ # ๐ŸŽฒ Game Mechanics
68
+ def generate_situation():
69
+ return random.choice(SITUATIONS)
70
+
71
+ def generate_actions():
72
+ return random.sample(ACTIONS, 3)
73
+
74
+ def evaluate_action(action, gear_strength, rider_skill, history):
75
+ base_success_chance = (gear_strength + rider_skill) / 2
76
+ if action['id'] in history:
77
+ success_chance = base_success_chance + (history[action['id']] * 2)
78
+ else:
79
+ success_chance = base_success_chance
80
+ outcome = random.randint(1, 100) <= success_chance
81
+ return outcome, success_chance
82
+
83
+ def generate_encounter_conclusion(situation, action, outcome):
84
+ if outcome:
85
+ conclusions = [
86
+ f"Your {action['name']} was successful! You've overcome the challenges of {situation['name']}.",
87
+ f"Through clever use of {action['name']}, you've triumphed in the {situation['name']}!",
88
+ f"Your mastery of {action['name']} has led to a victorious outcome in the {situation['name']}!"
89
+ ]
90
+ else:
91
+ conclusions = [
92
+ f"Despite your efforts with {action['name']}, you've failed to overcome the {situation['name']}.",
93
+ f"Your attempt at {action['name']} wasn't enough to succeed in the {situation['name']}.",
94
+ f"The challenges of {situation['name']} proved too great for your {action['name']} this time."
95
+ ]
96
+ return random.choice(conclusions)
97
+
98
+ def update_character_stats(game_state, outcome):
99
+ if outcome:
100
+ game_state['gear_strength'] = min(10, game_state['gear_strength'] + random.uniform(0.1, 0.5))
101
+ game_state['rider_skill'] = min(10, game_state['rider_skill'] + random.uniform(0.1, 0.5))
102
+ return game_state
103
+
104
+ # ๐ŸŒณ Journey Visualization with Heterogeneous Graph Structure
105
+ def create_heterogeneous_graph(history_df):
106
+ nodes = []
107
+ edges = []
108
+
109
+ # Define node shapes based on situation and action types
110
+ situation_shapes = {
111
+ "escape": "diamond",
112
+ "exploration": "triangle",
113
+ "competition": "star"
114
+ }
115
+ action_shapes = {
116
+ "skill": "square",
117
+ "physical": "circle",
118
+ "social": "hexagon",
119
+ "mental": "octagon"
120
+ }
121
+
122
+ for index, row in history_df.iterrows():
123
+ situation_id = f"situation-{index}"
124
+ action_id = f"action-{index}"
125
+ conclusion_id = f"conclusion-{index}"
126
+
127
+ # Create situation node
128
+ situation_content = f"{row['situation_emoji']} {row['situation_name']}\n๐Ÿ•’ {row['timestamp']}"
129
+ situation_node = StreamlitFlowNode(situation_id, (0, 0), {'content': situation_content}, 'output', 'bottom', 'top', shape=situation_shapes[row['situation_type']])
130
+ nodes.append(situation_node)
131
+
132
+ # Create action node
133
+ action_content = f"{row['action_emoji']} {row['action_name']}\nOutcome: {'โœ… Success' if row['outcome'] else 'โŒ Failure'}"
134
+ action_node = StreamlitFlowNode(action_id, (0, 0), {'content': action_content}, 'output', 'bottom', 'top', shape=action_shapes[row['action_type']])
135
+ nodes.append(action_node)
136
+
137
+ # Create conclusion node
138
+ conclusion_content = f"๐Ÿ“œ {row['conclusion']}\n๐Ÿ’ช Gear: {row['gear_strength']:.2f} | ๐Ÿ‹๏ธ Skill: {row['rider_skill']:.2f}"
139
+ conclusion_node = StreamlitFlowNode(conclusion_id, (0, 0), {'content': conclusion_content}, 'output', 'bottom', 'top', shape='parallelogram')
140
+ nodes.append(conclusion_node)
141
+
142
+ # Create edges
143
+ edges.append(StreamlitFlowEdge(f"{situation_id}-{action_id}", situation_id, action_id, animated=True, dashed=False))
144
+ edges.append(StreamlitFlowEdge(f"{action_id}-{conclusion_id}", action_id, conclusion_id, animated=True, dashed=False))
145
+
146
+ # Create edge to previous conclusion if not the first node
147
+ if index > 0:
148
+ prev_conclusion_id = f"conclusion-{index-1}"
149
+ edges.append(StreamlitFlowEdge(f"{prev_conclusion_id}-{situation_id}", prev_conclusion_id, situation_id, animated=True, dashed=True))
150
+
151
+ return nodes, edges
152
+
153
+ # ๐Ÿ“ Markdown Preview
154
+ def create_markdown_preview(history_df):
155
+ markdown = "## ๐ŸŒณ Journey Preview\n\n"
156
+ for index, row in history_df.iterrows():
157
+ indent = " " * (index * 3)
158
+ markdown += f"{indent}๐ŸŒŸ **{row['situation_name']}** ({row['situation_type']})\n"
159
+ markdown += f"{indent} โ†ช {row['action_emoji']} {row['action_name']} ({row['action_type']}): "
160
+ markdown += "โœ… Success\n" if row['outcome'] else "โŒ Failure\n"
161
+ markdown += f"{indent} ๐Ÿ“œ {row['conclusion']}\n"
162
+ markdown += f"{indent} ๐Ÿ’ช Gear: {row['gear_strength']:.2f} | ๐Ÿ‹๏ธ Skill: {row['rider_skill']:.2f}\n\n"
163
+ return markdown
164
+
165
+ # ๐Ÿ”„ Game State Management
166
+ def update_game_state(game_state, situation, action, outcome, timestamp):
167
+ conclusion = generate_encounter_conclusion(situation, action, outcome)
168
+ game_state = update_character_stats(game_state, outcome)
169
+
170
+ new_record = pd.DataFrame({
171
+ 'user_id': [game_state['user_id']],
172
+ 'timestamp': [timestamp],
173
+ 'situation_id': [situation['id']],
174
+ 'situation_name': [situation['name']],
175
+ 'situation_emoji': [situation['emoji']],
176
+ 'situation_type': [situation['type']],
177
+ 'action_id': [action['id']],
178
+ 'action_name': [action['name']],
179
+ 'action_emoji': [action['emoji']],
180
+ 'action_type': [action['type']],
181
+ 'outcome': [outcome],
182
+ 'conclusion': [conclusion],
183
+ 'gear_strength': [game_state['gear_strength']],
184
+ 'rider_skill': [game_state['rider_skill']],
185
+ 'score': [game_state['score']]
186
+ })
187
+ game_state['history_df'] = pd.concat([game_state['history_df'], new_record], ignore_index=True)
188
+
189
+ if action['id'] in game_state['history']:
190
+ game_state['history'][action['id']] += 1 if outcome else -1
191
+ else:
192
+ game_state['history'][action['id']] = 1 if outcome else -1
193
+
194
+ return game_state
195
+
196
+ # ๐ŸŽฎ Main Game Application
197
+ def main():
198
+ st.title("๐Ÿฑ Cat Rider ๐Ÿ‡")
199
+ st.markdown("""
200
+ ## Welcome to Cat Rider!
201
+ 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.
202
+ """)
203
+
204
+ # ๐Ÿ“œ Game Rules
205
+ st.markdown("""
206
+ ### ๐Ÿ“œ Game Rules
207
+ | ๐Ÿ›ค๏ธ Step | ๐Ÿ“ Description |
208
+ |---------|----------------|
209
+ | 1๏ธโƒฃ | Choose your Cat Rider |
210
+ | 2๏ธโƒฃ | Select the Riding Gear |
211
+ | 3๏ธโƒฃ | Set off on an Adventure |
212
+ | 4๏ธโƒฃ | Encounter Challenges and Make Decisions |
213
+ | 5๏ธโƒฃ | Complete the Quest and Grow Stronger |
214
+ """)
215
+
216
+ # ๐Ÿ Initialize game state
217
+ if 'game_state' not in st.session_state:
218
+ st.session_state.game_state = {
219
+ 'user_id': str(uuid.uuid4()),
220
+ 'score': 0,
221
+ 'history': {},
222
+ 'gear_strength': 5,
223
+ 'rider_skill': 5,
224
+ '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'])
225
+ }
226
+
227
+ # ๐Ÿ“Š Game Stats
228
+ st.sidebar.markdown("## ๐Ÿ“Š Game Stats")
229
+ st.sidebar.markdown(f"**Score:** {st.session_state.game_state['score']}")
230
+ st.sidebar.markdown(f"**Gear Strength:** {st.session_state.game_state['gear_strength']:.2f}")
231
+ st.sidebar.markdown(f"**Rider Skill:** {st.session_state.game_state['rider_skill']:.2f}")
232
+
233
+ # ๐ŸŽญ Game Loop
234
+ situation = generate_situation()
235
+ actions = generate_actions()
236
+
237
+ st.markdown(f"## {situation['emoji']} Current Situation: {situation['name']} ({situation['type']})")
238
+ st.markdown(situation['description'])
239
+ st.markdown("### ๐ŸŽญ Choose your action:")
240
+
241
+ cols = st.columns(3)
242
+ for i, action in enumerate(actions):
243
+ if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})"):
244
+ 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'])
245
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
246
+
247
+ st.markdown(f"You decided to: **{action['name']}** ({action['type']})")
248
+ st.markdown(action['description'])
249
+ st.markdown(f"**Outcome:** {'โœ… Success!' if outcome else 'โŒ Failure.'}")
250
+ st.markdown(f"**Success Chance:** {success_chance:.2f}%")
251
+
252
+ if outcome:
253
+ st.session_state.game_state['score'] += 1
254
+
255
+ # ๐Ÿ”„ Update game state
256
+ st.session_state.game_state = update_game_state(
257
+ st.session_state.game_state,
258
+ situation,
259
+ action,
260
+ outcome,
261
+ timestamp
262
+ )
263
+
264
+ # Display conclusion
265
+ conclusion = st.session_state.game_state['history_df'].iloc[-1]['conclusion']
266
+ st.markdown(f"**Encounter Conclusion:** {conclusion}")
267
+
268
+ # Display updated stats
269
+ st.markdown(f"**Updated Stats:**")
270
+ st.markdown(f"๐Ÿ’ช Gear Strength: {st.session_state.game_state['gear_strength']:.2f}")
271
+ st.markdown(f"๐Ÿ‹๏ธ Rider Skill: {st.session_state.game_state['rider_skill']:.2f}")
272
+
273
+ # ๐Ÿ“ Display Markdown Preview
274
+ if not st.session_state.game_state['history_df'].empty:
275
+ st.markdown(create_markdown_preview(st.session_state.game_state['history_df']))
276
+
277
+ # ๐ŸŒณ Display Heterogeneous Journey Graph
278
+ if not st.session_state.game_state['history_df'].empty:
279
+ st.markdown("## ๐ŸŒณ Your Journey (Heterogeneous Graph)")
280
+ nodes, edges = create_heterogeneous_graph(st.session_state.game_state['history_df'])
281
+ try:
282
+ streamlit_flow('cat_rider_flow',
283
+ nodes,
284
+ edges,
285
+ layout=TreeLayout(direction='down'),
286
+ fit_view=True,
287
+ height=600)
288
+ except Exception as e:
289
+ st.error(f"An error occurred while rendering the journey graph: {str(e)}")
290
+ st.markdown("Please try refreshing the page if the graph doesn't appear.")
291
+
292
+ # ๐Ÿ“Š Character Stats Visualization
293
+ data = {"Stat": ["Gear Strength ๐Ÿ›ก๏ธ", "Rider Skill ๐Ÿ‡"],
294
+ "Value": [st.session_state.game_state['gear_strength'], st.session_state.game_state['rider_skill']]}
295
+ df = pd.DataFrame(data)
296
+ fig = px.bar(df, x='Stat', y='Value', title="Cat Rider Stats ๐Ÿ“Š")
297
+ st.plotly_chart(fig)
298
+
299
+ if __name__ == "__main__":
300
+ main()