ich habe am bwinf 2. Runde teilgenommen und mich interessiert einfach nur, was ihr zu meinen Lösungen sagt. Wer mal ein wenig Zeit hat, kann ja einfach mal etwas schreiben.
thx
mfg
cime
hier noch ein Link zu den Aufgaben
PS: Ich fände es auch interessant zu wissen, ob hier noch jemand daran teilgenommen hat.
Aufgabe 1:
Code: Alles auswählen
# -*- coding: cp1252 -*-
#losgehts.pyw
import wx,re,os,sys,math
wildcard = "Text Files (*.txt)|*.txt|"\
"All files (*.*)|*.*"
NULL=10**-10
NULLV=10**-8
NULLA=10**-2
DEUTSCH={
"title":"Museumsanzeige",
'file':'Datei',
'new':'Neu',
'new status bar':'Aufrufen eines neuen Museums',
'exit':'Beenden',
'exit status bar':'Beendet das Programm',
'edit':'Bearbeiten',
'config':'Einstellungen',
'config status bar':'Konfigurieren des Programms',
'open':'Öffnen',
'open status bar':'Öffnen einer Datei',
'load file':'Wählen Sie bitte eine Datei aus ...',
'invalid file':'Die Datei %s ist keine korrekte Museumsform! Wollen Sie sie bearbeiten?',
'invalid file title':'Fehler beim Einlesen der Datei',
'zoom-':'Verkleinern',
'zoom- status bar':'Verkleinern des Anzeigefeldes',
'zoom+':'Vergrößern',
'zoom+ status bar':'Vergrößern des Anzeigefeldes',
'show zoom status':'Zoom: %0.3f',
'view':'Ansicht',
'quest exit':'Wollen Sie wirklich beenden?',
'exit title':'Beenden ...',
'error no way':'Sie müssen erst einen Weg festlegen, bevor die Sicht angezeigt werden kann.',
'no way title':'Kein Weg gewählt!',
'standard':'Standard',
'standard status bar':'Stellt die Standardansicht wieder her',
'clear':'Löschen',
'clear status bar':'Löschen der momentanen Ansicht',
'none':'Keiner',
'tour':'Rundweg',
'tour status bar':'den Rundweg festlegen',
'show tour': 'Sicht Anzeigen',
'show tour status bar':'Anzeigen des gesamten Sichtfeldes des Wächters',
'poly read error title':'fehlerhaftes Polygon',
'poly read error':'Das Polygon %s schneidet sich selbst. Daher wird es nicht weiter mitbearbeit.'
}
COLOR={
'frame':'black',
'bg':'white',
'way':'red',
'light':'yellow'
}
end_of_polygon='End of Polygon'
invalid_file='Invalid file found'
class app(wx.App):
def OnInit(self):
frame = myframe(None,DEUTSCH)
self.SetTopWindow(frame)
frame.Show(True)
return True
class choice_way(wx.Dialog):
def __init__(self,parent,id,dic,num,*names):
pre = wx.PreDialog()
pre.SetExtraStyle(wx.DIALOG_EX_CONTEXTHELP)
pre.Create(parent, id, dic['tour'], wx.DefaultPosition, wx.DefaultSize, wx.DEFAULT_DIALOG_STYLE)
self.PostCreate(pre)
sizer = wx.BoxSizer(wx.VERTICAL)
self.lb = wx.ListBox(self, 60, (80, 50), (200, 120), (dic['none'],)+names, wx.LB_SINGLE)
self.lb.Select(num+1)#because none is -1, but here 0
self.Bind(wx.EVT_LISTBOX_DCLICK, self.end, self.lb)
sizer.Add(self.lb, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
btn = wx.Button(self, wx.ID_OK)
btn.SetDefault()
sizer.Add(btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
def end(self,event=None):
self.Destroy()
class myframe(wx.Frame):
def __init__(self,parent,dic):
self.nr_poly=0
self.zfactor=1.3
self.mouse_pos=()
size=wx.GetDisplaySize()
size=(size[0]-60,size[1]-60)
pos=(20,20)
self.dic=dic
wx.Frame.__init__(self,parent,-1,dic['title'],pos,size)
self.wnd=draw_window(self,-1,dic)
menu=wx.Menu()
menu.Append(1001,dic['new'],dic['new status bar'])
menu.Append(1004,dic['open'],dic['open status bar'])
menu.Append(1009,dic['clear'],dic['clear status bar'])
menu.AppendSeparator()
menu.Append(1002,dic['exit'],dic['exit status bar'])
self.menubar=wx.MenuBar()
self.menubar.Append(menu,dic['file'])
menu=wx.Menu()
menu.Append(1003,dic['config'],dic['config status bar'])
menu.Append(1010,dic['show tour'],dic['show tour status bar'])
self.menubar.Append(menu,dic['edit'])
menu=wx.Menu()
menu.Append(1005,dic['zoom+'],dic['zoom+ status bar'])
menu.Append(1006,dic['zoom-'],dic['zoom- status bar'])
menu.Append(1007,dic['standard'],dic['standard status bar'])
menu.Append(1008,dic['tour'],dic['tour status bar'])
self.menubar.Append(menu,dic['view'])
self.SetMenuBar(self.menubar)
self.status=self.CreateStatusBar(2)
self.SetStatusText(self.dic['show zoom status']%self.wnd.zoom,1)
self.tools = self.CreateToolBar( wx.TB_HORIZONTAL
| wx.NO_BORDER
| wx.TB_FLAT
| wx.TB_TEXT
| wx.TB_3DBUTTONS
)
tsize = (-1,-1)
exit_bmp = wx.ArtProvider.GetBitmap(wx.ART_QUIT, wx.ART_TOOLBAR, tsize)
new_bmp = wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, tsize)
open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, tsize)
zplus_bmp = wx.Image('images/zplus.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
zminus_bmp = wx.Image('images/zminus.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
standard_bmp = wx.Image('images/standard.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
self.tools.AddSimpleTool(1002, exit_bmp, dic['exit'], dic['exit status bar'])
self.tools.AddSimpleTool(1001, new_bmp, dic['new'], dic['new status bar'])
self.tools.AddSimpleTool(1004, open_bmp, dic['open'], dic['open status bar'])
self.tools.AddSimpleTool(1005, zplus_bmp, dic['zoom+'], dic['zoom+ status bar'])
self.tools.AddSimpleTool(1006, zminus_bmp, dic['zoom-'], dic['zoom- status bar'])
self.tools.AddSimpleTool(1007, standard_bmp, dic['standard'], dic['standard status bar'])
self.Bind(wx.EVT_TOOL, self.new, id=1001)
self.Bind(wx.EVT_TOOL, self.open, id=1004)
self.Bind(wx.EVT_TOOL, self.zoomplus, id=1005)
self.Bind(wx.EVT_TOOL, self.zoomminus, id=1006)
self.Bind(wx.EVT_TOOL, self.resetwnd, id=1007)
self.Bind(wx.EVT_TOOL, self.on_end, id=1002)
self.Bind(wx.EVT_MENU, self.new, id=1001)
self.Bind(wx.EVT_MENU, self.open, id=1004)
self.Bind(wx.EVT_MENU, self.zoomplus, id=1005)
self.Bind(wx.EVT_MENU, self.zoomminus, id=1006)
self.Bind(wx.EVT_MENU, self.resetwnd, id=1007)
self.Bind(wx.EVT_MENU, self.on_end, id=1002)
self.Bind(wx.EVT_MENU, self.choose_way, id=1008)
self.Bind(wx.EVT_MENU, self.wnd.clean, id=1009)
self.Bind(wx.EVT_MENU, self.show_sight, id=1010)
self.Bind(wx.EVT_CLOSE, self.on_end)
self.wnd.Bind(wx.EVT_MOTION, self.motion)
self.tools.Realize()
def show_sight(self,event=None):
self.wnd.show_sight()
def choose_way(self,event=None):
dlg = choice_way(self,1000,self.dic,self.wnd.way,*[poly.name for poly in self.wnd.group])
dlg.CenterOnScreen()
dlg.ShowModal()
self.wnd.way=dlg.lb.GetSelection()-1
dlg.Destroy()
if self.wnd.sight:
self.wnd.sight=[]
self.wnd.dc.Clear()
self.wnd.on_paint()
def resetwnd(self,event=None):
self.wnd.zoom=1.0
self.wnd.movedx=0
self.wnd.movedy=0
self.wnd.dc.Clear()
self.wnd.on_paint()
def motion(self,event):
if event.Dragging() and self.wnd.group:
if self.mouse_pos:
new_mouse_pos=event.GetPosition()
self.wnd.movedx+=new_mouse_pos[0]-self.mouse_pos[0]
self.wnd.movedy+=new_mouse_pos[1]-self.mouse_pos[1]
self.wnd.dc.Clear()
self.wnd.on_paint()
self.mouse_pos=new_mouse_pos
else:
self.mouse_pos=event.GetPosition()
elif self.mouse_pos:
self.mouse_pos=()
def on_end(self,event=None):
dlg = wx.MessageDialog(self, self.dic['quest exit'],
self.dic['exit title'], wx.YES_NO | wx.ICON_QUESTION
| wx.NO_DEFAULT)
ret = dlg.ShowModal()
dlg.Destroy()
if ret == wx.ID_NO:
if event is None:
event.Skip()
else:
self.Destroy()
def zoomplus(self,event=None):
p = self.wnd.get_mid_p()
self.wnd.zoom*=self.zfactor
self.wnd.set_mid_to_point(*p)
self.wnd.dc.Clear()
self.wnd.on_paint()
self.SetStatusText(self.dic['show zoom status']%self.wnd.zoom,1)
def zoomminus(self,event=None):
p = self.wnd.get_mid_p()
if self.wnd.zoom/self.zfactor>1.01:
self.wnd.zoom/=self.zfactor
else:
self.wnd.zoom=1.0
self.wnd.set_mid_to_point(*p)
self.wnd.dc.Clear()
self.wnd.on_paint()
self.SetStatusText(self.dic['show zoom status']%self.wnd.zoom,1)
def new(self,event=None):
self.wnd.clean()
self.open()
def open(self,even=None):
self.wnd.dc.Clear()
path=os.path.join(os.getcwd(),'Meine Museen')
if not os.path.exists(path):
path=os.getcwd()
dlg= wx.FileDialog(
self, message=self.dic['load file'], defaultDir=path,
defaultFile="", wildcard=wildcard, style=wx.OPEN | wx.CHANGE_DIR | wx.MULTIPLE
)
ret=dlg.ShowModal()
dlg.Destroy()
if ret== wx.ID_OK:
paths = dlg.GetPaths()
for path in paths:
self.open_file(path)
self.wnd.dc.Clear()
self.wnd.on_paint()
def open_file(self,file):
try:
for i in create_polygon_from_file(file):
self.wnd.add_poly(i)
except invalid_file,text:
msg = wx.MessageDialog(self, self.dic['invalid file']%file,
self.dic['invalid file title'],
wx.YES_NO | wx.ICON_ERROR
)
if msg.ShowModal()==wx.ID_YES:
path=os.path.join(os.path.split(sys.argv[0])[0],'Editor.pyw')
os.spawnv(os.P_NOWAIT,sys.executable,[sys.executable,path,file])
msg.Destroy()
else:
if self.wnd.sight:
self.wnd.sight=[]
self.wnd.dc.Clear()
self.wnd.on_paint()
class draw_window(wx.Window):
def __init__(self,parent,id,dic, pos=wx.DefaultPosition, size=wx.DefaultSize):
wx.Window.__init__(self, parent, id, pos, size)
wx.FileDialog(self).Show()
self.dic=dic
self.mult=0.0
self.size=None
self.color=COLOR
self.sight=[]
self.group=[]
self.frame=10
self.xmax=1
self.ymax=1
self.zoom=1.0
self.movedx=0
self.movedy=0
self.way=-1
self.SetBackgroundColour(wx.NamedColour(self.color['bg']))
self.dc = wx.ClientDC(self)
self.SetFocus()
self.Bind(wx.EVT_PAINT, self.on_paint)
self.Bind(wx.EVT_SIZE, self.on_size)
def show_sight(self):
if self.way==-1:# no way chosen
dlg = wx.MessageDialog(self, self.dic['error no way'],
self.dic['no way title'], wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
self.GetParent().choose_way()
return
self._buffer_sight={}
self._show_sight()
self._complete_sight()
#self.write_buffer_sight_to_add_poly()
self.dc.Clear()
self.on_paint()
def write_buffer_sight_to_add_poly(self):
if not self._buffer_sight:
return
for list in self._buffer_sight.values():
if not list:
continue
for poly in list:
self.add_poly(poly,light=True)
self._buffer_sight={}
def _complete_sight(self):
while self._buffer_sight:
buffer=self._buffer_sight.copy()
self.write_buffer_sight_to_add_poly()
keys=buffer.keys()
len_keys=len(keys)
if len_keys<=1:
return
triangles=[]
for i in range(len_keys):# only index, because I also have to take the next
p1=keys[i]
if i+1==len_keys:
p2=keys[0]
else:
p2=keys[i+1]
#npx: new point nr x
for el1 in buffer[p1]:
for el2 in buffer[p2]:
np1=self.get_cut2((p1,el1.points[1]),(p2,el2.points[1]))
np2=self.get_cut2((p1,el1.points[2]),(p2,el2.points[1]))
np3=self.get_cut2((p1,el1.points[1]),(p2,el2.points[2]))
np4=self.get_cut2((p1,el1.points[2]),(p2,el2.points[2]))
if not (np1 and np2 and np3 and np4):
continue
sorted=self.sort_by_height(p1,p2, np1,np2,np3,np4)
p_on_poly=[]
for poly in self.group:
if self.group[self.way]==poly:
continue
for p in poly.points:
if self.same(sorted[1],p):
p_on_poly.append(sorted[1])
elif self.same(sorted[2],p):
p_on_poly.append(sorted[2])
if len(p_on_poly)==2:
break
if not p_on_poly:
continue
for point in p_on_poly:
m1,n1=self.get_function(p1,point)
m2,n2=self.get_function(p2,point)
for poly in self.group:
if poly==self.group[self.way]:
continue
len_poly=len(poly.points)
for i in range(len_poly):
if not self.both_p_on_one_side(p2,poly.points[i],[m1,n1],ret_if_on_line=True,given_points=False) and not self.both_p_on_one_side(p1,poly.points[i],[m2,n2],ret_if_on_line=True,given_points=False):
if i==len_poly-1:
x1=0
else:
x1=i+1
if i==0:
x2=len_poly-1
else:
x2=i-1
if (self.same(point,poly.points[i]) or
self.same(point,poly.points[x1]) or
self.same(point,poly.points[x2])):
continue
m3,n3=self.get_function(point,p1)
if point[0]>p1:
testp1=[point[0]-NULLA,m3*(point[0]-NULLA)+n3]
elif point[0]<p1:
testp1=[point[0]+NULLA,m3*(point[0]+NULLA)+n3]
m3,n3=self.get_function(point,p2)
if point[0]>p2:
testp2=[point[0]-NULLA,m3*(point[0]-NULLA)+n3]
elif point[0]<p2:
testp2=[point[0]+NULLA,m3*(point[0]+NULLA)+n3]
if ((self.check(testp1,poly.points[i],poly.points[x1],moeglich=True) or
self.check(testp2,poly.points[i],poly.points[x1],moeglich=True))
and not self.isintriangles(point,poly.points[i],poly.points[x1],triangles)):
if not self.both_p_on_one_side(p2,poly.points[x1],[m1,n1],ret_if_on_line=False,given_points=False) and not self.both_p_on_one_side(p1,poly.points[x1],[m2,n2],ret_if_on_line=False,given_points=False):
triangles.append((point,poly.points[i],poly.points[x1],poly.points[i],poly.points[x1]))
else:
m3,n3=self.get_function(poly.points[i],poly.points[x1])
xs1=(n3-n1)/(m1-m3)
xs2=(n3-n2)/(m2-m3)
if not (poly.points[i][0]-NULLV<xs1<poly.points[x1][0]+NULLV or poly.points[x1][0]-NULLV<xs1<poly.points[i][0]+NULLV):
cut1=None
else:
cut1=(xs1,m3*xs1+n3)
if not (poly.points[i][0]-NULLV<xs2<poly.points[x1][0]+NULLV or poly.points[x1][0]-NULLV<xs2<poly.points[i][0]+NULLV):
cut2=None
else:
cut2=(xs2,m3*xs2+n3)
if cut1 and not cut2:
triangles.append((point,poly.points[i],cut1,poly.points[i],poly.points[x1]))
elif cut2 and not cut1:
triangles.append((point,poly.points[i],cut2,poly.points[i],poly.points[x1]))
if ((self.check(testp1,poly.points[x2],poly.points[i],moeglich=True) or
self.check(testp2,poly.points[x2],poly.points[i],moeglich=True))
and self.isintriangles(point,poly.points[x2],poly.points[i],triangles)):
if not self.both_p_on_one_side(p2,poly.points[x2],[m1,n1],ret_if_on_line=False,given_points=False) and not self.both_p_on_one_side(p1,poly.points[x2],[m2,n2],ret_if_on_line=False,given_points=False):
triangles.append((point,poly.points[x2],poly.points[i],poly.points[x2],poly.points[i]))
else:
m3,n3=self.get_function(poly.points[i],poly.points[x2])
xs1=(n3-n1)/(m1-m3)
xs2=(n3-n2)/(m2-m3)
if not (poly.points[i][0]-NULLV<xs1<poly.points[x2][0]+NULLV or poly.points[x2][0]-NULLV<xs1<poly.points[i][0]+NULLV):
cut1=None
else:
cut1=(xs1,m3*xs1+n3)
if not (poly.points[i][0]-NULLV<xs2<poly.points[x2][0]+NULLV or poly.points[x2][0]-NULLV<xs2<poly.points[i][0]+NULLV):
cut2=None
else:
cut2=(xs2,m3*xs2+n3)
if cut1 and not cut2:
triangles.append((point,cut1,poly.points[i],poly.points[i],poly.points[x1]))
elif cut2 and not cut1:
triangles.append((point,cut2,poly.points[i],poly.points[i],poly.points[x1]))
for p1,p2,p3,old1,old2 in triangles:
self.check(p1,p2,p3,oldies=(old1,old2))
def isintriangles(self,p1,p2,p3,triangles):
new=[el[0:3] for el in triangles]
return ((p1,p2,p3) in new) or ((p1,p3,p2) in new)
def both_p_on_one_side(self,p1,p2,line,ret_if_on_line=False,given_points=True):
if given_points:
m,n=self.get_function(*line)
else:
m,n=line
if m*p1[0]+n>p1[1]:
return m*p2[0]+n>p2[1]
elif m*p1[0]+n<p1[1]:
return m*p2[0]+n<p2[1]
return ret_if_on_line # p1 is on the line
def sort_by_height(self,p1,p2,*np):#np: list for sorting; in difference to line: p1,p2
new=[]
np=[[p,self.get_height(p,p1,p2)] for p in np]
while np:
max=(0,0)
for i in range(len(np)):
if np[i][1]>max[1]:
max=(i,np[i][1])
new.append(list(np[max[0]][0]))
del np[max[0]]
return new
def get_height(self,p1,p2,p3):
m1,n1=self.get_function(p2,p3)
if m1==0:
m2=-1/NULL
else:
m2=-1/m1
n2=p1[1]-m2*p1[0]
xs=(n1-n2)/(m2-m1) #xs--> x which will be returned
ys=m1*xs+n1
return ((xs-p1[0])**2+(ys-p1[1])**2)**(1/2.0)#Satz des Pythagoras nach c umgestellt
def _show_sight(self):
for p in self.group[self.way]:#p--> point#############
for i in range(len(self.group)):#i-->index in group to polygon
if i==self.way:
continue # i think the guardian can look over his way
for j in range(len(self.group[i][0:-1])):#j-->index in polygon to point,-1 because the last is used after
self.check(p,self.group[i][j],self.group[i][j+1])
self.check(p,self.group[i][-1],self.group[i][0])
def same(self,p1,p2):
return (abs(p1[0]-p2[0])<NULLV) and (abs(p1[1]-p2[1])<NULLV)
def check(self,p1,p2,p3,oldies=None,moeglich=False):#oldies-->old points if existing (used for the recursion)
rest=range(len(self.group))
rest.remove(self.way)
if oldies:
oldp2=oldies[0]
oldp3=oldies[1]
else:
oldp2=p2
oldp3=p3
for i in rest:# i--> index
len_grp=len(self.group[i])
for j in range(len_grp):
if j+1==len_grp:
v=0# only used, because the last point has also a connection to the first one
else:
v=j+1
if ((self.same(oldp2,self.group[i][j]) and self.same(oldp3,self.group[i][v])) or
(self.same(oldp2,self.group[i][v]) and self.same(oldp3,self.group[i][j])) or
(self.same(p1,self.group[i][v]) or self.same(p1,self.group[i][j]))):
continue
ins1=self.is_inside(p1,p2,p3,self.group[i][j])
ins2=self.is_inside(p1,p2,p3,self.group[i][v])
if ins1 and ins2:
np1=self.get_cut1((p1,self.group[i][j]),(p2,p3))
np2=self.get_cut1((p1,self.group[i][v]),(p2,p3))
if abs(self.get_function(p1,p2)[0]-self.get_function(p1,np1)[0])<abs(self.get_function(p1,p2)[0]-self.get_function(p1,np2)[0]):
ret1=self.check(p1,p2,np1,oldies=(oldp2,oldp3),moeglich=moeglich)
ret2=self.check(p1,p3,np2,oldies=(oldp2,oldp3),moeglich=moeglich)
if moeglich:
return ret1 or ret2
else:
ret1=self.check(p1,p2,np2,oldies=(oldp2,oldp3),moeglich=moeglich)
ret2=self.check(p1,p3,np1,oldies=(oldp2,oldp3),moeglich=moeglich)
if moeglich:
return ret1 or ret2
return
elif ins1:
if self.same(p2,self.group[i][v]):
p2=self.get_cut1((p1,self.group[i][j]),(p2,p3))
elif self.same(p3,self.group[i][v]):
p3=self.get_cut1((p1,self.group[i][j]),(p2,p3))
if self.both_p_on_one_side(self.group[i][j],self.group[i][v],(p1,p2)):
p3=self.get_cut1((p1,self.group[i][j]),(p2,p3))
else:
p2=self.get_cut1((p1,self.group[i][j]),(p2,p3))
elif ins2:
if self.same(p2,self.group[i][j]):
p2=self.get_cut1((p1,self.group[i][v]),(p2,p3))
elif self.same(p3,self.group[i][j]):
p3=self.get_cut1((p1,self.group[i][v]),(p2,p3))
if self.both_p_on_one_side(self.group[i][j],self.group[i][v],(p1,p2)):
p3=self.get_cut1((p1,self.group[i][v]),(p2,p3))
else:
p2=self.get_cut1((p1,self.group[i][v]),(p2,p3))
else:
cut1=self.get_cut2((p1,p2),(self.group[i][j],self.group[i][v]))
cut2=self.get_cut2((p1,p3),(self.group[i][j],self.group[i][v]))
if cut1 and cut2:
return
if moeglich:
return True
poly=polygon('show')
poly.points=[p1,p2,p3]
if tuple(p1) in self._buffer_sight.keys():
self._buffer_sight[tuple(p1)].append(poly)
else:
self._buffer_sight[tuple(p1)]=[poly]
def get_cut2(self,linea,lineb):#inside
(xa1,ya1),(xa2,ya2)=linea
(xb1,yb1),(xb2,yb2)=lineb
ma,na=self.get_function(*linea)
mb,nb=self.get_function(*lineb)
if mb-ma==0:
return None # because linea and lineb are parallel
xs=(na-nb)/(mb-ma) #xs--> x which will be returned
ys=ma*xs+na
if (xa1-NULLV<xs<xa2+NULLV or xa2-NULLV<xs<xa1+NULLV) and (xb1-NULLV<xs<xb2+NULLV or xb2-NULLV<xs<xb1+NULLV):
return xs,ys
return None # not in defined
def get_cut1(self,linea,lineb,a_as_function=False):#outside
(xa1,ya1),(xa2,ya2)=linea
(xb1,yb1),(xb2,yb2)=lineb
ma,na=self.get_function(*linea)
mb,nb=self.get_function(*lineb)
if mb-ma==0:
return None # because linea and lineb are parallel
xs=(na-nb)/(mb-ma) #xs--> x which will be returned
ys=ma*xs+na
if (xa1-NULLV<=xs>=xa2-NULLV or xa2+NULLV>=xs<=xa1+NULLV) and (xb1-NULLV<=xs<=xb2+NULLV or xb2-NULLV<=xs<=xb1+NULLV):
return xs,ys
return None # not in defined
def get_function(self,p1,p2):
(x1,y1),(x2,y2)=p1,p2
if x1-x2==0:
m=(y1-y2)/NULL
else:
m=(y1-y2)/(x1-x2)
n=y1-m*x1
return m,n
def is_inside(self,p1,p2,p3,p4):#p4 in p1,p2,p3
#only directly inside is meant, so if the point is on the line, it will be accepted as not inside
ma,na=self.get_function(p1,p2)
mb,nb=self.get_function(p1,p3)
mc,nc=self.get_function(p2,p3)
if mb-ma==0 or ma-mc==0 or mb-mc==0:
return None # because line a and line b are parallel
var=True
if ma*p3[0]+na>p3[1]:
var= var and (ma*p4[0]+na>p4[1]+NULL)
elif ma*p3[0]+na<p3[1]:
var= var and (ma*p4[0]+na<p4[1]-NULL)
else:
return False #because p4 is on the line
if mb*p2[0]+nb>p2[1]:
var= var and (mb*p4[0]+nb>p4[1]+NULL)
elif mb*p2[0]+nb<p2[1]:
var= var and (mb*p4[0]+nb<p4[1]-NULL)
else:
return False #because p4 is on the line
if mc*p1[0]+nc>p1[1]:
var= var and (mc*p4[0]+nc>p4[1]+NULL)
elif mc*p1[0]+nc<p1[1]:
var= var and (mc*p4[0]+nc<p4[1]-NULL)
else:
return False #because p4 is on the line
return var
def clean(self,event=None):
self.dc.Clear()
self.way=-1
self.zoom=1.0
self.movedx=0
self.movedy=0
self.group=[]
self.sight=[]
self.mult=0.0
self.xmax=1
self.ymax=1
def set_mid_to_point(self,x,y):
mx,my=self.get_mid()
x,y=self.convert1(x,y)
self.movedx-=x-mx
self.movedy-=y-my
def get_mid(self): #-->returns a size point
return [i/2 for i in self.GetSize()]
def get_mid_p(self): #-->returns a poly point
return self.convert2(*self.get_mid())
def convert1(self,x,y): #--> from poly point to size point
x=int(x*self.mult*self.zoom)+self.frame+self.movedx
y=int(-y*self.mult*self.zoom)+self.yheight-self.frame+self.movedy
return x,y
def convert2(self,x,y): #--> from size point to poly point
x=(x-self.frame-self.movedx)/(self.mult*self.zoom)
y=(-y+self.yheight+self.movedy-self.frame)/(self.mult*self.zoom)
return x,y
def add_poly(self,poly,light=False):
if not light:
len_poly=len(poly.points)
for i in range(len_poly):
if i==len_poly-1:
x1=0
else:
x1=i+1
for j in range(i,len_poly):
if j==len_poly-1:
x2=0
else:
x2=j+1
if (i==j or
i==x2 or
x1==j or
x1==x2):
continue
if self.get_cut2((poly.points[i],poly.points[x1]),
(poly.points[j],poly.points[x2])):
dlg=wx.MessageDialog(self,self.dic['poly read error']%poly.name,
self.dic['poly read error title'],
wx.OK)
dlg.CenterOnScreen()
dlg.ShowModal()
dlg.Destroy()
return
if light:
self.sight.append(poly)
else:
self.group.append(poly)
x,y=getmax(poly)
if x>self.xmax:
self.xmax=x
if y>self.ymax:
self.ymax=y
if self.mult==0:
self.mult=(self.size[0]-2*self.frame)/x
if (self.size[0]-2*self.frame)/x<(self.size[1]-2*self.frame)/y:
mult=float(self.size[0]-2*self.frame)/x
else:
mult=float(self.size[1]-2*self.frame)/y
if mult<self.mult:
self.mult=mult
def _draw_polygon(self,poly,way=False,light=False):
if way:
self.dc.SetPen(wx.Pen(wx.NamedColour(self.color['way']), 2))
elif light:
self.dc.SetPen(wx.Pen(wx.NamedColour(self.color['light']), 1))
else:
self.dc.SetPen(wx.Pen(wx.NamedColour(self.color['frame']), 2))
if light:
b = wx.Brush(wx.NamedColor(self.color['light']),wx.SOLID)#TRANSPARENT)#SOLID)
else:
b = wx.Brush(wx.BLACK,wx.TRANSPARENT)
self.dc.SetBrush(b)
self.dc.DrawPolygon([self.convert1(*point) for point in poly.points])
def on_paint(self, event=None):
self.yheight=self.size[1]
if not event is None:
old=self.dc
self.dc=wx.PaintDC(self)
for i in self.sight:
self._draw_polygon(i,light=True)
x=0 #only used for the compare with self.way
for i in self.group:
self._draw_polygon(i,way=(self.way==x))
x+=1
if not event is None:
self.dc=old
def on_size(self,event=None):
self.size=self.GetSize()
if float(self.size[0]-2*self.frame)/self.xmax<float(self.size[1]-2*self.frame)/self.ymax:
self.mult=float(self.size[0]-2*self.frame)/self.xmax
else:
self.mult=float(self.size[1]-2*self.frame)/self.ymax
self.dc.Clear()
self.on_paint()
class polygon:
def __init__(self,name):
self.name=name
self.points=[]
def __getitem__(self,x):
return self.points[x]
def __len__(self):
return len(self.points)
def __repr__(self):
txt='Polygon-Object(%s): '%self.name;
for i in self.points:
txt+='[%0.4f, %0.4f] '%tuple(i)
return txt
def __str__(self):
return self.__repr__()
def add_point(self,x,y):
self.points.append([x,y])
def getnum(self):
return len(self.points)
def create_polygon_from_file(new):
f=open(new,'r')
regex=re.compile('\d+\.\d \d+\.\d')
now=None
line=f.readline().strip()
all=[]
while line:
if not regex.match(line) is None:
if now is None:
f.close()
raise invalid_file
try:
now.add_point(*[float(i) for i in line.split(' ',1)])
except ValueError:
f.close()
raise invalid_file
else:
if not now is None and len(now.points)>2:
all.append(now)
now=polygon(line)
line=f.readline().strip()
if now is None or len(now.points)<3:
f.close()
raise invalid_file
all.append(now)
f.close()
return all
def getmax(new):
xmax=0.0
ymax=0.0
for x,y in new.points:
if x>xmax:xmax=x
if y>ymax:ymax=y
return xmax,ymax
if __name__=='__main__':
main=app()
main.MainLoop()
Code: Alles auswählen
# -*- coding: cp1252 -*-
#Editor.pyw
import wx,os,sys
wildcard = "Text-Dateien (*.txt)|*.txt|"\
"Alle Dateien (*.*)|*.*"
class app(wx.App):
def OnInit(self):
frame = myframe(None)
self.SetTopWindow(frame)
frame.Show(True)
return True
class myframe(wx.Frame):
def __init__(self,parent):
wx.Frame.__init__(self,parent,-1,'Editor',(-1,-1),(900,700))
panel=mypanel(self)
class mypanel(wx.Panel):
def __init__(self,parent):
self.parent=parent
self.document=''
self.saved=True
wx.Panel.__init__(self, parent, -1)
self.inp = wx.TextCtrl(self, -1,"",size=(890, 640), style=wx.TE_MULTILINE)
space=4
bn = wx.Button(self, -1, "Neu", (50,50))
self.Bind(wx.EVT_BUTTON, self.new, bn)
bo = wx.Button(self, -1, "Öffnen", (50,50))
self.Bind(wx.EVT_BUTTON, self.open, bo)
bs = wx.Button(self, -1, "Speichern", (50,50))
self.Bind(wx.EVT_BUTTON, self.save, bs)
bsa = wx.Button(self, -1, "Speichern unter", (50,50))
self.Bind(wx.EVT_BUTTON, self.save_as, bsa)
ba = wx.Button(self, -1, "Aktualisieren", (50,50))
self.Bind(wx.EVT_BUTTON, self.act, ba)
sizerbtn = wx.FlexGridSizer(cols=5, hgap=space, vgap=space)
sizerbtn.AddMany([bn,bo,bs,bsa,ba])
sizer = wx.FlexGridSizer(cols=1, hgap=space, vgap=space)
sizer.AddMany([ sizerbtn,self.inp])
self.SetSizer(sizer)
self.SetAutoLayout(True)
self.Bind(wx.EVT_TEXT,self.changed,self.inp)
if len(sys.argv)>=2:
self.open_file(sys.argv[1])
if len(sys.argv)>=3:
for file in sys.argv[2:]:
path=sys.argv[0]
os.spawnv(os.P_NOWAIT,sys.executable,[sys.executable,path,file])
def changed(self,event=None):
if self.saved:
self.saved=False
self.parent.SetTitle('*'+self.parent.GetTitle()+'*')
def act(self,event):
if self.document:
try:
f=open(self.document,'r')
except:
dlg = wx.MessageDialog(self,'Datei kann nicht geöffnet werden',
'MUAHAHAHAHA', wx.OK)
dlg.ShowModal()
dlg.Destroy()
else:
self.inp.Clear()
self.inp.WriteText(f.read())
f.close()
self.saved=True
self.parent.SetTitle('Editor - %s'%self.document)
else:
dlg = wx.MessageDialog(self,'Diese Datei wurde noch nicht gespeichert',
'MUAHAHAHAHA', wx.OK)
dlg.ShowModal()
dlg.Destroy()
def save(self,event=None):
if self.document:
try:
f=open(self.document,'w')
except:
dlg = wx.MessageDialog(self,'Datei kann nicht geschrieben werden',
'MUAHAHAHAHA', wx.OK)
dlg.ShowModal()
dlg.Destroy()
else:
f.write(self.inp.GetValue())
f.close()
self.parent.SetTitle('Editor - %s'%self.document)
return
self.save_as()
def save_as(self,event=None):
while True:
dlg = wx.FileDialog(
self, defaultDir=os.getcwd(),
defaultFile="", wildcard=wildcard, style=wx.SAVE | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path=dlg.GetPaths()[0]
if os.path.isfile(path):
dlg = wx.MessageDialog(self,'Es existiert schon eine solche Datei. Soll diese Überschrieben werden?',
'MUAHAHAHAHA', wx.YES_NO|wx.NO_DEFAULT)
ret==dlg.ShowModal()
dlg.Destroy()
if ret==wx.ID_NO:
continue
try:
f=open(path,'w')
except:
dlg.Destroy()
dlg = wx.MessageDialog(self,'Datei kann nicht geschrieben werden',
'MUAHAHAHAHA', wx.OK)
dlg.ShowModal()
dlg.Destroy()
continue
self.document=path
f.write(self.inp.GetValue())
f.close()
dlg.Destroy()
break
self.saved=True
if self.document:
self.parent.SetTitle('Editor - %s'%self.document)
else:
self.parent.SetTitle('Editor')
def new(self,event=None):
if not self.saved:
if self.document:
txt=u'Wollen Sie %s ohne Speichern schließen?'%self.document
else:
txt=u'Wollen Sie dieses Dokument ohne Speichern schließen?'
dlg = wx.MessageDialog(self,txt,
'MUAHAHAHAHA', wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_NO:
self.save
dlg.Destroy()
self.document=''
self.inp.Clear()
self.saved=True
self.parent.SetTitle('Editor')
def open(self,event=None):
if not self.saved:
if self.document:
txt=u'Wollen Sie %s ohne Speichern schließen?'%self.document
else:
txt=u'Wollen Sie dieses Dokument ohne Speichern schließen?'
dlg = wx.MessageDialog(self,txt,
'MUAHAHAHAHA', wx.YES_NO|wx.NO_DEFAULT)
if dlg.ShowModal()==wx.ID_NO:
self.save
dlg.Destroy()
self.document=''
self.inp.Clear()
while True:
dlg = wx.FileDialog(
self, defaultDir=os.getcwd(),
defaultFile="", wildcard=wildcard, style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
dlg.Destroy()
if not self.open_file(dlg.GetPaths()[0]):
continue
else:
dlg.Destroy()
break
def open_file(self,path):
try:
f=open(path,'r')
except:
dlg = wx.MessageDialog(self,u'Datei %s kann nicht geöffnet werden'%path,
'MUAHAHAHAHA', wx.OK)
dlg.ShowModal()
dlg.Destroy()
return False
self.document=path
self.inp.WriteText(f.read())
f.close()
self.saved=True
if self.document:
self.parent.SetTitle('Editor - %s'%self.document)
else:
self.parent.SetTitle('Editor')
return True
if __name__=='__main__':
main=app()
main.MainLoop()