vloz do skriptu funkci, která po stisknuti tlačítka Analyzovat, bude analyžovat…
- User
vloz do skriptu funkci, která po stisknuti tlačítka Analyzovat, bude analyžovat narysovany geometricky utvar na počet bodu, usecek, a ploch, které vznikly zakreslenim usecek. plochy pak rozdeli na trojúhelníky, ctyruhelniky a tak dale. jejich pocty pak zapise do textového pole.
cely upraveny skript pak zapis.
puvodni skript.
import tkinter as tk from tkinter import messagebox, filedialog import math from PIL import Image, ImageDraw, ImageGrab import os import re
class CircleDrawer: def init(self, root): self.root = root self.root.title("Circle Drawer")
# Inicializace proměnných self.num_points = 0 self.points = {} # point_num: (x, y) self.lines = set() # set of frozensets self.intersections = {} # (x, y): intersection_num self.intersection_counter = 1 self.current_clicks = [] # Vytvoření GUI prvků self.create_widgets() def create_widgets(self): # Horní rámec pro vstupní ovládací prvky control_frame = tk.Frame(self.root) control_frame.pack(side=tk.TOP, pady=10, padx=10, fill=tk.X) # Vstup pro počet bodů tk.Label(control_frame, text="Počet Bodů (1-36):").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W) self.num_entry = tk.Entry(control_frame, width=5) self.num_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W) self.num_entry.insert(0, "12") # výchozí hodnota self.draw_circle_button = tk.Button(control_frame, text="Nakreslit Kružnici", command=self.draw_circle) self.draw_circle_button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.W) # Vstup pro páry bodů tk.Label(control_frame, text="Zadání Párů (např. (2,8),(2,9)):").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W) self.pair_entry = tk.Entry(control_frame, width=30) self.pair_entry.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=tk.W) self.draw_lines_button = tk.Button(control_frame, text="Nakreslit Čáry", command=self.draw_lines_from_input) self.draw_lines_button.grid(row=1, column=3, padx=5, pady=5, sticky=tk.W) # Hlavní rámeček pro plátno a boční informace main_frame = tk.Frame(self.root) main_frame.pack(padx=10, pady=10) # Plátno pro kreslení self.canvas_size = 400 # Upravená velikost pro lepší rozložení self.canvas = tk.Canvas(main_frame, width=self.canvas_size, height=self.canvas_size, bg="white") self.canvas.pack(side=tk.LEFT, padx=10) self.canvas.bind("<Button-1>", self.canvas_click) # Boční rámec pro seznamy a tlačítka side_frame = tk.Frame(main_frame) side_frame.pack(side=tk.RIGHT, fill=tk.Y) # Seznam čar tk.Label(side_frame, text="Čáry:").pack(anchor=tk.W) self.lines_text = tk.Text(side_frame, width=25, height=10) self.lines_text.pack(pady=5) # Seznam průsečíků tk.Label(side_frame, text="Průsečíky:").pack(anchor=tk.W, pady=(10, 0)) self.intersections_text = tk.Text(side_frame, width=25, height=10) self.intersections_text.pack(pady=5) # Tlačítka buttons_frame = tk.Frame(side_frame) buttons_frame.pack(pady=10) self.back_button = tk.Button(buttons_frame, text="Zpět", command=self.back) self.back_button.pack(fill=tk.X, pady=2) self.save_button = tk.Button(buttons_frame, text="Uložit", command=self.save_images) self.save_button.pack(fill=tk.X, pady=2) self.clear_button = tk.Button(buttons_frame, text="Vymazat", command=self.clear_all) self.clear_button.pack(fill=tk.X, pady=2) def draw_circle(self): try: n = int(self.num_entry.get()) if not 1 <= n <= 36: raise ValueError except ValueError: messagebox.showerror("Neplatný Vstup", "Prosím, zadejte celé číslo mezi 1 a 36.") return self.num_points = n self.points = {} self.lines = set() self.intersections = {} self.intersection_counter = 1 self.current_clicks = [] self.lines_text.delete(1.0, tk.END) self.intersections_text.delete(1.0, tk.END) self.canvas.delete("all") center = self.canvas_size / 2 radius = self.canvas_size * 0.4 angle_gap = -2 * math.pi / n # Záporný pro směrem hodinových ručiček for i in range(n): angle = -math.pi / 2 + i * angle_gap # Start ze shora, směrem hodinových ručiček x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") def parse_pairs(self, input_text): pattern = r'\s*\((\d+),\s*(\d+)\)\s*' # Updatovaný regulární výraz matches = re.findall(pattern, input_text) pairs = [] for match in matches: a, b = map(int, match) # Použijeme map a int pro převod stringů na čísla if a != b and a in self.points and b in self.points: pair = frozenset([a, b]) pairs.append(pair) return pairs def draw_lines_from_input(self): input_text = self.pair_entry.get() pairs = self.parse_pairs(input_text) for pair in pairs: if pair not in self.lines: self.lines.add(pair) self.draw_line(pair) self.update_lines_text() def draw_line(self, pair): a, b = sorted(pair) x1, y1 = self.points[a] x2, y2 = self.points[b] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line_{a}{b}") # Kontrola průsečíků self.check_intersections(a, b) def update_lines_text(self): self.lines_text.delete(1.0, tk.END) for pair in sorted(self.lines, key=lambda x: sorted(x)): a, b = sorted(pair) self.lines_text.insert(tk.END, f"({a}, {b})\n") def canvas_click(self, event): if self.num_points == 0: return clicked_point = self.get_clicked_point(event.x, event.y) if clicked_point is None: return if clicked_point in self.current_clicks: return # Ignorovat opakované kliknutí na stejný bod self.current_clicks.append(clicked_point) self.highlight_point(clicked_point) if len(self.current_clicks) == 2: pair = frozenset(self.current_clicks) if pair not in self.lines: self.lines.add(pair) self.draw_line(pair) self.update_lines_text() self.unhighlight_points() self.current_clicks = [] def get_clicked_point(self, x, y): for point_num, (px, py) in self.points.items(): if math.hypot(px - x, py - y) <= 10: return point_num return None def highlight_point(self, point_num): x, y = self.points[point_num] r = 8 self.canvas.create_oval(x - r, y - r, x + r, y + r, outline="green", width=2, tags="highlight") def unhighlight_points(self): self.canvas.delete("highlight") def back(self): if not self.lines: return last_line = sorted(self.lines)[-1] self.lines.remove(frozenset(last_line)) self.redraw_canvas() self.update_lines_text() self.update_intersections() def clear_all(self): self.lines.clear() self.intersections.clear() self.intersection_counter = 1 self.current_clicks = [] self.lines_text.delete(1.0, tk.END) self.intersections_text.delete(1.0, tk.END) self.redraw_canvas() def redraw_canvas(self): self.canvas.delete("all") center = self.canvas_size / 2 radius = self.canvas_size * 0.4 angle_gap = -2 * math.pi / self.num_points # Směr hodinových ručiček for i in range(self.num_points): angle = -math.pi / 2 + i * angle_gap # Start ze shora x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") # Nakreslení čar for pair in self.lines: a, b = sorted(pair) x1, y1 = self.points[a] x2, y2 = self.points[b] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line{a}{b}") # Nakreslení průsečíků for (x, y), num in self.intersections.items(): self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection{num}") self.canvas.create_text(x + 6, y, text=str(num), fill="purple", tags=f"intersection_text_{num}") def check_intersections(self, a, b): new_line = (self.points[a], self.points[b]) for existing_pair in self.lines: if existing_pair == frozenset([a, b]): continue c, d = sorted(existing_pair) existing_line = (self.points[c], self.points[d]) intersect_point = self.get_line_intersection(new_line, existing_line) if intersect_point: x, y = intersect_point # Kontrola, zda průsečík není na koncích čar if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): # Kontrola, zda průsečík již není zaznamenán if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 def get_line_intersection(self, line1, line2): (x1, y1), (x2, y2) = line1 (x3, y3), (x4, y4) = line2 # Výpočet jmenovatelů s operátory násobení denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None # Paralelní nebo souběžné čáry # Výpočet průsečíku Px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denom Py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denom # Kontrola, zda průsečík leží na obou úsecích if self.point_on_segment(Px, Py, line1) and self.point_on_segment(Px, Py, line2): return (Px, Py) else: return None def point_on_segment(self, x, y, segment): (x1, y1), (x2, y2) = segment return (min(x1, x2) - 1e-6 <= x <= max(x1, x2) + 1e-6) and (min(y1, y2) - 1e-6 <= y <= max(y1, y2) + 1e-6) def update_intersections(self): # Přepočet průsečíků self.intersections.clear() self.intersections_text.delete(1.0, tk.END) self.intersection_counter = 1 lines = list(self.lines) for i in range(len(lines)): for j in range(i + 1, len(lines)): pair1 = lines[i] pair2 = lines[j] a, b = sorted(pair1) c, d = sorted(pair2) if len(pair1.intersection(pair2)) > 0: continue # Čáry sdílejí společný bod intersect_point = self.get_line_intersection((self.points[a], self.points[b]), (self.points[c], self.points[d])) if intersect_point: x, y = intersect_point if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 self.redraw_canvas() def is_at_endpoint(self, x, y, points): for px, py in points: if math.isclose(px, x, abs_tol=1e-6) and math.isclose(py, y, abs_tol=1e-6): return True return False def save_images(self): if self.num_points == 0: messagebox.showerror("Chyba", "Nejprve nakreslete kružnici.") return # Zeptání se na složku pro uložení directory = filedialog.askdirectory() if not directory: return # Uložení prvního obrázku s popisky a průsečíky ps_file = os.path.join(directory, "kruznice_s_popisky.eps") self.canvas.postscript(file=ps_file, colormode='color') try: img1 = Image.open(ps_file) img1.save(os.path.join(directory, "kruznice_s_popisky.png"), "png") os.remove(ps_file) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání prvního obrázku: {e}") return # Uložení druhého obrázku bez popisků a průsečíků # Dočasné skrytí popisků a průsečíků all_items = self.canvas.find_all() for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='hidden') # Aktualizace plátna self.canvas.update() ps_file2 = os.path.join(directory, "kruznice_bez_popisku.eps") self.canvas.postscript(file=ps_file2, colormode='color') try: img2 = Image.open(ps_file2) img2.save(os.path.join(directory, "kruznice_bez_popisku.png"), "png") os.remove(ps_file2) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání druhého obrázku: {e}") return # Obnovení viditelnosti popisků a průsečíků for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='normal') messagebox.showinfo("Hotovo", f"Obrázky byly uloženy do složky: {directory}")if name == "main": root = tk.Tk() app = CircleDrawer(root) root.mainloop()
- Assistant
Rozumím, že chcete do svého skriptu přidat funkci, která analyzuje nakreslený geometrický útvar po stisknutí tlačítka "Analyzovat". Tato funkce by měla spočítat počet bodů, úseček a ploch (polygonů) rozdělených na trojúhelníky, čtyřúhelníky atd., a výsledky zobrazit v textovém poli. Níže uvádím upravený skript s implementovanou touto funkcionalitou.
Přehled úprav:
-
Přidání tlačítka "Analyzovat": Vytvoříme nové tlačítko v uživatelském rozhraní, které spustí analyzaci.
-
Vytvoření textového pole pro výsledky analýzy: Přidáme nové textové pole, kde se budou zobrazovat výsledky analýzy.
-
Implementace analyzovací funkce: Tato funkce:
- Sestrojí graf z existujících bodů a úseček, včetně průsečíků jako nových bodů.
- Použije Eulerovu formuli pro odhad počtu ploch.
- Pokusí se identifikovat jednotlivé plochy a kategorizovat je podle počtu stran.
- Výsledky zapíše do textového pole.
Níže je kompletní upravený skript:
import tkinter as tk from tkinter import messagebox, filedialog import math from PIL import Image, ImageDraw, ImageGrab, ImageTk import os import re from collections import defaultdict, deque class CircleDrawer: def __init__(self, root): self.root = root self.root.title("Circle Drawer") # Inicializace proměnných self.num_points = 0 self.points = {} # point_num: (x, y) self.lines = set() # set of frozensets self.intersections = {} # (x, y): intersection_num self.intersection_counter = 1 self.current_clicks = [] # Vytvoření GUI prvků self.create_widgets() def create_widgets(self): # Horní rámec pro vstupní ovládací prvky control_frame = tk.Frame(self.root) control_frame.pack(side=tk.TOP, pady=10, padx=10, fill=tk.X) # Vstup pro počet bodů tk.Label(control_frame, text="Počet Bodů (1-36):").grid(row=0, column=0, padx=5, pady=5, sticky=tk.W) self.num_entry = tk.Entry(control_frame, width=5) self.num_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W) self.num_entry.insert(0, "12") # výchozí hodnota self.draw_circle_button = tk.Button(control_frame, text="Nakreslit Kružnici", command=self.draw_circle) self.draw_circle_button.grid(row=0, column=2, padx=5, pady=5, sticky=tk.W) # Vstup pro páry bodů tk.Label(control_frame, text="Zadání Párů (např. (2,8),(2,9)):").grid(row=1, column=0, padx=5, pady=5, sticky=tk.W) self.pair_entry = tk.Entry(control_frame, width=30) self.pair_entry.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky=tk.W) self.draw_lines_button = tk.Button(control_frame, text="Nakreslit Čáry", command=self.draw_lines_from_input) self.draw_lines_button.grid(row=1, column=3, padx=5, pady=5, sticky=tk.W) # Přidání tlačítka "Analyzovat" self.analyze_button = tk.Button(control_frame, text="Analyzovat", command=self.analyze_geometry) self.analyze_button.grid(row=2, column=0, padx=5, pady=5, sticky=tk.W) # Hlavní rámeček pro plátno a boční informace main_frame = tk.Frame(self.root) main_frame.pack(padx=10, pady=10) # Plátno pro kreslení self.canvas_size = 400 # Upravená velikost pro lepší rozložení self.canvas = tk.Canvas(main_frame, width=self.canvas_size, height=self.canvas_size, bg="white") self.canvas.pack(side=tk.LEFT, padx=10) self.canvas.bind("<Button-1>", self.canvas_click) # Boční rámec pro seznamy a tlačítka side_frame = tk.Frame(main_frame) side_frame.pack(side=tk.RIGHT, fill=tk.Y) # Seznam čar tk.Label(side_frame, text="Čáry:").pack(anchor=tk.W) self.lines_text = tk.Text(side_frame, width=25, height=10) self.lines_text.pack(pady=5) # Seznam průsečíků tk.Label(side_frame, text="Průsečíky:").pack(anchor=tk.W, pady=(10, 0)) self.intersections_text = tk.Text(side_frame, width=25, height=10) self.intersections_text.pack(pady=5) # Přidání textového pole pro analýzu tk.Label(side_frame, text="Analýza:").pack(anchor=tk.W, pady=(10, 0)) self.analysis_text = tk.Text(side_frame, width=25, height=10) self.analysis_text.pack(pady=5) # Tlačítka buttons_frame = tk.Frame(side_frame) buttons_frame.pack(pady=10) self.back_button = tk.Button(buttons_frame, text="Zpět", command=self.back) self.back_button.pack(fill=tk.X, pady=2) self.save_button = tk.Button(buttons_frame, text="Uložit", command=self.save_images) self.save_button.pack(fill=tk.X, pady=2) self.clear_button = tk.Button(buttons_frame, text="Vymazat", command=self.clear_all) self.clear_button.pack(fill=tk.X, pady=2) def draw_circle(self): try: n = int(self.num_entry.get()) if not 1 <= n <= 36: raise ValueError except ValueError: messagebox.showerror("Neplatný Vstup", "Prosím, zadejte celé číslo mezi 1 a 36.") return self.num_points = n self.points = {} self.lines = set() self.intersections = {} self.intersection_counter = 1 self.current_clicks = [] self.lines_text.delete(1.0, tk.END) self.intersections_text.delete(1.0, tk.END) self.analysis_text.delete(1.0, tk.END) self.canvas.delete("all") center = self.canvas_size / 2 radius = self.canvas_size * 0.4 angle_gap = -2 * math.pi / n # Záporný pro směrem hodinových ručiček for i in range(n): angle = -math.pi / 2 + i * angle_gap # Start ze shora, směrem hodinových ručiček x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") def parse_pairs(self, input_text): pattern = r'\s*\((\d+),\s*(\d+)\)\s*' # Upravený regulární výraz matches = re.findall(pattern, input_text) pairs = [] for match in matches: a, b = map(int, match) # Použijeme map a int pro převod stringů na čísla if a != b and a in self.points and b in self.points: pair = frozenset([a, b]) pairs.append(pair) return pairs def draw_lines_from_input(self): input_text = self.pair_entry.get() pairs = self.parse_pairs(input_text) for pair in pairs: if pair not in self.lines: self.lines.add(pair) self.draw_line(pair) self.update_lines_text() self.analysis_text.delete(1.0, tk.END) # Vymazat předchozí analýzu def draw_line(self, pair): a, b = sorted(pair) x1, y1 = self.points[a] x2, y2 = self.points[b] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line_{a}{b}") # Kontrola průsečíků self.check_intersections(a, b) def update_lines_text(self): self.lines_text.delete(1.0, tk.END) for pair in sorted(self.lines, key=lambda x: sorted(x)): a, b = sorted(pair) self.lines_text.insert(tk.END, f"({a}, {b})\n") def canvas_click(self, event): if self.num_points == 0: return clicked_point = self.get_clicked_point(event.x, event.y) if clicked_point is None: return if clicked_point in self.current_clicks: return # Ignorovat opakované kliknutí na stejný bod self.current_clicks.append(clicked_point) self.highlight_point(clicked_point) if len(self.current_clicks) == 2: pair = frozenset(self.current_clicks) if pair not in self.lines: self.lines.add(pair) self.draw_line(pair) self.update_lines_text() self.unhighlight_points() self.current_clicks = [] self.analysis_text.delete(1.0, tk.END) # Vymazat předchozí analýzu def get_clicked_point(self, x, y): for point_num, (px, py) in self.points.items(): if math.hypot(px - x, py - y) <= 10: return point_num return None def highlight_point(self, point_num): x, y = self.points[point_num] r = 8 self.canvas.create_oval(x - r, y - r, x + r, y + r, outline="green", width=2, tags="highlight") def unhighlight_points(self): self.canvas.delete("highlight") def back(self): if not self.lines: return last_line = sorted(self.lines)[-1] self.lines.remove(frozenset(last_line)) self.redraw_canvas() self.update_lines_text() self.update_intersections() self.analysis_text.delete(1.0, tk.END) # Vymazat předchozí analýzu def clear_all(self): self.lines.clear() self.intersections.clear() self.intersection_counter = 1 self.current_clicks = [] self.lines_text.delete(1.0, tk.END) self.intersections_text.delete(1.0, tk.END) self.analysis_text.delete(1.0, tk.END) self.redraw_canvas() def redraw_canvas(self): self.canvas.delete("all") center = self.canvas_size / 2 radius = self.canvas_size * 0.4 angle_gap = -2 * math.pi / self.num_points # Směr hodinových ručiček for i in range(self.num_points): angle = -math.pi / 2 + i * angle_gap # Start ze shora x = center + radius * math.cos(angle) y = center + radius * math.sin(angle) point_num = i + 1 self.points[point_num] = (x, y) # Nakreslení bodu r = 5 self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="blue", tags=f"point{point_num}") # Očíslování bodu self.canvas.create_text(x, y - 10, text=str(point_num), tags=f"label{point_num}") # Nakreslení hlavní kružnice self.canvas.create_oval(center - radius, center - radius, center + radius, center + radius, outline="black") # Nakreslení čar for pair in self.lines: a, b = sorted(pair) x1, y1 = self.points[a] x2, y2 = self.points[b] self.canvas.create_line(x1, y1, x2, y2, fill="red", tags=f"line{a}{b}") # Nakreslení průsečíků for (x, y), num in self.intersections.items(): self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection{num}") self.canvas.create_text(x + 6, y, text=str(num), fill="purple", tags=f"intersection_text_{num}") def check_intersections(self, a, b): new_line = (self.points[a], self.points[b]) for existing_pair in self.lines: if existing_pair == frozenset([a, b]): continue c, d = sorted(existing_pair) existing_line = (self.points[c], self.points[d]) intersect_point = self.get_line_intersection(new_line, existing_line) if intersect_point: x, y = intersect_point # Kontrola, zda průsečík není na koncích čar if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): # Kontrola, zda průsečík již není zaznamenán if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 def get_line_intersection(self, line1, line2): (x1, y1), (x2, y2) = line1 (x3, y3), (x4, y4) = line2 # Výpočet jmenovatelů s operátory násobení denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if denom == 0: return None # Paralelní nebo souběžné čáry # Výpočet průsečíku Px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denom Py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denom # Kontrola, zda průsečík leží na obou úsecích if self.point_on_segment(Px, Py, line1) and self.point_on_segment(Px, Py, line2): return (Px, Py) else: return None def point_on_segment(self, x, y, segment): (x1, y1), (x2, y2) = segment return (min(x1, x2) - 1e-6 <= x <= max(x1, x2) + 1e-6) and (min(y1, y2) - 1e-6 <= y <= max(y1, y2) + 1e-6) def update_intersections(self): # Přepočet průsečíků self.intersections.clear() self.intersections_text.delete(1.0, tk.END) self.intersection_counter = 1 lines = list(self.lines) for i in range(len(lines)): for j in range(i + 1, len(lines)): pair1 = lines[i] pair2 = lines[j] a, b = sorted(pair1) c, d = sorted(pair2) if len(pair1.intersection(pair2)) > 0: continue # Čáry sdílejí společný bod intersect_point = self.get_line_intersection((self.points[a], self.points[b]), (self.points[c], self.points[d])) if intersect_point: x, y = intersect_point if not self.is_at_endpoint(x, y, [self.points[a], self.points[b], self.points[c], self.points[d]]): if (x, y) not in self.intersections: self.intersections[(x, y)] = self.intersection_counter self.intersections_text.insert(tk.END, f"{self.intersection_counter}: Čáry ({a},{b}) & ({c},{d})\n") # Nakreslení průsečíku self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="purple", tags=f"intersection_{self.intersection_counter}") self.canvas.create_text(x + 6, y, text=str(self.intersections[(x, y)]), fill="purple", tags=f"intersection_text_{self.intersection_counter}") self.intersection_counter += 1 self.redraw_canvas() def is_at_endpoint(self, x, y, points): for px, py in points: if math.isclose(px, x, abs_tol=1e-6) and math.isclose(py, y, abs_tol=1e-6): return True return False def save_images(self): if self.num_points == 0: messagebox.showerror("Chyba", "Nejprve nakreslete kružnici.") return # Zeptání se na složku pro uložení directory = filedialog.askdirectory() if not directory: return # Uložení prvního obrázku s popisky a průsečíky ps_file = os.path.join(directory, "kruznice_s_popisky.eps") self.canvas.postscript(file=ps_file, colormode='color') try: img1 = Image.open(ps_file) img1.save(os.path.join(directory, "kruznice_s_popisky.png"), "png") os.remove(ps_file) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání prvního obrázku: {e}") return # Uložení druhého obrázku bez popisků a průsečíků # Dočasné skrytí popisků a průsečíků all_items = self.canvas.find_all() for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='hidden') # Aktualizace plátna self.canvas.update() ps_file2 = os.path.join(directory, "kruznice_bez_popisku.eps") self.canvas.postscript(file=ps_file2, colormode='color') try: img2 = Image.open(ps_file2) img2.save(os.path.join(directory, "kruznice_bez_popisku.png"), "png") os.remove(ps_file2) except Exception as e: messagebox.showerror("Chyba při ukládání", f"Chyba při ukládání druhého obrázku: {e}") return # Obnovení viditelnosti popisků a průsečíků for item in all_items: tags = self.canvas.gettags(item) if any(tag.startswith("label") for tag in tags) or self.canvas.itemcget(item, "fill") == "purple": self.canvas.itemconfigure(item, state='normal') messagebox.showinfo("Hotovo", f"Obrázky byly uloženy do složky: {directory}") def analyze_geometry(self): """ Analyzuje aktuální geometrický útvar a vypíše počet bodů, úseček a ploch rozdělených na typy. """ # Sestavení všech bodů včetně průsečíků all_points = {} point_id = 1 point_map = {} # (x, y) -> point_id for p_num, coords in self.points.items(): all_points[point_id] = coords point_map[coords] = point_id point_id += 1 for coords in self.intersections.keys(): all_points[point_id] = coords point_map[coords] = point_id point_id += 1 # Sestavení grafu jako adjacency list adjacency = defaultdict(set) # Funkce pro rozdělení úseček na segmenty podle průsečíků def split_line(a, b): point_a = self.points[a] point_b = self.points[b] # Najít průsečíky na této úsečce intersections_on_line = [] for (x, y) in self.intersections.keys(): if self.point_on_segment(x, y, (point_a, point_b)): intersections_on_line.append((x, y)) # Seřadit průsečíky podle vzdálenosti od a intersections_on_line.sort(key=lambda coord: math.hypot(coord[0] - point_a[0], coord[1] - point_a[1])) # Rozdělit úsečku na segmenty segments = [] current_start = point_a for coord in intersections_on_line: segments.append((current_start, coord)) current_start = coord segments.append((current_start, point_b)) return segments # Rozdělení všech úseček na segmenty for pair in self.lines: a, b = sorted(pair) segments = split_line(a, b) for seg_start, seg_end in segments: id_start = point_map[seg_start] id_end = point_map[seg_end] if id_start != id_end: adjacency[id_start].add(id_end) adjacency[id_end].add(id_start) # Vyhledávání všech cyklů (plošek) pomocí DFS # Abychom se vyhnuli duplikacím cyklům, uchováváme navštívené hrany visited_edges = set() faces = [] def dfs(current, start, path, parent): for neighbor in adjacency[current]: edge = tuple(sorted((current, neighbor))) if edge in visited_edges: continue if neighbor == start and len(path) >= 3: faces.append(path.copy()) continue if neighbor in path: continue visited_edges.add(edge) path.append(neighbor) dfs(neighbor, start, path, current) path.pop() for vertex in all_points.keys(): dfs(vertex, vertex, [vertex], None) # Odstranění duplikovaných cyklů (reprezentovaných setem) unique_faces = [] seen = set() for face in faces: sorted_face = tuple(sorted(face)) if sorted_face not in seen: seen.add(sorted_face) unique_faces.append(face) # Kategorizace ploch podle počtu stran face_counts = defaultdict(int) for face in unique_faces: face_counts[len(face)] += 1 # Výpočet počtu ploch pomocí Eulerovy formule (pro kontrolu) V = len(all_points) E = 0 for adj in adjacency.values(): E += len(adj) E = E // 2 # každá hrana je spočítána dvakrát F_euler = E - V + 2 # Vyplnění výsledků do textového pole self.analysis_text.delete(1.0, tk.END) self.analysis_text.insert(tk.END, f"Počet Bodů (V): {V}\n") self.analysis_text.insert(tk.END, f"Počet Úseček (E): {E}\n") self.analysis_text.insert(tk.END, f"Počet Ploch (F): {len(unique_faces)} (Euler: {F_euler})\n\n") self.analysis_text.insert(tk.END, "Plochy podle počtu stran:\n") for sides in sorted(face_counts.keys()): if sides < 3: continue # Ignorovat plochy s méně než 3 stranami self.analysis_text.insert(tk.END, f"{sides}-úhelníky: {face_counts[sides]}\n") # ... (zbytek metod zůstává beze změn) if __name__ == "__main__": root = tk.Tk() app = CircleDrawer(root) root.mainloop()Podrobné vysvětlení úprav:
-
Přidání tlačítka "Analyzovat" a textového pole pro analýzu:
- V
create_widgetsmetodě jsme přidali nové tlačítkoself.analyze_button, které při stisknutí zavolá metoduanalyze_geometry. - Přidali jsme také nové textové pole
self.analysis_text, kde se budou zobrazovat výsledky analýzy.
- V
-
Implementace funkce
analyze_geometry:- Sestavení všech bodů: Kombinujeme původní body a průsečíky do jedné sady bodů.
- Sestavení grafu: Použijeme studené segmentace úseček, abychom správně zohlednili průsečíky jako nové vrcholy grafeu.
- Vyhledávání cyklů (plošek): Pomocí depth-first search (DFS) procházíme graf a hledáme všechny možné cykly, které představují plochy.
- Kategorizace ploch: Počet stran každé plochy je použit k jejich kategorizaci (trojúhelníky, čtyřúhelníky atd.).
- Eulerova formule: Pro kontrolu jsme vypočítali počet ploch podle Eulerovy formule ( F = E - V + 2 ), kde ( V ) je počet vrcholů, ( E ) počet úseček a ( F ) počet ploch.
-
Upravili jsme další metody pro zajištění správného fungování analýzy:
draw_lines_from_input,canvas_click,back, aclear_allnyní také vymažou předchozí analýzu, pokud dojde ke změně geometrie.
Poznámky a omezení:
-
Vyhledávání cyklů: Implementace v této funkci je jednoduchá a nemusí být plně optimalizovaná nebo bezchybně detekovat všechny plochy v komplexních grafech. Pro složitější grafy by bylo vhodné použít specializované knihovny jako
networkxa její funkce pro planární grafy. -
Eulerova formule: Eulerova formulace poskytuje kontrolu konzistence výsledků, ale skutečný počet ploch může záviset na konkrétním uspořádání úseček.
-
Omezení na jednoduchá mnohoúhelníky: Analýza počtu stran ploch nezohledňuje případné konkávní nebo složité plochy, které mohou mít opakující se hrany nebo chybějící části.
Tento skript by měl splňovat vaše základní požadavky na analýzu nakresleného geometrického útvaru. Pro pokročilejší analýzu a přesnější detekci ploch doporučuji integraci s grafovými knihovnami, které poskytují robustní nástroje pro manipulaci s planárními grafy.
-