on
ai 주식투자
- Get link
- X
- Other Apps
This example demonstrates simulating dice rolls using NumPy and a simple graphical user interface (GUI) built with Tkinter. The GUI allows users to specify the number of dice to roll and the number of sides on each die, then displays the results of the simulation.
dice_simulator.py
import tkinter as tk
from tkinter import messagebox
import numpy as np
def simulate_dice_rolls():
try:
num_dice = int(num_dice_entry.get())
num_sides = int(num_sides_entry.get())
if num_dice <= 0 or num_sides <= 0:
raise ValueError("Number of dice and sides must be positive integers.")
rolls = np.random.randint(1, num_sides + 1, size=num_dice)
result_label.config(text="Dice Rolls: " + str(rolls))
total = np.sum(rolls)
total_label.config(text="Total: " + str(total))
except ValueError as e:
messagebox.showerror("Error", str(e))
root = tk.Tk()
root.title("Dice Roll Simulator")
num_dice_label = tk.Label(root, text="Number of Dice:")
num_dice_label.pack()
num_dice_entry = tk.Entry(root)
num_dice_entry.pack()
num_sides_label = tk.Label(root, text="Number of Sides per Die:")
num_sides_label.pack()
num_sides_entry = tk.Entry(root)
num_sides_entry.pack()
roll_button = tk.Button(root, text="Roll Dice", command=simulate_dice_rolls)
roll_button.pack(pady=10)
result_label = tk.Label(root, text="")
result_label.pack()
total_label = tk.Label(root, text="")
total_label.pack()
root.mainloop()
-
How to Run the Code:
pip install tkinter numpy
-
python dice_simulator.py
-A window will appear with input fields for the number of dice and the number of sides per die. Enter the desired values and click the "Roll Dice" button to simulate the rolls and display the results.
Code Explanation:
Comments
Post a Comment