awacke1 commited on
Commit
6fc412e
Β·
1 Parent(s): c28abe2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -68
app.py CHANGED
@@ -1,73 +1,93 @@
1
  import os
2
- import streamlit as st
3
- import numpy as np
4
  import pandas as pd
5
- import plotly.express as px
6
-
7
- st.set_page_config(layout='wide')
8
-
9
- st.title('🎲 Random Dice Game')
10
-
11
- dice_types = [{'name': 'Six-sided Dice', 'sides': 6, 'emoji': '🎲'},
12
- {'name': 'Twenty-sided Dice', 'sides': 20, 'emoji': '🎯'},
13
- {'name': 'Thirty-sided Dice', 'sides': 30, 'emoji': '🎯'},
14
- {'name': 'One Hundred-sided Dice', 'sides': 100, 'emoji': 'πŸ’―'}]
15
-
16
- def username_input():
17
- if 'username' not in st.session_state:
18
- st.session_state.username = ''
19
- st.text_input('πŸ‘€ Username', key='username')
20
-
21
- def display_dice_roll_distribution():
22
- dice_type = st.selectbox('🎲 Choose a type of dice', dice_types, format_func=lambda d: f"{d['name']} {d['emoji']}")
23
- num_rolls = st.slider('πŸ”„ How many times do you want to roll the dice?', 1, 1000000, 1000)
24
-
25
- rolls = np.random.randint(1, dice_type['sides'] + 1, num_rolls, dtype=np.uint64)
26
- roll_counts = pd.Series(rolls).value_counts().sort_index()
27
-
28
- fig = px.sunburst(names=[f'Roll {i}' for i in roll_counts.index],
29
- parents=['Dice Rolls'] * dice_type['sides'],
30
- values=roll_counts.values,
31
- color=[f'Roll {i}' for i in roll_counts.index],
32
- color_discrete_sequence=px.colors.qualitative.Dark24,
33
- maxdepth=2)
34
- fig.update_layout(title='πŸ“ˆ Dice Roll Distribution', margin=dict(l=20, r=20, t=40, b=20), width=800, height=600)
35
-
36
- show_labels = st.checkbox('🏷️ Show Labels', value=True)
37
- if not show_labels:
38
- fig.update_traces(textinfo='none')
39
- fig.show()
40
-
41
- return dice_type, rolls
42
-
43
- def display_bonus_match(bonus_match, bonus_dice_type, bonus_dice_emoji):
44
- if bonus_match:
45
- st.success(f'πŸŽ‰ You rolled a {bonus_dice_type} {bonus_dice_emoji} on the first roll!')
46
-
47
- def update_dice_roll_history(dice_type, rolls):
48
- bonus_match = False
49
- for dice in dice_types:
50
- if rolls[0] == dice['sides']:
51
- bonus_match = True
52
- bonus_dice_type = dice['name']
53
- bonus_dice_emoji = dice['emoji']
54
- break
55
-
56
- dice_roll_history = st.session_state.dice_roll_history
57
- new_roll_data = pd.DataFrame({'Roll': rolls,
58
- 'Count': np.ones(len(rolls), dtype=np.uint64),
59
- 'DiceNumberOfSides': [dice_type['sides']] * len(rolls),
60
- 'Username': [st.session_state.username] * len(rolls)})
61
- if bonus_match:
62
- new_roll_data['BonusMatchToDiceName'] = [bonus_dice_type] * len(rolls)
63
- new_roll_data['BonusMatchToDiceEmoji'] = [bonus_dice_emoji] * len(rolls)
64
- dice_roll_history = dice_roll_history.append(new_roll_data, ignore_index=True)
65
- st.session_state.dice_roll_history = dice_roll_history
66
-
67
- return bonus_match, bonus_dice_type, bonus_dice_emoji
68
-
69
- def download_dice_roll_history(include_name_column):
70
- dice_roll
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
 
73
  st.write("""
 
1
  import os
 
 
2
  import pandas as pd
3
+ import streamlit as st
4
+
5
+ # Set page title and icon
6
+ st.set_page_config(page_title="Dice Roller", page_icon="🎲")
7
+
8
+ # Set page title
9
+ st.title("🎲 Dice Roller")
10
+
11
+ # Check if username is already set, if not, create a text input to set it
12
+ if 'username' not in st.session_state:
13
+ st.session_state.username = st.text_input("πŸ‘€ Username", max_chars=50)
14
+
15
+ # Define the dice types
16
+ dice_types = {
17
+ "🎲 Six-sided dice": {"sides": 6, "name": "d6", "emoji": "🎲"},
18
+ "🎲 Thirty-sided dice": {"sides": 30, "name": "d30", "emoji": "🎲"},
19
+ "🎲 Twenty-sided dice": {"sides": 20, "name": "d20", "emoji": "🎲"},
20
+ "🎲 One hundred-sided dice": {"sides": 100, "name": "d100", "emoji": "πŸ’―"},
21
+ }
22
+
23
+ # Create a selectbox to choose the dice type
24
+ dice_type = st.selectbox("🎲 Select a dice type", options=list(dice_types.keys()), format_func=lambda x: x.split(' ')[-2])
25
+
26
+ # Create a slider to choose the number of rolls
27
+ num_rolls = st.slider("🎲 How many times do you want to roll the dice?", 1, 1000000, 100)
28
+
29
+ # Create a string with the rolls for the selected dice type
30
+ rolls = [str(pd.Series([dice_types[dice_type]["sides"]] * num_rolls).apply(pd.Series.sample, replace=True))]
31
+ rolls = rolls[0].strip('[]').split('\n')
32
+
33
+ # Create a button to roll the dice
34
+ if st.button("🎲 Roll Dice"):
35
+ # Display the rolls
36
+ display_roll = [int(i) for i in rolls]
37
+ st.write(f"{dice_types[dice_type]['emoji']} You rolled {len(display_roll)} {dice_types[dice_type]['name']} dice: {', '.join(map(str, display_roll))}.")
38
+
39
+ # Check if the count is a multiple of the dice sides to see if there's a bonus match
40
+ bonus_match = None
41
+ count = sum(display_roll)
42
+ if count % dice_types[dice_type]['sides'] == 0:
43
+ bonus_match = dice_types[dice_type]['name']
44
+ bonus_emoji = dice_types[dice_type]['emoji']
45
+ st.write(f"πŸŽ‰ Bonus match! You rolled a multiple of {dice_types[dice_type]['sides']}.")
46
+
47
+ # Create a DataFrame with the rolls, count, and dice number of sides
48
+ df = pd.DataFrame({'Roll': rolls, 'Count': count, 'DiceNumberOfSides': dice_types[dice_type]['sides']})
49
+
50
+ # Check if the file exists
51
+ file_exists = os.path.exists("SharedState.csv")
52
+
53
+ # Append the new rolls to the file
54
+ if file_exists:
55
+ df.to_csv("SharedState.csv", mode='a', header=False, index=False)
56
+ # If the file doesn't exist, create it and write the headers
57
+ else:
58
+ df.to_csv("SharedState.csv", mode='w', header=True, index=False)
59
+
60
+ # Create a checkbox to download the roll history
61
+ download_roll_history = st.checkbox("πŸ“₯ Download Roll History", value=True)
62
+
63
+ # Check if the file exists and display it as a download link
64
+ if os.path.exists("SharedState.csv"):
65
+ # Read the file into a DataFrame
66
+ data = pd.read_csv("SharedState.csv")
67
+
68
+ # Check if the user wants to include their name in the output
69
+ if st.checkbox("πŸ’» Include Username in Output", value=True):
70
+ # Add the username to the DataFrame
71
+ data["DiceRollerName"] = st.session_state.username
72
+ # Check if there is a bonus match and add the bonus match column to the DataFrame
73
+ if bonus_match:
74
+ data["BonusMatchToDiceName"] = bonus_match
75
+ data["BonusMatchToDiceEmoji"] = bonus_emoji
76
+ # Check if the user wants to download the file
77
+ if download_roll_history:
78
+ st.download_button("πŸ“₯ Download Roll History", data.to_csv(index=False), f"shared_state_{st.session_state.username}.csv", "text/csv")
79
+ else:
80
+ # Remove the username from the DataFrame
81
+ data = data.drop(columns=["DiceRollerName"])
82
+ # Check if there is a bonus match and add the bonus match column to the DataFrame
83
+ if bonus_match:
84
+ data["BonusMatchToDiceName"] = bonus_match
85
+ data["BonusMatchToDiceEmoji"] = bonus_emoji
86
+ # Check if the user wants to download the file
87
+ if download_roll_history:
88
+ st.download_button("πŸ“₯ Download Roll History", data.to_csv(index=False), "shared_state.csv", "text/csv")
89
+ else:
90
+ st.write("πŸ“œ No roll history available.")
91
 
92
 
93
  st.write("""