import tkinter as tk import random stop_simulation = False def estimate_pi(num_points): points_inside_circle = 0 for _ in range(num_points): if stop_simulation: break x = random.uniform(0, 1) y = random.uniform(0, 1) distance = x**2 + y**2 if distance <= 1: points_inside_circle += 1 pi_estimate = 4 * points_inside_circle / num_points return pi_estimate def draw_circle_and_square(canvas): # Draw square canvas.create_rectangle(100, 100, 300, 300) # Draw circle canvas.create_oval(100, 100, 300, 300, outline="blue") def stop_simulation_func(): global stop_simulation stop_simulation = True def clear_canvas(): global stop_simulation stop_simulation = True canvas.delete("all") draw_circle_and_square(canvas) def start_simulation(): global stop_simulation stop_simulation = False num_points = int(entry.get()) # Clear canvas canvas.delete("all") # Draw circle and square draw_circle_and_square(canvas) # Draw points for _ in range(num_points): if stop_simulation: break x = random.randint(100, 300) y = random.randint(100, 300) distance = (x - 200) ** 2 + (y - 200) ** 2 if distance <= 10000: canvas.create_oval(x, y, x, y, fill="green") else: canvas.create_oval(x, y, x, y, fill="red") canvas.update() if not stop_simulation: # Estimate pi and display result pi_value = estimate_pi(num_points) label_result.config(text=f"Estimated value of pi using {num_points} points: {pi_value}") # Create the main window root = tk.Tk() root.title("Monte Carlo Pi Estimation App") # Create GUI elements label = tk.Label(root, text="Enter the number of points:") label.pack() entry = tk.Entry(root, justify="center") entry.pack() start_button = tk.Button(root, text="Start Simulation", command=start_simulation) start_button.pack() stop_button = tk.Button(root, text="Stop Simulation", command=stop_simulation_func) stop_button.pack() clear_button = tk.Button(root, text="Clear Points", command=clear_canvas) clear_button.pack() label_result = tk.Label(root, text="") label_result.pack() canvas = tk.Canvas(root, width=400, height=400) canvas.pack() # Draw circle and square initially draw_circle_and_square(canvas) # Run the main loop root.mainloop()