awacke1 commited on
Commit
23a63a0
ยท
verified ยท
1 Parent(s): 42a4f26

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +269 -0
app.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ๐ŸŒณ Journey Visualization with Heterogeneous Graph Structure
84
+ def create_heterogeneous_graph(history_df):
85
+ nodes = []
86
+ edges = []
87
+
88
+ # Define node shapes based on situation and action types
89
+ situation_shapes = {
90
+ "escape": "diamond",
91
+ "exploration": "triangle",
92
+ "competition": "star"
93
+ }
94
+ action_shapes = {
95
+ "skill": "square",
96
+ "physical": "circle",
97
+ "social": "hexagon",
98
+ "mental": "octagon"
99
+ }
100
+
101
+ for index, row in history_df.iterrows():
102
+ situation_id = f"situation-{index}"
103
+ action_id = f"action-{index}"
104
+
105
+ # Create situation node
106
+ situation_content = f"{row['situation_emoji']} {row['situation_name']}\n๐Ÿ•’ {row['timestamp']}"
107
+ situation_node = StreamlitFlowNode(situation_id, (0, 0), {'content': situation_content}, 'output', 'bottom', 'top', shape=situation_shapes[row['situation_type']])
108
+ nodes.append(situation_node)
109
+
110
+ # Create action node
111
+ action_content = f"{row['action_emoji']} {row['action_name']}\nOutcome: {'โœ… Success' if row['outcome'] else 'โŒ Failure'}"
112
+ action_node = StreamlitFlowNode(action_id, (0, 0), {'content': action_content}, 'output', 'bottom', 'top', shape=action_shapes[row['action_type']])
113
+ nodes.append(action_node)
114
+
115
+ # Create edge between situation and action
116
+ edge = StreamlitFlowEdge(f"{situation_id}-{action_id}", situation_id, action_id, animated=True, dashed=False)
117
+ edges.append(edge)
118
+
119
+ # Create edge to previous action if not the first node
120
+ if index > 0:
121
+ prev_action_id = f"action-{index-1}"
122
+ prev_edge = StreamlitFlowEdge(f"{prev_action_id}-{situation_id}", prev_action_id, situation_id, animated=True, dashed=True)
123
+ edges.append(prev_edge)
124
+
125
+ return nodes, edges
126
+
127
+ # ๐Ÿ“ Markdown Preview
128
+ def create_markdown_preview(history_df):
129
+ markdown = "## ๐ŸŒณ Journey Preview\n\n"
130
+ for index, row in history_df.iterrows():
131
+ indent = " " * index
132
+ markdown += f"{indent}- {row['situation_emoji']} **{row['situation_name']}** ({row['situation_type']})\n"
133
+ markdown += f"{indent} - {row['action_emoji']} {row['action_name']} ({row['action_type']}): "
134
+ markdown += "โœ… Success\n" if row['outcome'] else "โŒ Failure\n"
135
+ return markdown
136
+
137
+ # ๐Ÿ”„ Game State Management
138
+ def update_game_state(game_state, situation, action, outcome, timestamp):
139
+ new_record = pd.DataFrame({
140
+ 'user_id': [game_state['user_id']],
141
+ 'timestamp': [timestamp],
142
+ 'situation_id': [situation['id']],
143
+ 'situation_name': [situation['name']],
144
+ 'situation_emoji': [situation['emoji']],
145
+ 'situation_type': [situation['type']],
146
+ 'action_id': [action['id']],
147
+ 'action_name': [action['name']],
148
+ 'action_emoji': [action['emoji']],
149
+ 'action_type': [action['type']],
150
+ 'outcome': [outcome],
151
+ 'score': [game_state['score']]
152
+ })
153
+ game_state['history_df'] = pd.concat([game_state['history_df'], new_record], ignore_index=True)
154
+
155
+ if action['id'] in game_state['history']:
156
+ game_state['history'][action['id']] += 1 if outcome else -1
157
+ else:
158
+ game_state['history'][action['id']] = 1 if outcome else -1
159
+
160
+ return game_state
161
+
162
+ # ๐ŸŽฎ Main Game Application
163
+ def main():
164
+ st.title("๐Ÿฑ Cat Rider ๐Ÿ‡")
165
+ st.markdown("""
166
+ ## Welcome to Cat Rider!
167
+ 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.
168
+ """)
169
+
170
+ # ๐Ÿ“œ Game Rules
171
+ st.markdown("""
172
+ ### ๐Ÿ“œ Game Rules
173
+ | ๐Ÿ›ค๏ธ Step | ๐Ÿ“ Description |
174
+ |---------|----------------|
175
+ | 1๏ธโƒฃ | Choose your Cat Rider |
176
+ | 2๏ธโƒฃ | Select the Riding Gear |
177
+ | 3๏ธโƒฃ | Set off on an Adventure |
178
+ | 4๏ธโƒฃ | Encounter Challenges and Make Decisions |
179
+ | 5๏ธโƒฃ | Complete the Quest |
180
+ """)
181
+
182
+ # ๐Ÿ Initialize game state
183
+ if 'game_state' not in st.session_state:
184
+ st.session_state.game_state = {
185
+ 'user_id': str(uuid.uuid4()),
186
+ 'score': 0,
187
+ 'history': {},
188
+ 'gear_strength': 5,
189
+ 'rider_skill': 5,
190
+ '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', 'score'])
191
+ }
192
+
193
+ # ๐Ÿ“Š Game Stats
194
+ st.sidebar.markdown("## ๐Ÿ“Š Game Stats")
195
+ st.sidebar.markdown(f"**Score:** {st.session_state.game_state['score']}")
196
+
197
+ # ๐Ÿฆธ Character Stats
198
+ gear_strength = st.sidebar.slider('Gear Strength ๐Ÿ›ก๏ธ', 1, 10, st.session_state.game_state['gear_strength'])
199
+ rider_skill = st.sidebar.slider('Rider Skill ๐Ÿ‡', 1, 10, st.session_state.game_state['rider_skill'])
200
+
201
+ # ๐ŸŽญ Game Loop
202
+ situation = generate_situation()
203
+ actions = generate_actions()
204
+
205
+ st.markdown(f"## {situation['emoji']} Current Situation: {situation['name']} ({situation['type']})")
206
+ st.markdown(situation['description'])
207
+ st.markdown("### ๐ŸŽญ Choose your action:")
208
+
209
+ cols = st.columns(3)
210
+ for i, action in enumerate(actions):
211
+ if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})"):
212
+ outcome, success_chance = evaluate_action(action, gear_strength, rider_skill, st.session_state.game_state['history'])
213
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
214
+
215
+ st.markdown(f"You decided to: **{action['name']}** ({action['type']})")
216
+ st.markdown(action['description'])
217
+ st.markdown(f"**Outcome:** {'โœ… Success!' if outcome else 'โŒ Failure.'}")
218
+ st.markdown(f"**Success Chance:** {success_chance:.2f}%")
219
+
220
+ if outcome:
221
+ st.session_state.game_state['score'] += 1
222
+
223
+ # ๐Ÿ”„ Update game state
224
+ st.session_state.game_state = update_game_state(
225
+ st.session_state.game_state,
226
+ situation,
227
+ action,
228
+ outcome,
229
+ timestamp
230
+ )
231
+
232
+ # ๐Ÿ“ Display Markdown Preview
233
+ if not st.session_state.game_state['history_df'].empty:
234
+ st.markdown(create_markdown_preview(st.session_state.game_state['history_df']))
235
+
236
+ # ๐ŸŒณ Display Heterogeneous Journey Graph
237
+ if not st.session_state.game_state['history_df'].empty:
238
+ st.markdown("## ๐ŸŒณ Your Journey (Heterogeneous Graph)")
239
+ nodes, edges = create_heterogeneous_graph(st.session_state.game_state['history_df'])
240
+ try:
241
+ streamlit_flow('cat_rider_flow',
242
+ nodes,
243
+ edges,
244
+ layout=TreeLayout(direction='down'),
245
+ fit_view=True,
246
+ height=600)
247
+ except Exception as e:
248
+ st.error(f"An error occurred while rendering the journey graph: {str(e)}")
249
+ st.markdown("Please try refreshing the page if the graph doesn't appear.")
250
+
251
+ # ๐Ÿ“Š Character Stats Visualization
252
+ data = {"Stat": ["Gear Strength ๐Ÿ›ก๏ธ", "Rider Skill ๐Ÿ‡"],
253
+ "Value": [gear_strength, rider_skill]}
254
+ df = pd.DataFrame(data)
255
+ fig = px.bar(df, x='Stat', y='Value', title="Cat Rider Stats ๐Ÿ“Š")
256
+ st.plotly_chart(fig)
257
+
258
+ # Example of Data Table
259
+ st.markdown("### ๐Ÿ› ๏ธ Available Gear")
260
+ gear_data = {
261
+ 'Gear': ['Helmet', 'Armor', 'Boots', 'Gloves'],
262
+ 'Protection Level': [8, 7, 5, 4],
263
+ 'Type': ['Head', 'Body', 'Feet', 'Hands']
264
+ }
265
+ gear_df = pd.DataFrame(gear_data)
266
+ st.dataframe(gear_df)
267
+
268
+ if __name__ == "__main__":
269
+ main()