File size: 12,839 Bytes
f44d20e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
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.",
        "emoji": "๐Ÿšช",
        "type": "escape"
    },
    {
        "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.",
        "emoji": "๐Ÿ›๏ธ",
        "type": "exploration"
    },
    {
        "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.",
        "emoji": "๐Ÿ‘‘",
        "type": "competition"
    }
]

ACTIONS = [
    {
        "id": "stealth",
        "name": "Use Stealth",
        "description": "Sneak past obstacles or enemies without being detected.",
        "emoji": "๐Ÿคซ",
        "type": "skill"
    },
    {
        "id": "agility",
        "name": "Showcase Agility",
        "description": "Perform impressive acrobatic maneuvers to overcome challenges.",
        "emoji": "๐Ÿƒ",
        "type": "physical"
    },
    {
        "id": "charm",
        "name": "Charm Others",
        "description": "Use your cat's natural charisma to win over allies or distract foes.",
        "emoji": "๐Ÿ˜ป",
        "type": "social"
    },
    {
        "id": "resourcefulness",
        "name": "Be Resourceful",
        "description": "Utilize the environment or items in creative ways to solve problems.",
        "emoji": "๐Ÿง ",
        "type": "mental"
    }
]

# ๐ŸŽฒ Game Mechanics
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):
    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']} has led to a victorious outcome in the {situation['name']}!"
        ]
    else:
        conclusions = [
            f"Despite your efforts with {action['name']}, you've failed to overcome the {situation['name']}.",
            f"Your attempt at {action['name']} wasn't enough to succeed in the {situation['name']}.",
            f"The challenges of {situation['name']} proved too great for your {action['name']} this time."
        ]
    return random.choice(conclusions)

def update_character_stats(game_state, outcome):
    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
def create_heterogeneous_graph(history_df):
    nodes = []
    edges = []
    
    # Define node shapes based on situation and action types
    situation_shapes = {
        "escape": "diamond",
        "exploration": "triangle",
        "competition": "star"
    }
    action_shapes = {
        "skill": "square",
        "physical": "circle",
        "social": "hexagon",
        "mental": "octagon"
    }
    
    for index, row in history_df.iterrows():
        situation_id = f"situation-{index}"
        action_id = f"action-{index}"
        conclusion_id = f"conclusion-{index}"
        
        # Create situation node
        situation_content = f"{row['situation_emoji']} {row['situation_name']}\n๐Ÿ•’ {row['timestamp']}"
        situation_node = StreamlitFlowNode(situation_id, (0, 0), {'content': situation_content}, 'output', 'bottom', 'top', shape=situation_shapes[row['situation_type']])
        nodes.append(situation_node)
        
        # Create action node
        action_content = f"{row['action_emoji']} {row['action_name']}\nOutcome: {'โœ… Success' if row['outcome'] else 'โŒ Failure'}"
        action_node = StreamlitFlowNode(action_id, (0, 0), {'content': action_content}, 'output', 'bottom', 'top', shape=action_shapes[row['action_type']])
        nodes.append(action_node)
        
        # Create conclusion node
        conclusion_content = f"๐Ÿ“œ {row['conclusion']}\n๐Ÿ’ช Gear: {row['gear_strength']:.2f} | ๐Ÿ‹๏ธ Skill: {row['rider_skill']:.2f}"
        conclusion_node = StreamlitFlowNode(conclusion_id, (0, 0), {'content': conclusion_content}, 'output', 'bottom', 'top', shape='parallelogram')
        nodes.append(conclusion_node)
        
        # Create edges
        edges.append(StreamlitFlowEdge(f"{situation_id}-{action_id}", situation_id, action_id, animated=True, dashed=False))
        edges.append(StreamlitFlowEdge(f"{action_id}-{conclusion_id}", action_id, conclusion_id, animated=True, dashed=False))
        
        # Create edge to previous conclusion if not the first node
        if index > 0:
            prev_conclusion_id = f"conclusion-{index-1}"
            edges.append(StreamlitFlowEdge(f"{prev_conclusion_id}-{situation_id}", prev_conclusion_id, situation_id, animated=True, dashed=True))
    
    return nodes, edges

# ๐Ÿ“ Markdown Preview
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
def update_game_state(game_state, situation, action, outcome, timestamp):
    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
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
    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
    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
    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
    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()