awacke1 commited on
Commit
119c81d
Β·
verified Β·
1 Parent(s): be3e5a6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -53
app.py CHANGED
@@ -121,47 +121,80 @@ def update_character_stats(game_state, outcome):
121
  def create_heterogeneous_graph(history_df):
122
  nodes = []
123
  edges = []
 
124
  for index, row in history_df.iterrows():
125
- scenario_id = f"scenario-{row['situation_id']}-{index}"
126
- action_id = f"action-{row['action_id']}-{index}"
127
- conclusion_id = f"conclusion-{index}"
128
-
129
- # Scenario node
130
- scenario_node = StreamlitFlowNode(scenario_id, (0, 0), {'content': f"{row['situation_emoji']} {row['situation_name']}"}, 'output', 'bottom', 'top', shape='ellipse')
131
- nodes.append(scenario_node)
 
 
 
 
 
 
 
 
 
 
132
 
133
  # Action node
134
- action_node = StreamlitFlowNode(action_id, (0, 0), {'content': f"{row['action_emoji']} {row['action_name']}"}, 'output', 'bottom', 'top', shape='ellipse')
 
 
 
 
 
 
 
 
135
  nodes.append(action_node)
136
 
137
- # Conclusion node with stars
 
138
  stars = '⭐' * int(row['score'])
139
- conclusion_node = StreamlitFlowNode(conclusion_id, (0, 0), {'content': f"{row['conclusion']}\n{stars}"}, 'output', 'bottom', 'top', shape='ellipse')
140
- nodes.append(conclusion_node)
 
 
 
 
 
 
 
 
141
 
142
  # Edges
143
- edges.append(StreamlitFlowEdge(f"{scenario_id}-{action_id}", scenario_id, action_id, animated=True))
144
- edges.append(StreamlitFlowEdge(f"{action_id}-{conclusion_id}", action_id, conclusion_id, animated=True))
145
-
146
- # Link to previous scenario
147
- if index > 0:
148
- prev_conclusion_id = f"conclusion-{index-1}"
149
- edges.append(StreamlitFlowEdge(f"{prev_conclusion_id}-{scenario_id}", prev_conclusion_id, scenario_id, animated=True, dashed=True))
 
 
 
 
 
150
 
151
  return nodes, edges
152
 
153
- # πŸ“ Markdown Preview with Single Scenario Entry and Attempts
154
  def create_markdown_preview(history_df):
155
  markdown = "## 🌳 Journey Preview\n\n"
156
- grouped_scenarios = history_df.groupby('situation_name')
157
 
158
- for situation_name, group in grouped_scenarios:
159
- markdown += f"🌟 **{situation_name}**\n"
160
  for _, row in group.iterrows():
 
161
  stars = '⭐' * int(row['score'])
162
- markdown += f" β†ͺ {row['action_emoji']} {row['action_name']}: "
163
- markdown += "βœ… Success\n" if row['outcome'] else "❌ Failure\n"
164
- markdown += f" πŸ“œ {row['conclusion']} {stars} πŸ’ͺ Gear: {row['gear_strength']:.2f} | πŸ‹οΈ Skill: {row['rider_skill']:.2f}\n"
165
  markdown += "\n"
166
  return markdown
167
 
@@ -260,7 +293,6 @@ def main():
260
  st.markdown("## Choose Your Cat Rider:")
261
  cols = st.columns(len(CAT_RIDERS))
262
  for i, rider in enumerate(CAT_RIDERS):
263
- # Adding unique key for each button
264
  if cols[i].button(f"{rider['emoji']} {rider['name']} ({rider['type']})", key=f"rider_{i}"):
265
  st.session_state.game_state['cat_rider'] = rider
266
  st.session_state.game_state['rider_skill'] = rider['skill']
@@ -270,7 +302,6 @@ def main():
270
  st.markdown("## Select Your Riding Gear:")
271
  cols = st.columns(len(RIDING_GEAR))
272
  for i, gear in enumerate(RIDING_GEAR):
273
- # Adding unique key for each button
274
  if cols[i].button(f"{gear['name']} ({gear['type']})", key=f"gear_{i}"):
275
  st.session_state.game_state['riding_gear'] = gear
276
  st.session_state.game_state['gear_strength'] = gear['strength']
@@ -286,7 +317,6 @@ def main():
286
 
287
  cols = st.columns(3)
288
  for i, action in enumerate(actions):
289
- # Adding unique key for each button
290
  if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})", key=f"action_{i}"):
291
  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'])
292
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@@ -320,31 +350,31 @@ def main():
320
  # πŸ… Display Scoreboard
321
  display_scoreboard(st.session_state.game_state)
322
 
323
- # πŸ“ Display Markdown Preview
324
- if not st.session_state.game_state['history_df'].empty:
325
- st.markdown(create_markdown_preview(st.session_state.game_state['history_df']))
326
-
327
- # 🌳 Display Heterogeneous Journey Graph
328
- if not st.session_state.game_state['history_df'].empty:
329
- st.markdown("## 🌳 Your Journey (Heterogeneous Graph)")
330
- nodes, edges = create_heterogeneous_graph(st.session_state.game_state['history_df'])
331
- try:
332
- streamlit_flow('cat_rider_flow',
333
- nodes,
334
- edges,
335
- layout=TreeLayout(direction='down'),
336
- fit_view=True,
337
- height=600)
338
- except Exception as e:
339
- st.error(f"An error occurred while rendering the journey graph: {str(e)}")
340
- st.markdown("Please try refreshing the page if the graph doesn't appear.")
341
-
342
- # πŸ“Š Character Stats Visualization
343
- data = {"Stat": ["Gear Strength πŸ›‘οΈ", "Rider Skill πŸ‡"],
344
- "Value": [st.session_state.game_state['gear_strength'], st.session_state.game_state['rider_skill']]}
345
- df = pd.DataFrame(data)
346
- fig = px.bar(df, x='Stat', y='Value', title="Cat Rider Stats πŸ“Š")
347
- st.plotly_chart(fig)
348
 
349
  if __name__ == "__main__":
350
  main()
 
121
  def create_heterogeneous_graph(history_df):
122
  nodes = []
123
  edges = []
124
+ node_ids = {}
125
  for index, row in history_df.iterrows():
126
+ situation_node_id = f"situation_{row['situation_id']}_{index}"
127
+ action_node_id = f"action_{row['action_id']}_{index}"
128
+ outcome_node_id = f"outcome_{index}"
129
+
130
+ # Situation node
131
+ if situation_node_id not in node_ids:
132
+ situation_node = StreamlitFlowNode(
133
+ id=situation_node_id,
134
+ position=(0, 0),
135
+ data={'content': f"{row['situation_emoji']} {row['situation_name']}"},
136
+ type='default',
137
+ sourcePosition='bottom',
138
+ targetPosition='top',
139
+ shape='ellipse'
140
+ )
141
+ nodes.append(situation_node)
142
+ node_ids[situation_node_id] = situation_node_id
143
 
144
  # Action node
145
+ action_node = StreamlitFlowNode(
146
+ id=action_node_id,
147
+ position=(0, 0),
148
+ data={'content': f"{row['action_emoji']} {row['action_name']}"},
149
+ type='default',
150
+ sourcePosition='bottom',
151
+ targetPosition='top',
152
+ shape='ellipse'
153
+ )
154
  nodes.append(action_node)
155
 
156
+ # Outcome node with success celebration
157
+ outcome_content = 'βœ… Success' if row['outcome'] else '❌ Failure'
158
  stars = '⭐' * int(row['score'])
159
+ outcome_node = StreamlitFlowNode(
160
+ id=outcome_node_id,
161
+ position=(0, 0),
162
+ data={'content': f"{row['conclusion']}\n{outcome_content}\n{stars}"},
163
+ type='default',
164
+ sourcePosition='bottom',
165
+ targetPosition='top',
166
+ shape='ellipse'
167
+ )
168
+ nodes.append(outcome_node)
169
 
170
  # Edges
171
+ edges.append(StreamlitFlowEdge(
172
+ id=f"edge_{situation_node_id}_{action_node_id}_{index}",
173
+ source=situation_node_id,
174
+ target=action_node_id,
175
+ animated=True
176
+ ))
177
+ edges.append(StreamlitFlowEdge(
178
+ id=f"edge_{action_node_id}_{outcome_node_id}_{index}",
179
+ source=action_node_id,
180
+ target=outcome_node_id,
181
+ animated=True
182
+ ))
183
 
184
  return nodes, edges
185
 
186
+ # πŸ“ Markdown Preview with Subpoints for Each Action
187
  def create_markdown_preview(history_df):
188
  markdown = "## 🌳 Journey Preview\n\n"
189
+ grouped = history_df.groupby('situation_name', sort=False)
190
 
191
+ for situation_name, group in grouped:
192
+ markdown += f"### {group.iloc[0]['situation_emoji']} **{situation_name}**\n"
193
  for _, row in group.iterrows():
194
+ outcome_str = 'βœ… Success' if row['outcome'] else '❌ Failure'
195
  stars = '⭐' * int(row['score'])
196
+ markdown += f"- {row['action_emoji']} **{row['action_name']}**: {outcome_str} {stars}\n"
197
+ markdown += f" - {row['conclusion']}\n"
 
198
  markdown += "\n"
199
  return markdown
200
 
 
293
  st.markdown("## Choose Your Cat Rider:")
294
  cols = st.columns(len(CAT_RIDERS))
295
  for i, rider in enumerate(CAT_RIDERS):
 
296
  if cols[i].button(f"{rider['emoji']} {rider['name']} ({rider['type']})", key=f"rider_{i}"):
297
  st.session_state.game_state['cat_rider'] = rider
298
  st.session_state.game_state['rider_skill'] = rider['skill']
 
302
  st.markdown("## Select Your Riding Gear:")
303
  cols = st.columns(len(RIDING_GEAR))
304
  for i, gear in enumerate(RIDING_GEAR):
 
305
  if cols[i].button(f"{gear['name']} ({gear['type']})", key=f"gear_{i}"):
306
  st.session_state.game_state['riding_gear'] = gear
307
  st.session_state.game_state['gear_strength'] = gear['strength']
 
317
 
318
  cols = st.columns(3)
319
  for i, action in enumerate(actions):
 
320
  if cols[i].button(f"{action['emoji']} {action['name']} ({action['type']})", key=f"action_{i}"):
321
  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'])
322
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
350
  # πŸ… Display Scoreboard
351
  display_scoreboard(st.session_state.game_state)
352
 
353
+ # Integration point for both functions
354
+ if not st.session_state.game_state['history_df'].empty:
355
+ # πŸ“ Display Markdown Preview
356
+ st.markdown(create_markdown_preview(st.session_state.game_state['history_df']))
357
+
358
+ # 🌳 Display Heterogeneous Journey Graph
359
+ st.markdown("## 🌳 Your Journey (Heterogeneous Graph)")
360
+ nodes, edges = create_heterogeneous_graph(st.session_state.game_state['history_df'])
361
+ try:
362
+ streamlit_flow('cat_rider_flow',
363
+ nodes,
364
+ edges,
365
+ layout=TreeLayout(direction='down'),
366
+ fit_view=True,
367
+ height=600)
368
+ except Exception as e:
369
+ st.error(f"An error occurred while rendering the journey graph: {str(e)}")
370
+ st.markdown("Please try refreshing the page if the graph doesn't appear.")
371
+
372
+ # πŸ“Š Character Stats Visualization
373
+ data = {"Stat": ["Gear Strength πŸ›‘οΈ", "Rider Skill πŸ‡"],
374
+ "Value": [st.session_state.game_state['gear_strength'], st.session_state.game_state['rider_skill']]}
375
+ df = pd.DataFrame(data)
376
+ fig = px.bar(df, x='Stat', y='Value', title="Cat Rider Stats πŸ“Š")
377
+ st.plotly_chart(fig)
378
 
379
  if __name__ == "__main__":
380
  main()