vloz do skriptu funkci, která po stisknuti tlačítka Analyzovat, bude presne analyzovat, nechci zadne metody, ktere jen odhaduji, narysovany geometricky utvar na presny 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, které se vytvori na leve strane.
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")
code
Assistant
# 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()
Zde je upravený skript s přidanou funkcí "Analyzovat", která přesně analyzuje nakreslený geometrický útvar, spočítá počet bodů, úseček a ploch, které vznikly zakreslením úseček. Plochy jsou pak rozděleny na trojúhelníky, čtyřúhelníky atd. Výsledky jsou zobrazeny v novém textovém poli na levé straně.
python
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 = []
# Přidané proměnné pro analýzu
self.vertex_id_to_coords = {}
self.coords_to_vertex_id = {}
self.segments = []
self.faces = []
self.face_counts = {}
# 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_figure)
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 = 500 # 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.RIGHT, padx=10)
self.canvas.bind("<Button-1>", self.canvas_click)
# Levý rámec pro analýzu
left_frame = tk.Frame(main_frame)
left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10)
# Textové pole pro výsledek analýzy
tk.Label(left_frame, text="Výsledky analýzy:").pack(anchor=tk.W)
self.analysis_text = tk.Text(left_frame, width=40, height=20)
self.analysis_text.pack(pady=5)
# Seznam čar
tk.Label(left_frame, text="Čáry:").pack(anchor=tk.W, pady=(10, 0))
self.lines_text = tk.Text(left_frame, width=40, height=10)
self.lines_text.pack(pady=5)
# Seznam průsečíků
tk.Label(left_frame, text="Průsečíky:").pack(anchor=tk.W, pady=(10, 0))
self.intersections_text = tk.Text(left_frame, width=40, height=10)
self.intersections_text.pack(pady=5)
# Tlačítka
buttons_frame = tk.Frame(left_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*' # 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.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
rounded_point = (round(x, 6), round(y, 6))
if rounded_point not in self.intersections:
self.intersections[rounded_point] = 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[rounded_point]), 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]]):
rounded_point = (round(x, 6), round(y, 6))
if rounded_point not in self.intersections:
self.intersections[rounded_point] = 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[rounded_point]), 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}")
# Přidaná funkce pro analýzu
def analyze_figure(self):
if self.num_points == 0 or not self.lines:
messagebox.showerror("Chyba", "Nejprve nakreslete kružnici a čáry.")
return
self.analysis_text.delete(1.0, tk.END)
# Krok 1: Shromáždění všech vrcholů
self.vertex_id_to_coords = {}
self.coords_to_vertex_id = {}
vertex_counter = 1
# Přidání původních bodů
for point_id, coords in self.points.items():
self.vertex_id_to_coords[point_id] = coords
rounded_coords = (round(coords[0], 6), round(coords[1], 6))
self.coords_to_vertex_id[rounded_coords] = point_id
vertex_counter = max(vertex_counter, point_id + 1)
# Přidání průsečíků
for coords, intersection_id in self.intersections.items():
self.vertex_id_to_coords[vertex_counter] = coords
self.coords_to_vertex_id[coords] = vertex_counter
vertex_counter += 1
total_vertices = len(self.vertex_id_to_coords)
# Krok 2: Vytvoření hran (rozdělení původních čar na segmenty v průsečících)
self.segments = []
for line_pair in self.lines:
a, b = sorted(line_pair)
start_point = self.points[a]
end_point = self.points[b]
points_on_line = [start_point]
for coords in self.intersections.keys():
if self.is_point_on_line(coords, start_point, end_point):
points_on_line.append(coords)
points_on_line.append(end_point)
# Seřazení bodů na čáře
points_on_line = list(set(points_on_line))
points_on_line.sort(key=lambda point: self.distance_along_line(point, start_point, end_point))
# Vytvoření segmentů mezi body
for i in range(len(points_on_line) - 1):
p1 = points_on_line[i]
p2 = points_on_line[i + 1]
id1 = self.coords_to_vertex_id[(round(p1[0],6), round(p1[1],6))]
id2 = self.coords_to_vertex_id[(round(p2[0],6), round(p2[1],6))]
self.segments.append((id1, id2))
total_edges = len(self.segments)
# Krok 3: Vytvoření seznamu sousedů pro každý vrchol
adjacency = {}
for vertex_id in self.vertex_id_to_coords.keys():
adjacency[vertex_id] = []
for edge in self.segments:
a, b = edge
adjacency[a].append(b)
adjacency[b].append(a)
# Krok 4: Seřazení sousedů proti směru hodinových ručiček
ordered_adjacency = {}
for vertex_id, neighbors in adjacency.items():
origin = self.vertex_id_to_coords[vertex_id]
def angle(n_id):
dest = self.vertex_id_to_coords[n_id]
return math.atan2(dest[1] - origin[1], dest[0] - origin[0])
ordered_neighbors = sorted(neighbors, key=angle, reverse=True)
ordered_adjacency[vertex_id] = ordered_neighbors
# Krok 5: Procházení stěn
self.faces = []
visited_half_edges = set()
for v_id in self.vertex_id_to_coords.keys():
for n_id in ordered_adjacency[v_id]:
half_edge = (v_id, n_id)
if half_edge in visited_half_edges:
continue
face = []
current_half_edge = half_edge
while True:
visited_half_edges.add(current_half_edge)
face.append(current_half_edge)
tail = current_half_edge[1]
neighbors = ordered_adjacency[tail]
index = neighbors.index(current_half_edge[0])
next_neighbor = neighbors[(index - 1) % len(neighbors)]
current_half_edge = (tail, next_neighbor)
if current_half_edge == half_edge:
break
self.faces.append(face)
# Krok 6: Klasifikace stěn
self.face_counts = {}
for face in self.faces:
edge_count = len(face)
if edge_count not in self.face_counts:
self.face_counts[edge_count] = 0
self.face_counts[edge_count] += 1
# Odstranění vnější stěny (pokud existuje)
self.face_counts[max(self.face_counts.keys())] -= 1
# Krok 7: Výpis výsledků
self.analysis_text.insert(tk.END, f"Počet bodů: {total_vertices}\n")
self.analysis_text.insert(tk.END, f"Počet úseček: {total_edges}\n")
total_faces = sum(self.face_counts.values())
self.analysis_text.insert(tk.END, f"Počet ploch: {total_faces}\n")
for edge_count in sorted(self.face_counts.keys()):
count = self.face_counts[edge_count]
if count > 0:
if edge_count == 3:
shape = "Trojúhelníky"
elif edge_count == 4:
shape = "Čtyřúhelníky"
elif edge_count == 5:
shape = "Pětiúhelníky"
elif edge_count == 6:
shape = "Šestiúhelníky"
else:
shape = f"{edge_count}-úhelníky"
self.analysis_text.insert(tk.END, f"{shape}: {count}\n")
def is_point_on_line(self, point, line_start, line_end):
x0, y0 = point
x1, y1 = line_start
x2, y2 = line_end
# Zkontrolujeme, zda je bod na přímce definované dvěma body a mezi nimi
cross = abs((x2 - x1)*(y0 - y1) - (x0 - x1)*(y2 - y1))
if cross > 1e-6:
return False
dotprod = (x0 - x1)*(x2 - x1) + (y0 - y1)*(y2 - y1)
if dotprod < 0:
return False
squaredlengthba = (x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)
if dotprod > squaredlengthba:
return False
return True
def distance_along_line(self, point, line_start, line_end):
x0, y0 = point
x1, y1 = line_start
return math.hypot(x0 - x1, y0 - y1)
if __name__ == "__main__":
root = tk.Tk()
app = CircleDrawer(root)
root.mainloop()
Poznámky k aktualizovanému skriptu:
Přidáno tlačítko "Analyzovat" v GUI, které volá funkci analyze_figure.
Přidáno textové pole analysis_text na levé straně pro zobrazení výsledků analýzy.
Funkce analyze_figure provádí následující:
Shromáždí všechny vrcholy (původní body a průsečíky) a přiřadí jim unikátní ID.
Rozdělí původní čáry na segmenty v průsečících.
Vytvoří seznam sousedů pro každý vrchol a seřadí je proti směru hodinových ručiček.
Pomocí algoritmu pro procházení stěn nalezne všechny plochy.
Klasifikuje plochy podle počtu hran (trojúhelníky, čtyřúhelníky atd.).
Zobrazí výsledky v textovém poli.
Tento skript přesně analyzuje nakreslený geometrický útvar a poskytuje požadované informace.