import streamlit as st import secrets # Dùng secrets thay cho random để tăng tính ngẫu nhiên from collections import Counter # Cấu hình Streamlit st.set_page_config(page_title="Bầu Cua Tôm Cá - Xác Suất Xúc Xắc 3", page_icon="🎲", layout="centered") # Tiêu đề ứng dụng st.title("🎲 Bầu Cua Tôm Cá 🎲") st.subheader("Chọn 3 mặt xúc xắc:") # Danh sách các mặt xúc xắc hợp lệ valid_faces = ["Bầu", "Cua", "Tôm", "Cá", "Gà", "Nai"] opposite_faces = { "Gà": "Nai", "Nai": "Gà", "Cua": "Tôm", "Tôm": "Cua", "Bầu": "Cá", "Cá": "Bầu" } # Chọn mặt xúc xắc bằng radio button face_selectors = [st.radio(f"Chọn mặt xúc xắc {i+1}", valid_faces) for i in range(3)] # Chọn số lần lắc ban đầu roll_times = st.selectbox("Số lần lắc ban đầu:", ["1000", "5", "50", "100", "500", "1"]) roll_times = int(roll_times) # Khi nhấn nút "Lắc Xúc Xắc" if st.button("Lắc Xúc Xắc"): faces = face_selectors roll_history = [] max_iterations = 1000 # Giới hạn số vòng lặp để tránh chạy vô tận iteration = 0 while iteration < max_iterations: iteration += 1 # Lắc xúc xắc và ghi nhận kết quả for _ in range(roll_times): rolled_faces = [secrets.choice([f for f in valid_faces if f != opposite_faces[face]]) for face in faces] roll_history.extend(rolled_faces) # Đếm số lần xuất hiện của từng mặt face_counts = Counter(roll_history) total_rolls = len(roll_history) # Tính xác suất probabilities = {face: (count / total_rolls) * 100 for face, count in face_counts.items()} # Sắp xếp theo số lần xuất hiện sorted_face_counts = sorted(face_counts.items(), key=lambda x: x[1], reverse=True) # Nếu có ít nhất 2 mặt xúc xắc, kiểm tra điều kiện dừng if len(sorted_face_counts) > 1: rank_1_face, rank_1_count = sorted_face_counts[0] rank_2_face, rank_2_count = sorted_face_counts[1] if rank_1_count - rank_2_count >= 30: break # Dừng vòng lặp nếu điều kiện được thỏa mãn # Tăng số lần lắc để tiếp tục thử nghiệm roll_times *= 2 # Nhân đôi số lần lắc để đạt điều kiện nhanh hơn # Hiển thị kết quả cuối cùng st.write(f"🔄 Đã lắc tổng cộng **{total_rolls // 3} lần** sau {iteration} vòng lặp:") for face, count in sorted_face_counts: st.write(f"- {face}: {count} lần") st.write("\n📊 **Xác suất tổng hợp:**") for rank, (face, prob) in enumerate(sorted(probabilities.items(), key=lambda x: x[1], reverse=True), 1): st.write(f"{rank}. {face}: {prob:.2f}%") # Reset ứng dụng if st.button("Reset"): st.experimental_rerun()