File size: 9,144 Bytes
b80c026
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import pandas as pd
import plotly.express as px
import random
import json
import csv
import base64
import uuid
from io import StringIO
from datetime import datetime
from streamlit_flow import streamlit_flow
from streamlit_flow.elements import StreamlitFlowNode, StreamlitFlowEdge
from streamlit_flow.layouts import TreeLayout

# Rich data structures for game content
SITUATIONS = [
    {
        "id": "village_peril",
        "name": "The Village in Peril",
        "description": "A once-peaceful village is shrouded in dark miasma. Villagers cower in fear as shadowy figures lurk in the mist.",
        "emoji": "🏘️"
    },
    {
        "id": "cursed_artifact",
        "name": "The Cursed Artifact",
        "description": "Deep in an ancient tomb, a glowing artifact pulses with malevolent energy, its whispers echoing in your mind.",
        "emoji": "🏺"
    },
    {
        "id": "sacred_pact",
        "name": "The Sacred Pact",
        "description": "At a moonlit shrine, spirits of the land gather, awaiting a mediator to forge a new covenant between realms.",
        "emoji": "πŸŒ™"
    },
    {
        "id": "shapeshifter_challenge",
        "name": "The Shapeshifter's Challenge",
        "description": "A rival kitsune issues a challenge, their forms flickering between human and fox. The air crackles with competitive energy.",
        "emoji": "🦊"
    },
    {
        "id": "fox_fire_trial",
        "name": "The Fox Fire Trial",
        "description": "Sacred blue flames dance before you, a test of your mastery over kitsune magic. The heat is both inviting and intimidating.",
        "emoji": "πŸ”₯"
    }
]

ACTIONS = [
    {
        "id": "fox_fire",
        "name": "Use Fox Fire",
        "description": "Summon mystical flames to illuminate the darkness or ward off evil spirits.",
        "emoji": "πŸ”₯"
    },
    {
        "id": "shapeshift",
        "name": "Shapeshift",
        "description": "Transform your appearance to blend in or deceive others.",
        "emoji": "🦊"
    },
    {
        "id": "possess_object",
        "name": "Possess an Object",
        "description": "Infuse your spirit into an inanimate object to manipulate or gather information.",
        "emoji": "πŸ‘»"
    },
    {
        "id": "call_spirits",
        "name": "Call Upon Ancient Spirits",
        "description": "Invoke the wisdom and power of your ancestors to guide you.",
        "emoji": "🌟"
    },
    {
        "id": "use_artifact",
        "name": "Use Mystical Artifact",
        "description": "Activate a powerful magical item to unleash its effects.",
        "emoji": "πŸ—‘οΈ"
    }
]

def generate_situation():
    return random.choice(SITUATIONS)

def generate_actions():
    return random.sample(ACTIONS, 3)

def evaluate_action(action, power_level, mystical_energy, history):
    base_success_chance = (power_level + mystical_energy) / 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 create_graph_from_history(history_df):
    nodes = []
    edges = []
    for index, row in history_df.iterrows():
        node_id = f"{index}-{row['situation_id']}-{row['action_id']}"
        content = f"{row['situation_emoji']} {row['situation_name']}\n{row['action_emoji']} {row['action_name']}\nOutcome: {'βœ… Success' if row['outcome'] else '❌ Failure'}\nπŸ•’ {row['timestamp']}"
        new_node = StreamlitFlowNode(node_id, (0, 0), {'content': content}, 'output', 'bottom', 'top')
        nodes.append(new_node)
        
        if index > 0:
            prev_node_id = f"{index-1}-{history_df.iloc[index-1]['situation_id']}-{history_df.iloc[index-1]['action_id']}"
            new_edge = StreamlitFlowEdge(f"{prev_node_id}-{node_id}", prev_node_id, node_id, animated=True, dashed=True)
            edges.append(new_edge)
    
    return nodes, edges

def save_history_to_csv(history_df):
    csv_buffer = StringIO()
    history_df.to_csv(csv_buffer, index=False)
    csv_string = csv_buffer.getvalue()
    b64 = base64.b64encode(csv_string.encode()).decode()
    return b64

def load_history_from_csv(csv_string):
    csv_buffer = StringIO(csv_string)
    history_df = pd.read_csv(csv_buffer)
    return history_df

def app():
    st.markdown("# 🦊 Kitsune - The Mystical Shape-Shifter Game 🦊")
    
    if 'user_id' not in st.session_state:
        st.session_state.user_id = str(uuid.uuid4())
    
    if 'game_state' not in st.session_state:
        st.session_state.game_state = {
            'score': 0,
            'history': {},
            'power_level': 50,
            'mystical_energy': 75,
            'history_df': pd.DataFrame(columns=['user_id', 'timestamp', 'situation_id', 'situation_name', 'situation_emoji', 'action_id', 'action_name', 'action_emoji', 'outcome', 'score'])
        }
    
    # Game Stats
    st.sidebar.markdown("## πŸ“Š Game Stats")
    st.sidebar.markdown(f"**Score:** {st.session_state.game_state['score']}")
    
    # Character Stats
    power_level = st.sidebar.slider('Power Level ⚑', 0, 100, st.session_state.game_state['power_level'])
    mystical_energy = st.sidebar.slider('Mystical Energy ✨', 0, 100, st.session_state.game_state['mystical_energy'])
    
    # Game Loop
    situation = generate_situation()
    actions = generate_actions()
    
    st.markdown(f"## {situation['emoji']} Current Situation: {situation['name']}")
    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']}"):
            outcome, success_chance = evaluate_action(action, power_level, mystical_energy, st.session_state.game_state['history'])
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            
            st.markdown(f"You decided to: **{action['name']}**")
            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 history
            if action['id'] in st.session_state.game_state['history']:
                st.session_state.game_state['history'][action['id']] += 1 if outcome else -1
            else:
                st.session_state.game_state['history'][action['id']] = 1 if outcome else -1
            
            # Add new record to history DataFrame
            new_record = pd.DataFrame({
                'user_id': [st.session_state.user_id],
                'timestamp': [timestamp],
                'situation_id': [situation['id']],
                'situation_name': [situation['name']],
                'situation_emoji': [situation['emoji']],
                'action_id': [action['id']],
                'action_name': [action['name']],
                'action_emoji': [action['emoji']],
                'outcome': [outcome],
                'score': [st.session_state.game_state['score']]
            })
            st.session_state.game_state['history_df'] = pd.concat([st.session_state.game_state['history_df'], new_record], ignore_index=True)
            
            # Save history to CSV and provide download link
            csv_b64 = save_history_to_csv(st.session_state.game_state['history_df'])
            href = f'<a href="data:file/csv;base64,{csv_b64}" download="kitsune_game_history.csv">Download Game History</a>'
            st.markdown(href, unsafe_allow_html=True)
    
    # Display Graph
    if not st.session_state.game_state['history_df'].empty:
        st.markdown("## 🌳 Your Journey")
        nodes, edges = create_graph_from_history(st.session_state.game_state['history_df'])
        streamlit_flow('kitsune_game_flow', 
                       nodes, 
                       edges, 
                       layout=TreeLayout(direction='down'),
                       fit_view=True, 
                       height=600)
    
    # Character Stats Visualization
    data = {"Stat": ["Power Level ⚑", "Mystical Energy ✨"],
            "Value": [power_level, mystical_energy]}
    df = pd.DataFrame(data)
    fig = px.bar(df, x='Stat', y='Value', title="Kitsune Stats πŸ“Š")
    st.plotly_chart(fig)
    
    # Load Game State
    st.markdown("## πŸ’Ύ Load Game")
    uploaded_file = st.file_uploader("Load Game History", type="csv")
    if uploaded_file is not None:
        csv_string = uploaded_file.getvalue().decode()
        loaded_history_df = load_history_from_csv(csv_string)
        st.session_state.game_state['history_df'] = loaded_history_df
        st.session_state.game_state['score'] = loaded_history_df['score'].iloc[-1]
        st.session_state.user_id = loaded_history_df['user_id'].iloc[0]
        st.success("Game history loaded successfully!")

if __name__ == "__main__":
    app()