diff --git a/.DS_Store b/.DS_Store index 227b3e0..18a0daf 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/Chaos Equation/chaos.py b/Chaos Equation/chaos.py new file mode 100644 index 0000000..359afc6 --- /dev/null +++ b/Chaos Equation/chaos.py @@ -0,0 +1,126 @@ +from mywindow import Window +from mycolors import * +from math import sqrt +from random import randint +import pygame + +class Chaos: + def __init__(self,window,equations,number=255,radius=1,start=0,delta=0.000001): + fx,fy=equations + self.start=start + self.window=window + self.window.name="Chaos" + self.window.size=[1440,900] + self.window.fullscreen=True + self.window.build() + self.fx=fx + self.fy=fy + self.number=number + #self.colors=[self.window.randomColor() for i in range(number)] + self.colors=[(i,0,0) for i in range(number)] + self.radius=radius + wsx,wsy=window.size + self.positions=[[wsx//2,wsy//2] for i in range(number)] + #self.points=self.generate(number,window.size) + self.delta=delta + + def old_generate(self,number,size): + sx,sy=size + #return [[randint(0,sx-1),randint(0,sy-1),self.window.randomColor()] for i in range(number)] + return [[0,0,self.window.randomColor()] for i in range(number)] + + def old1_generate(self,position,t,number): + x,y=position + points=[] + for i in range(number): + points.append([x,y]) + nx=fx(x,y,t) + ny=fy(x,y,t) + x,y=nx,ny + return points + + + + def __call__(self): + self.time=self.start + while self.window.open: + self.window.check() + #self.update() + self.show() + self.time+=self.delta + + def update(self,t=1): + for i,point in enumerate(self.points): + x,y=point + nx=self.fx(x,y,t) + ny=self.fy(x,y,t) + self.points[i]=[nx,ny] + print([nx,ny]) + + def show(self): + t=self.time + #print(t) + wsx,wsy=window.size + self.window.clear() + positions=[] + x,y=t,t + + for i in range(self.number): + nx=self.fx(x,y,t) + ny=self.fy(x,y,t) + x,y=nx,ny + #print([x,y]) + if not (-1=50: + r+=(255-r)*luminosity/100 + g+=(255-g)*luminosity/100 + b+=(255-b)*luminosity/100 + else: + r-=r*luminosity/100 + g-=g*luminosity/100 + b-=b*luminosity/100 + color=r,g,b + return color + + def colorize(self,image, color): + """Return image colorized""" + image = image.copy() + image.fill((0,0,0,255),None,pygame.BLEND_RGBA_MULT) + image.fill(color[0:3]+(0,),None,pygame.BLEND_RGBA_ADD) + return image + + + + def wavelengthToRGB(self,wavelength): + """Convert wavelength [380,780] to rgb color type.""" + gamma,max_intensity=0.80,255 + def adjust(color, factor): + if color==0: return 0 + else: return round(max_intensity*pow(color*factor,gamma)) + if 380<=wavelength<=440: r,g,b=-(wavelength-440)/(440-380),0,1 + elif 440<=wavelength<=490: r,g,b=0,(wavelength-440)/(490-440),1 + elif 490<=wavelength<=510: r,g,b=0,1,-(wavelength-510)/(510-490) + elif 510<=wavelength<=580: r,g,b=(wavelength-510)/(580-510),1,0 + elif 580<=wavelength<=645: r,g,b=1,-(wavelength-645)/(645-580),0 + elif 645<=wavelength<=780: r,g,b=1,0,0 + else: r,g,b=0,0,0 + if 380<=wavelength<=420: factor=0.3+0.7*(wavelength-380)/(420-380) + elif 420<=wavelength<=701: factor=1 + elif 701<=wavelength<=780: factor=0.3+0.7*(780-wavelength)/(780-700) + else: factor=0 + r,g,b=adjust(r,factor),adjust(g,factor),adjust(b,factor) + return (r,g,b) + + def kill(self): + """Quit pygame.""" + pygame.quit() + + def log(self,message): + """Print message with window mention.""" + text="["+self.name+"] "+message + print(text) + + def __del__(self): + """Executed before the window is destroyed.""" + self.log("Window has been closed.") + + + + + + + +if __name__=="__main__": + w=Window("Window Prototype") + #save(w,"grosse fenetre") + #w=load("grosse fenetre") + #print(w.lighten(BLUE)) + #w.alert("test") + w.pause() + w.clear() + w.alert("je raconte de la merde juste pour avoir une longue chaine de caractere") + w.pause() + w.kill() diff --git a/Fourier/.DS_Store b/Fourier/.DS_Store new file mode 100644 index 0000000..5008ddf Binary files /dev/null and b/Fourier/.DS_Store differ diff --git a/Grapher/Version 3/GrapherV3.py b/Grapher/Version 3/GrapherV3.py index 4b578bf..9f45c9a 100644 --- a/Grapher/Version 3/GrapherV3.py +++ b/Grapher/Version 3/GrapherV3.py @@ -23,6 +23,21 @@ import random import numpy as np import noise + +BLUE = ( 0, 0,255) +RED = (255, 0, 0) +GREEN = ( 0,255, 0) +YELLOW = (255,255, 0) +BLACK = ( 0, 0, 0) +WHITE = (255,255,255) +GREY = (100,100,100) +PURPLE = (100, 0,100) +DARKGREY = ( 20, 20, 20) +DARKRED = ( 10, 10, 10) +DARKGREEN = ( 10, 10, 10) +DARKBLUE = ( 10, 10, 10) + + #-------# #Classes# #-------# diff --git a/Grapher/Version 3/test.py b/Grapher/Version 3/test.py index 3a64a7e..c4cb1f3 100644 --- a/Grapher/Version 3/test.py +++ b/Grapher/Version 3/test.py @@ -1,5 +1,5 @@ from GrapherV3 import Grapher -from math import exp,sin,cos,atan +from math import exp,sin,cos,atan,log def sigmoid(x): return 1/(1+exp(-x)) @@ -16,4 +16,7 @@ polynome=lambda x:x**4+2*x**3-x**2-6*x-3 functions=[polynome] +dm=lambda x:x*log(x)+x-1 +functions=[dm] + Grapher(functions) diff --git a/Intersection/.DS_Store b/Intersection/.DS_Store new file mode 100644 index 0000000..e4ef284 Binary files /dev/null and b/Intersection/.DS_Store differ diff --git a/Intersection/game.py b/Intersection/game.py new file mode 100644 index 0000000..b08890b --- /dev/null +++ b/Intersection/game.py @@ -0,0 +1,50 @@ +from mygeometry import Forms +from mywindow import Window + + +class Level: + def __init__(self,name="Unnamed",over=False): + self.name=name + self.over=over + def create(self): + self.entities + +class Game: + def __init__(self,name="Asteroid",window=None): + self.name=name + self.window=window + if self.window==None: self.window=Window(self.name,build=False) + self.window.build() + self.plan=Plan(lines=False) + self.levels=[Level("First level")] + self.round=0 + self.over=False + def __call__(self): + while self.window.open and not self.over: + self.window.check() + self.update() + self.show() + def update(self): + level=self.levels[self.round] + if level.over: + self.round+=1 + else: + level() + entities=self.levels[self.level].entities + player=level.control() + for entity in entities: + entity.update(entities) + + def show(self): + self.window.clear() + for entity in self.levels[self.round].entities: + entity.show(self.window,self.plan) + self.window.flip() + + + + +if __name__=="__main__": + window=Window(build=False) + game=Game(window=window) + game() diff --git a/Intersection/geometry.py b/Intersection/geometry.py new file mode 100644 index 0000000..9bc456e --- /dev/null +++ b/Intersection/geometry.py @@ -0,0 +1,121 @@ +from mycolors import WHITE +from mymaths import mean,pi +from mywindow import Window + + +class Trace: + def __init__(self,color=WHITE): + self.color=color + + +class Form(Trace): + def __init__(self,points,color=WHITE): + Trace.__init__(self,color) + self.points=points + self.center=self.center(self.points) + def center(self,points): + mx=mean([point.x for point in points]) + my=mean([point.y for point in points]) + return [mx,my] + def rotate(self,center=None,angle=pi): + if center==None: + center=self.center(self.points) + def __getitem__(self, index): + return self.points[index] + def __setitem__(self, index, value): + self.points[index]=value + + + +class Circle(Trace): + def __init__(self,*args,radius=10,color=WHITE): + Trace.__init__(self,color) + #self.x=x + #self.y=y + self.position=list(args) + self.radius=radius + self.color=color + def show(self,window): + pass + + +class Point(Circle): + def __init__(self,x,y,radius=1,color=WHITE): + Circle.__init__(self,x,y,radius=radius,color=color) + def __getitem__(self, index): + return self.position[index] + def __setitem__(self, index, value): + self.position[index]=value + +class Line(Form): + def __init__(self,p1,p2,color=WHITE): + Form.__init__(self,[p1,p2],color) + if p1.x!=p2.x: + self.a=(p2.y-p1.y)/(p2.x-p1.x) + else: + self.a=None + if self.a!=None: + self.b=p1.y-self.a*p1.x + else: + self.b=None + def show(self,window): + pass + + +class Segment(Line): + def __init__(self,p1,p2,color=WHITE): + Line.__init__(self,p1,p2) + self.p1=p1 + self.p2=p2 + + def __mul__(self,other): + Mx=max(self.p1[0],self.p2[1]) + My + return True + + def show(self,window): + window.draw.line(window.screen,self.color,[p1[0],p1[1]],[p2[0],p2[1]],1) + + def showAll(self,window): + pass + + + + +class Polygone(Form): + def __init__(self,points): + self.points=points + self.segments=[Segment(points[i%len(points)],points[(i+1)%len(points)]) for i in range(len(points))] + def __mul__(self,other): + pass + + +class Triangle(Polygone): + def __init__(self,points): + Polygone.__init__(points) + + +class Square(Polygone): + def __init__(self,points): + Polygone.__init__(points) + +""" +Syntax: +segment1*segment2=>bool +polygone1*polygone2=>bool + +x:p.position[0] +x:p.x +x:p[0] +""" + + + +if __name__=="__main__": + window=Window() + p1=Point(15,200) + p2=Point(540,54) + #s=Segment(p1,p2) + print(p1.x) + s.show(window) + window() diff --git a/Intersection/main.py b/Intersection/main.py new file mode 100644 index 0000000..edfef25 --- /dev/null +++ b/Intersection/main.py @@ -0,0 +1,49 @@ +from mywindow import Window +from mylab import Lab +from mycolors import * +from mygeometry import Form,Point +import random + +class Room(Lab): + def __init__(self,name,entities): + Lab.__init__(self,name,entities) + def update(self): + for entity in self.entities: + entity.update(self.window) + if self.window.focus: + x,y=self.window.point() + self.window.focus.x=x + self.window.focus.y=y + if self.window.onclick(): + print("onClick") + self.onclick() + wx,wy=self.window.point() + c=self.entities[0].center() + c.color=GREEN + c.show(self.window) + x,y=c[0],c[1] + self.entities[0].move(wx-x,wy-y) + self.entities[0].rotate(0.01) + self.collide() + def collide(self): + for i in range(len(self.entities)): + self.entities[i].color=WHITE + for i in range(len(self.entities)): + for j in range(i+1,len(self.entities)): + if self.entities[i]|self.entities[j]: + self.entities[i].color=RED + self.entities[j].color=RED + def onclick(self): + print("clicked") + if self.window.focus is not None: + self.window.focus=None + else: + for form in self.entities: + for point in form.points: + if self.window.point() in point: + self.window.focus=point + +if __name__=="__main__": + entities=[Form([Point(random.random()*900,random.random()*400) for i in range(3)]) for i in range(3)] + r=Room(name="Geometry",entities=entities) + r() diff --git a/Intersection/mycolors.py b/Intersection/mycolors.py new file mode 100644 index 0000000..9402063 --- /dev/null +++ b/Intersection/mycolors.py @@ -0,0 +1,18 @@ +BLUE = ( 0, 0,255) +RED = (255, 0, 0) +GREEN = ( 0,255, 0) +YELLOW = (255,255, 0) +BLACK = ( 0, 0, 0) +WHITE = (255,255,255) +GREY = (100,100,100) +PURPLE = (100, 0,100) +HALFGREY = ( 50, 50, 50) +DARKGREY = ( 20, 20, 20) +DARKRED = ( 10, 10, 10) +DARKGREEN = ( 10, 10, 10) +DARKBLUE = ( 10, 10, 10) +LIGHTBROWN = (229,219,222) +LIGHTGREY = (200,200,200) +BEIGE = (199,175,138) + +print("mycolors imported") diff --git a/Intersection/mygeometry.py b/Intersection/mygeometry.py new file mode 100644 index 0000000..72b9b55 --- /dev/null +++ b/Intersection/mygeometry.py @@ -0,0 +1,395 @@ +WHITE=(255,255,255) + +from mywindow import Window + +from mymaths import sign2,mean +from math import sqrt,atan,pi,cos,sin +import random +from cmath import polar + +class Figure: + def __init__(self,segments,color=WHITE): + """Create a figure object.""" + self.segments=segments + self.color=color + def show(self,window): + """Show segments.""" + for segment in self.segments: + segment.show(window) + + +class Form: + def __init__(self,points,closed=True,fill=False,width=1,color=WHITE): + """Create the form object using points.""" + self.points=points + self.closed=closed + self.fill=fill + self.width=1 + self.color=color + def __add__(self,point): + """Add a point to the form.""" + self.points+=point + def __sub__(self,point): + """Remove a point to the form.""" + self.points.remove(point) + def center(self): + """Return the point of the center.""" + mx=mean([p.x for p in self.points]) + my=mean([p.y for p in self.points]) + return Point(mx,my) + def sides(self): + """"Return the list of the form sides.""" + return [Segment(self.points[i%len(self.points)],self.points[(i+1)%len(self.points)],color=self.color,width=self.width) for i in range(len(self.points))] + def show(self,window): + """Show the form using a window.""" + for point in self.points: + point.show(window) + for side in self.sides(): + side.show(window) + def __or__(self,other): + """Return the bool: (2 sides are crossing).""" + for myside in self.sides(): + for otherside in other.sides(): + if myside|otherside: + return True + return False + def connex(self): + """Return the bool (the form is connex).""" + pass + def sparse(self): + """Return the form with the most sparsed points.""" + pass + def __contains__(self,point): + """Return the bool: (the point is in the form).""" + x,y=point[0],point[1] + p1=Point(x,y) + p2=Point(0,0) + line=Line(p1,p2) + line.show(window) + print(line.__dict__) + for segment in self.sides(): + if segment|line: + return True + return False + #Trace une ligne passant par + def rotate(self,angle,center=None): + """Rotate the form by rotating its points from the center of rotation. + Use center of the shape as default center of rotation.""" #Actually not working + if not center: + center=self.center() + c=self.center() + for i in range(len(self.points)): + self.points[i].rotate(angle,center) + """for point in self.points: + point.rotate(angle,center) #rotate should have a second optional argument that does the same thing than above""" + + def move(self,*step): + """Move the object by moving all its points using step.""" + x,y=step[0],step[1] + for i in range(len(self.points)): + self.points[i].x+=x + self.points[i].y+=y + def moveTo(self,position): + """Move the object to an absolute position.""" + x,y=position[0],position[1] + cx,cy=self.center() + for i in range(len(self.points)): + vx=self.points[i].x-cx + vy=self.points[i].y-cy + self.points[i].x=vx+x + self.points[i].y=vy+y + + + def moveUntil(self,position): + """Move the object to the position until the point is hit.""" + pass + + def update(self,input): + """Update the points.""" + for point in self.points: + point.update(input) + def __getitem__(self,index): + """Return the point of index index.""" + return self.points[index] + def __setitem__(self,index,value): + """Change the points of a form.""" + self.points[index]=value + def triangleArea(self,form): + """Return the area of a triangle of type form.""" + a,b,c=form.sides() + A=1/4*sqrt(4*a.l**2*b.l**2-(a.l**2+b.l**2-c.l**2)**2) + def __len__(self): + """Return number of points.""" + return len(self.points) + + +class Polygon: + def __init__(self,points,fill=False,width=1,color=WHITE,showpoints=True): + """Create the polygon using points, fill, width, color and showpoints.""" + self.points=points + self.fill=fill + self.width=1 + self.color=color + self.showpoints=showpoints + def show(self,window): + """Show the polygon using window.""" + positions=[[p.x,p.y] for p in self.points] + window.draw.polygon(window.screen,self.color,positions,self.width) + if self.showpoints: + for point in self.points: + point.show(window) + return False + def update(self): + pass + +class Point: + def __init__(self,*args,radius=5,fill=False,color=WHITE): + """Create a point using x, y, radius, fill and color.""" + self.x=args[0] + self.y=args[1] + self.n=sqrt(self.x**2+self.y**2) + self.a=atan(self.y/self.x) + self.radius=radius + self.fill=fill + self.color=color + def __contains__(self,other): + """Return bool if objects is in point.""" + ox,oy=other[0],other[1] + if self.radius>=sqrt((ox-self.x)**2+(oy-self.y)**2): + return True + else: + return False + def __getitem__(self,index): + """Return x or y value using given index.""" + if index==0: + return self.x + if index==1: + return self.y + def __setitem__(self,index,value): + """Change x or y value using given index and value.""" + if index==0: + self.x=value + if index==1: + self.y=value + def rotate(self,angle=pi,point=[0,0]): + """Rotate the point using the angle and the center of rotation. + Uses [0,0] for the center of rotation by default.""" + s=Vector(self.x,self.y) + v=Vector(self.x-point[0],self.y-point[1]) + sn,sa=s.polar() + vn,va=v.polar() + self.x=s.x+vn*cos(sa+va) + self.y=s.y+vn*sin(sa+va) + print(self.x,self.y) + def move(self,*step): + """Move the point using given step.""" + self.x+=step[0] + self.y+=step[1] + def moveTo(self,position): + """Move the point to position using given position.""" + pass + def show(self,window): + """Show a point using window.""" + window.draw.circle(window.screen,self.color,[int(self.x),int(self.y)],self.radius,not self.fill) + def __add__(self,other): + """Add two points together by making the sum of their components.""" + """ if other.color==self.color: + color=self.color + else: + color=None + if other.width=self.width: + width=self.width + else: + width=None + if""" + return Point(self.x+other[0],self.y+other[1]) + def __sub__(self,other): + return Point(self.x-other[0],self.y-other[1]) + +class Line: + def __init__(self,p1,p2,width=1,color=WHITE): + """Create the line using 2 points, width and color.""" + self.width=width + self.color=color + if p1.x!=p2.x: + self.a=(p2.y-p1.y)/(p2.x-p1.x) + else: + self.a=None + if self.a!=None: + self.b=p1.y-self.a*p1.x + else: + self.b=None + def evaluate(self,x): + """Evaluate the affine function corresponding to the line using x.""" + return self.a*x+self.b + def show(self,window): + """Show the line using window.""" + wcmx,wcmy,wcMx,wcMy=window.coordonnates + my=self.evaluate(wcmx) + My=self.evaluate(wcMx) + window.draw.line(window.screen,self.color,[wcmx,my],[wcMx,My],self.width) + def __or__(self,other): + """Return bool for (2 lines are crossing).""" + if self.a==other.a: + return None + x=(self.b-other.b)/(other.a-self.a) + y=self.a*x+self.b + return Point(x,y) + + +class Segment(Line): + def __init__(self,p1,p2,width=1,color=WHITE): + """Create the segment using 2 points, width and color.""" + Line.__init__(self,p1,p2,width,color) + self.p1=p1 + self.p2=p2 + def center(self): + """Return the point of the center of the Segment.""" + x=(self.p1.x+self.p2.x)/2 + y=(self.p1.y+self.p2.y)/2 + return Point(x,y,color=self.color) + def show(self,window): + """Show the segment using window.""" + window.draw.line(window.screen,self.color,[self.p1.x,self.p1.y],[self.p2.x,self.p2.y],self.width) + def __len__(self): + """Return the length of the segment.""" + x=p1.x-p2.x + y=p1.y-p2.y + return sqrt(x**2+y**2) + + def __or__(self,other): + """Return bool for (2 segments are crossing).""" + if not self.a or not other.a or not self.b or not other.b: + return None + if self.a==other.a: + return None + x=(self.b-other.b)/(other.a-self.a) + y=self.a*x+self.b + if type(other)==Segment: + mx=max(min(self.p1.x,self.p2.x),min(other.p1.x,other.p2.x)) + Mx=min(max(self.p1.x,self.p2.x),max(other.p1.x,other.p2.x)) + my=max(min(self.p1.y,self.p2.y),min(other.p1.y,other.p2.y)) + My=min(max(self.p1.y,self.p2.y),max(other.p1.y,other.p2.y)) + if mx<=x<=Mx and my<=y<=My: + return Point(x,y,color=self.color) + else: + return None + if type(other)==Line: + mx=min(self.p1.x,self.p2.x) + Mx=max(self.p1.x,self.p2.x) + my=min(self.p1.y,self.p2.y) + My=max(self.p1.y,self.p2.y) + if mx<=x<=Mx and my<=y<=My: + return Point(x,y,color=self.color) + else: + return None + else: + return None + +class Vector: + def __init__(self,*args,arrow=(3,3),width=1,color=WHITE): + """Create a vector.""" + a=list(*args) + print(a) + self.x=a[0] + self.y=a[1] + self.width=width + self.color=color + def show(self,p,window): + """Show the vector.""" + print(p[0],p[1]) + p2=Point(self.x+p[0],self.y+p[1],color=self.color) + s=Segment(p1,p2,width=self.width,color=self.color) + s.show(window) + def __neg__(self): + """Return the negative vector.""" + x=-self.x + y=-self.y + return Vector(x,y,width=self.width,color=self.color) + def polar(self): + """Return the polar coordonnates for the x and y position of the object.""" + return list(polar(complex(self.x,self.y))) + def colinear(self,other): + """Return if two vectors are colinear.""" + return self.x*other.y-self.y*other.x==0 + def scalar(self,other): + """Return the scalar product between two vectors.""" + return self.x*other.x+self.y*other.y + def __mul__(self,factor): + """Multiply a vector by a given factor.""" + if type(factor)==Vector: + pass + else: + self.x*=factor + self.y*=factor + def __add__(self,other): + """Add two vectors together.""" + return Vector(self.x+other.x,self.y+other.y,width=self.width,color=self.color) + def rotate(self,angle): + """Rotate a vector using the angle of rotation.""" + n,a=self.polar() + a+=angle + self.x+=n*cos(a) + self.y+=n*sin(a) + def __getitem__(self,index): + """Return x or y value using given index.""" + if index==0: + return self.x + if index==1: + return self.y + def __setitem__(self,index,value): + """Change x or y value using given index and value.""" + if index==0: + self.x=value + if index==1: + self.y=value + def __call__(self,*points): + """Return points by applying the vector on those.""" + points=[point+self for point in points] + if len(points)==1: + return points[0] + else: + return points + + + + +class Wrapper: + def __init__(self,form): + self.form=form + def update(self): + pass + +if __name__=="__main__": + window=Window() + p1=Point(15,62) + p2=Point(250,400) + p3=Point(800,500) + p4=Point(400,400,color=(0,255,0)) + points=[p1,p2,p3,p4] + for point in points: + point.show(window) + #f=Form([p1,p2,p3],color=(0,0,255)) + #f.show(window) + #Segment(f[0],f[1],color=(255,0,0)).center().show(window) + #print(p4 in f) + #window.clear() + #p4.show(window) + #a=Line(p4,p2,color=(255,0,0)) + #b=Segment(p1,p3,color=(255,255,0)) + #a.show(window) + #b.show(window) + #p=b|a + a=p2-p1 + a=Vector(a) + b=Vector(60,-20) + a.show(p2,window) + b.show(p2,window) + window() + + + + #print(list(p)) + + +a=Vector(1,5) diff --git a/Intersection/myinput.py b/Intersection/myinput.py new file mode 100644 index 0000000..d7e70eb --- /dev/null +++ b/Intersection/myinput.py @@ -0,0 +1,14 @@ +import pygame + +class Input: + getKeys=pygame.key.get_pressed() + getClick=bool(pygame.mouse.get_pressed()[0]) + getCursor=pygame.mouse.get_pos() + + def __init__(self): + self() + + def __call__(self): + self.click=Input.getClick() + self.cursor=Input.getCursor() + self.keys=Input.getKeys() diff --git a/Intersection/mylab.py b/Intersection/mylab.py new file mode 100644 index 0000000..03edacf --- /dev/null +++ b/Intersection/mylab.py @@ -0,0 +1,43 @@ +from mywindow import Window + +class Lab: + def __init__(self,name="Lab",entities=[]): + """Creates lab using name.""" + self.name=name + self.entities=entities + self.loop=[] + self.window=Window(self.name) + + def __call__(self): + """Main loop.""" + #self.spawn() + while self.window.open: + self.window.check() + self.window.clear() + for function in self.loop: + function() + self.update() + self.show() + + def update(self): + """Updating all entities.""" + for entity in self.entities: + entity.update(self.window.input) + + def show(self): + """Update screen.""" + + for entity in self.entities: + entity.show(self.window) + self.window.flip() + + def spawn(self): + """Spawn all entites.""" + for entity in self.entities: + entity.spawn() + +if __name__=="__main__": + #import mypanel + + lab=Lab("Testing Zone") + lab() diff --git a/Intersection/mymaths.py b/Intersection/mymaths.py new file mode 100644 index 0000000..484c1b5 --- /dev/null +++ b/Intersection/mymaths.py @@ -0,0 +1,94 @@ +import math + +def mean(*args): + l=allout(args) + return sum([e for e in l])/len(l) + +def prod(*args): + l=allout(args) + r=1 + for e in l: + r*=e + return r + +def sum(*args): + l=allout(args) + r=0 + for e in l: + r+=e + return r + + +sign=lambda x:x>=0 + +def sign2(x): + if x>0: + return 1 + elif x<0: + return -1 + else: + return 0 + +def container(object): + if type(object)==str: + return False + try: + a=object[0] + return True + except: + return False + +""" +def sum(*args): + r=0 + for e in args: + if container(e): + for x in e: + r+=sum(x) + else: + r+=e + return r +""" + +def out(l): + if container(l): + r=[] + for e2 in l: + if container(e2): + r+=e2 + else: + r.append(e2) + return r + else: + return l + +def allout(l): + if container(l): + r=[] + for e2 in l: + if container(e2): + r+=allout(e2) + else: + r.append(e2) + return r + else: + return l + +def analyse(l): + r=[] + if container(l): + for e in l: + r.append(analyse(e)) + else: + r.append(type(l)) + return r + +bijection=lambda x,i1,i2:(i2[1]-i2[0])/(i1[1]-i1[0])*(x-i1[0])+i2[0] + +pi=PI=math.pi +e=E=euler=math.e + +if __name__=="__main__": + l1=[1,[3,1],[1,2,[2,1]],3] + l2=["12",["1","6"],"manger"] + print(analyse(l2)) diff --git a/Intersection/myplan.py b/Intersection/myplan.py new file mode 100644 index 0000000..ea5e7f8 --- /dev/null +++ b/Intersection/myplan.py @@ -0,0 +1,10 @@ +class Plan: + def __init__(self,size=[10,10],zoom=[1,1],position=[0,0],color_background=(0,0,0),color_line=(255,255,255),graduate=False): + self.size=size + self.zoom=zoom + self.color_background=color_background + self.color_line=line + self.graduate=graduate + def draw(self,window): + window.clear(color_background) + wsx,wsy=window.size diff --git a/Intersection/myposition.py b/Intersection/myposition.py new file mode 100644 index 0000000..46e5e36 --- /dev/null +++ b/Intersection/myposition.py @@ -0,0 +1,72 @@ +from math import sqrt,cos,sin +from cmath import polar +from numpy import array,dot + +class Position: + base="xyztabcdefhijklmnopqrsuvw" + angle_base="ab" + + def __init__(self,*data,base=None,system="cartesian"): + """Save a position using cartesian coordonnates.""" + self.system=system + if self.system is "cartesian": self.data=array(data) + if self.system is "polar": self.data=polar(list(data)) + if base: self.base=base + else: self.base=Position.base[:len(self.data)] + def __call__(self): + return list(self.data) + def __str__(self,system="cartesian"): + """Gives a representation of the position.""" + if system is "cartesian": + return " ".join([str(self.base[i])+"="+str(self.data[i]) for i in range(len(self.data))]) + if system is "polar": + pass + + x=lambda self:self.data[self.base.index("x")] + y=lambda self:self.data[self.base.index("y")] + z=lambda self:self.data[self.base.index("z")] + t=lambda self:self.data[self.base.index("t")] + __repr__=__str__ + __add__=lambda self,other:self.data+other.data + __sub__=lambda self,other:self.data-other.data + + + def __mul__(self,other): + if type(other) is Position: + return Position(dot(self.data,other.data)) + else: + return Position([self.data*other]) + + + def __sub__(self,other): + pass + def __len__(self): + """Return number of dimension of the position.""" + return len(self.data) + + def polar(self,position=None): + """Return an array of the polar coordonnates using optionnal position.""" + if not position: position=self.data + position=list(position) + if len(position)==2: + return array(polar(complex(*position))) + else: + raise Exception(str(position)+" is not a cartesian position.") + + def cartesian(self,position=None): + """Return an array of the cartesian position using optional polar position.""" + if not position: position=self.data + if len(position)==2: + return array([position[0]*cos(position[1]),position[0]*sin(position[1])]) + else: + raise Exception(str(position)+" is not a polar position.") + +a=Position(2,6) +b=Position(2,4) +print((a*b).data) + +print(a.polar()) +print(a.cartesian()) +print(Position.polar(a.data)) + +print(a) diff --git a/Intersection/mywindow.py b/Intersection/mywindow.py new file mode 100644 index 0000000..cc547ea --- /dev/null +++ b/Intersection/mywindow.py @@ -0,0 +1,312 @@ +from __future__ import division + +from mycolors import * +#from myinput import Input +import time + +import pygame +from pygame.locals import * +import time +import json + + + +class Window: + made=0 + draw=pygame.draw + bijection=lambda x,i1,i2:(i2[1]-i2[0])/(i1[1]-i1[0])*(x-i1[0])+i2[0] + + def __init__(self,name="Unnamed",size=None,text_font="monospace",text_size=65,text_color=WHITE,background_color=BLACK,fullscreen=False,build=True): + """Create a window object using name, size text_font, text_size, text_color, background and set.""" + Window.made+=1 + self.number=Window.made + self.name=name + self.size=size + self.text_font=text_font + self.text_size=text_size + self.text_color=text_color + self.background_color=background_color + self.fullscreen=fullscreen + #self.input=Input() + self.set() + if build: + self.build() + self.log("Window has been created.") + + def set(self): + """Set builtins attributs of window object.""" + self.RIGHT = 0 + self.UP = 1 + self.LEFT = 2 + self.DOWN = 3 + self.selecter_color=self.reverseColor(self.background_color) + self.open=False + self.screenshots_taken=0 + self.pause_cool_down=1 + self.click_cool_down=0.3 + self.last_click=time.time() + self.pause_time=0.2 + self.focus=None + + def build(self): + """Creates apparent window.""" + pygame.init() + self.info = pygame.display.Info() + self.font = pygame.font.SysFont(self.text_font, self.text_size) + if self.size is None: + if self.fullscreen: + self.size=[self.info.current_w,self.info.current_h] + else: + self.size=[2*self.info.current_w//3,2*self.info.current_h//3] + self.coordonnates=[0,0]+self.size + if self.fullscreen: + self.screen=pygame.display.set_mode(self.size,FULLSCREEN) + else: + self.screen=pygame.display.set_mode(self.size,RESIZABLE) + pygame.display.set_caption(self.name) + if self.text_color is None: + self.text_color=self.reverseColor(self.background_color) + self.clear() + self.flip() + self.open=True + + def clear(self,color=None): + """Clear to background color.""" + if color is None: + color=self.background_color + self.screen.fill(color) + + def scale(self,picture,size): + """Return scaled picture using picture and size.""" + return pygame.transform.scale(picture,size) + + def check(self): + """Update window's state depending if close buttons are pressed.""" + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.open=False + if event.type == KEYDOWN: + if event.key == K_ESCAPE: + self.open=False + + def update(self): + """Updates all window's main attributs.""" + self.mouse_click=bool(pygame.mouse.get_pressed()[0]) + self.mouse_position=pygame.mouse.get_pos() + for event in pygame.event.get(): + if event.type == pygame.QUIT: + self.open=False + if event.type == KEYDOWN: + if event.key == K_ESCAPE: + self.open=False + + def pause(self): + """Wait for user to click on space.""" + while self.open: + self.check() + keys=pygame.key.get_pressed() + if keys[K_SPACE]: + break + if self.open: + time.sleep(self.pause_time) + + def __call__(self): + self.flip() + self.pause() + + + + def direction(self): + """Return keys for arrows pressed. Trigonometric orientation is used.""" + keys=pygame.key.get_pressed() + return (keys[K_RIGHT],keys[K_UP],keys[K_LEFT],keys[K_DOWN]) + + + def select(self): + """Wait for user to click on screen, then return cursor position.""" + while self.open: + self.check() + for event in pygame.event.get(): + if event.type == MOUSEBUTTONDOWN and event.button == 1: + return (event.pos[0],event.pos[1]) + + def point(self): + """Return cursor position on screen.""" + return pygame.mouse.get_pos() + + def press(self): + """Return all keys.""" + return pygame.key.get_pressed() + + def click(self): + """Return bool value for clicking on screen.""" + return bool(pygame.mouse.get_pressed()[0]) + + def onclick(self): + if self.click() and time.time()-self.last_click>self.click_cool_down: + self.last_click=time.time() + return True + else: + return False + + + + def flip(self): + """Refresh screen.""" + pygame.display.flip() + + def screenshot(self): + """Save picture of the surface.""" + self.picture_saved+=1 + pygame.image.save(self.screen,self.name+"-"+str(self.picture_saved)+".png") + + + def getPicture(self,picture_directory): + """Return picture using picture directory.""" + return pygame.image.load(picture_directory) + + def placePicture(self,picture_directory,coordonnates,color=None): + """Draw a picture on screen using pygame picture directory and position.""" + x,y,sx,sy=coordonnates + picture=pygame.image.load(picture_directory) + picture=pygame.transform.scale(picture,(sx,sy)) + if color is not None: + picture=colorize(picture,color) + self.screen.blit(picture, position) + + def centerText(self,message,size=None): + """Centers Text on screen.""" + sx,sy=self.size + if size is None: + size=self.text_size + l=len(message) + letter_size=size/4 + x=sx//2-letter_size*l//2 + y=sy//2-size/3 + return (x,y) + + def alert(self,message): + """Quickly display text on window.""" + position=self.centerText(message) + self.print(message,position) + self.flip() + + def print(self,text,position,size=None,color=None,font=None): + """Display text on screen using position, size, color and font.""" + if size is None: + size=self.text_size + if color is None: + color=self.text_color + if font is None: + font=self.font + label = font.render(text, 1, color) + self.screen.blit(label, position) + + def drawRect(self,coordonnates,color): + """Draw a rectangle on the screen using color and coordonnates relative to window's fiducials.""" + wsx,wsy=self.size + wcx,wcy,wcsx,wcsy=self.coordonnates + rcx,rcy,rcsx,rcsy=coordonnates + x,y=(rcx-wcx,rcy-wcy) + w,h=(rcsx*wsx/wcsx,rcsy*wsy/wcsy) + pygame.draw.rect(self.screen,color,(x,y,w,h),0) + + def place(self,position): + """Return position relative to window's fiducials.""" + wcx,wcy,wcsx,wcsy=self.coordonnates + pcx,pcy=position + x,y=(rcx-wcx,rcy-wcy) + return (x,y) + + + def randomColor(self): + """Return random color.""" + import random + r=random.randint(0,255) + g=random.randint(0,255) + b=random.randint(0,255) + color=(r,g,b) + return color + + def reverseColor(self,color): + """Return reverse color.""" + r,g,b=color + r=255-r + g=255-g + b=255-b + color=(r,g,b) + return color + + def lighten(self,color,luminosity=80): #View later + """Return lightened color using color and luminosity percentage.""" + r,g,b=color + if luminosity>=50: + r+=(255-r)*luminosity/100 + g+=(255-g)*luminosity/100 + b+=(255-b)*luminosity/100 + else: + r-=r*luminosity/100 + g-=g*luminosity/100 + b-=b*luminosity/100 + color=r,g,b + return color + + def colorize(self,image, color): + """Return image colorized""" + image = image.copy() + image.fill((0,0,0,255),None,pygame.BLEND_RGBA_MULT) + image.fill(color[0:3]+(0,),None,pygame.BLEND_RGBA_ADD) + return image + + + + def wavelengthToRGB(self,wavelength): + """Convert wavelength to rgb color type.""" + gamma,max_intensity=0.80,255 + def adjust(color, factor): + if color==0: return 0 + else: return round(max_intensity*pow(color*factor,gamma)) + if 380<=wavelength<=440: r,g,b=-(wavelength-440)/(440-380),0,1 + elif 440<=wavelength<=490: r,g,b=0,(wavelength-440)/(490-440),1 + elif 490<=wavelength<=510: r,g,b=0,1,-(wavelength-510)/(510-490) + elif 510<=wavelength<=580: r,g,b=(wavelength-510)/(580-510),1,0 + elif 580<=wavelength<=645: r,g,b=1,-(wavelength-645)/(645-580),0 + elif 645<=wavelength<=780: r,g,b=1,0,0 + else: r,g,b=0,0,0 + if 380<=wavelength<=420: factor=0.3+0.7*(wavelength-380)/(420-380) + elif 420<=wavelength<=701: factor=1 + elif 701<=wavelength<=780: factor=0.3+0.7*(780-wavelength)/(780-700) + else: factor=0 + r,g,b=adjust(r,factor),adjust(g,factor),adjust(b,factor) + return (r,g,b) + + def kill(self): + """Quit pygame.""" + pygame.quit() + + def log(self,message): + """Print message with window mention.""" + text="["+self.name+"] "+message + print(text) + + def __del__(self): + """Executed before the window is destroyed.""" + self.log("Window has been closed.") + + + + + + + +if __name__=="__main__": + w=Window("Window Prototype") + #save(w,"grosse fenetre") + #w=load("grosse fenetre") + #print(w.lighten(BLUE)) + #w.alert("test") + w.pause() + w.clear() + w.alert("je raconte de la merde juste pour avoir une longue chaine de caractere") + w.pause() + w.kill() diff --git a/Intersection/pencil.py b/Intersection/pencil.py new file mode 100644 index 0000000..34a5521 --- /dev/null +++ b/Intersection/pencil.py @@ -0,0 +1,21 @@ +from geometry import * + +class Pencil: + def __init__(self,name="Unnammed",color=WHITE): + self.name=name + self.color=color + self.points=[] + self.forms=[] + def __call__(self,window): + if window.click(): + self.points.append(Point(window.point(),WHITE)) + + def show(self,window): + for point in self.points: + point.show(window) + for form in self.forms: + form.show(window) + + + def click(self,window): + pass diff --git a/Intersection/test.py b/Intersection/test.py new file mode 100644 index 0000000..3490e8d --- /dev/null +++ b/Intersection/test.py @@ -0,0 +1,26 @@ +class object: + def __init__(self,*args): + self.position=list(args) + def __setitem__(self,index,value): + self.position[index]=value + def __getitem__(self,index): + return self.position[index] + def __add__(self,other,prout): + return "caca"+prout + +class position: + def __init__(self,x): + self.x=x + def __int__(self): + return self.x + +o=object() +print(o+*[o,"wesh"]) + +#o=object(2,1) +#o[0]+=3 +#print(o[0],o[1],o.position) + +#x=position(3) + +#print(int(x)) diff --git a/Intersection/weirdspaceship.py b/Intersection/weirdspaceship.py new file mode 100644 index 0000000..8c3ced2 --- /dev/null +++ b/Intersection/weirdspaceship.py @@ -0,0 +1,8 @@ +from myforms import Form,Point + +class WeirdSpaceship: + def __init__(self,position,size): + self.spawn(position) + def spawn(self,position): + + self.form=Form() diff --git a/Libraries/converter.py b/Libraries/converter.py new file mode 100644 index 0000000..4431421 --- /dev/null +++ b/Libraries/converter.py @@ -0,0 +1,176 @@ +import inspect + + +def test(arg1,arg2): + a = arg1 + arg2 + return a + + #do something with args + +keywords=["assert","break","class","continue","def","del","elif","else","except","finally","for", + "from","global","if","import","in","pass","print","raise","return","try","while","yield"] + +conversion1 = {"assert":"ASSERT", + "break":"SORTIR DE LA BOUCLE", + "class":"CLASSE", + "continue":"CONTINER", + "def":"DONNEES", + "del":"SUPPRIMER", + "elif":["SINON SI","FAIRE"], + "else":["SINON","FAIRE"], + "except":"EXCEPTE", + "finally":"FINALLEMENT", + "for":["POUR","FAIRE"], + "from":"DEPUIS", + "global":"GLOBAL", + "if":"SI", + "import":"IMPORTER", + "in":"DANS", + "pass":"PASSER", + "print":"AFFICHER", + "raise":"RELEVER", + "return":"AFFICHER", + "try":"ESSAYER", + "while":["TANT QUE","FAIRE"], + "yield":"PASSER AU TOUR SUIVANT", + "==":"=", + "=":"<-"} + + + +def algorithm(name): + lines = inspect.getsource(name) + output = [] + lines = lines.split("\n") + for line in lines: + output.append(Converter(line)()) + #print("output: ",output) + return "\n".join(output) + + +class Converter: + def __init__(self,line): + self.line=line + self.alphabet="abcdefghijklmnopqrstuvwxyz" + self.numbers="0123456789" + self.punctuation="():.," + self.conversion= {"assert": [[None,"assert",None], [None,"ASSERT",None]], + "break": [[None,"break"], [None,"SORTIR DE LA BOUCLE"]], + "class": [["class",None], ["CLASS",None]], + "continue": [[None,"continue",None], [None,"CONTINUER",None]], + "def": [["def",None,"(",None,"):"], [None,":\nDONNES: ",None," :"]], + "del": [[None,"del",None], [None,"SUPPRIMER",None]], + "elif": [[None,"elif",None,":"], [None,"SINON SI",None," FAIRE"]], + "else": [[None,"else:",None], [None,"SINON",None," FAIRE"]], + "except": [[None,"except:",None], [None,"EXCEPTE",None]], + "finally": [[None,"finally:",None], [None,"FINALLEMENT",None]], + "for": [["for",None," in ",None,":"], ["POUR",None," DANS ",None," FAIRE"]], + "from": [["from",None], ["DEPUIS",None]], + "global": [["global",None], ["GLOBAL",None]], + "if": [[None,"if ",None], [None,"SI",None]], + "import": [[None,"import",None], [None,"IMPORTER",None]], + " in ": [[None," in ",None], [None, "DANS ",None]], + " is ": [[None," is ",None], [None," EST ",None]], + "pass": [[None,"pass"], [None,"PASSER",None]], + "print": [[None,"print",None,"(",None,")"], [None,"AFFICHER: ",None,None]], + "raise": [[None,"raise",None], [None,"RELEVER",None]], + "return": [[None,"return",None], [None,"AFFICHER",None]], + "try": [[None,"try:",None], [None,"ESSAYER",None]], + "while": [["while ",None,":"], ["TANT QUE ",None," FAIRE"]], + "yield": [[None,"yield"], [None,"PASSER AU TOUR SUIVANT"]], + "==": [[None,"==",None], [None,"=",None]], + "!=": [[None,"!=",None], [None,"≠",None]], + "=": [[None,"=",None], [None,"<=",None]], + "append": [[None,".append(",None,")"], ["AJOUTER A ",None," LA VALEUR ",None]]} + + self.removeIndent() + + + def removeIndent(self): + self.indent=0 + if self.line!="": + while self.line[0]==" ": + self.indent+=1 + self.line=self.line[1:] + + def convert(self): + if not ("#" in self.line): + for key in self.conversion: + if key in self.line: + self.apply(key) + + def apply(self,key): + #print("key:",key) + l=self.missing(self.conversion[key][0]) + #print("l:",l) + filled=self.fill(self.conversion[key][1],l) + #print("filled:",filled) + self.line="".join(filled) + #print(self.line) + + def missing(self,l): + """ + l= ["def ",None,"(",None,"):"] + self.line= "def algorithm(name):" + l1=["def","(","):"] + """ + line=[] + if l[0]==None: + i=self.next(self.line,l[1]) + line.append(self.line[:i]) + for i in range(1,len(l)-1): + #print("missing loop:",l[i-1],l[i],l[i+1]) + if l[i]==None: + a=self.between(self.line,l[i-1],l[i+1]) + line.append(a) + #print("a",a) + if l[-1]==None: + i=self.next(self.line,l[-2])+len(l[-2]) + line.append(self.line[i:]) + return line + + def removeNone(self,l): + l1=[] + for word in l: + if word!=None: + l1.append(word) + return l1 + + def between(self,text,word1,word2): + i1=self.next(text,word1)+len(word1) + i2=i1+self.next(text[i1:],word2) + return text[i1:i2] + + def cut(self,text,word): + for i in range(len(text)-len(word)+1): + if text[i:i+len(word)]==word: + break + return [text[:i],word,text[i+len(word):]] + + def next(self,text,word): + for i in range(len(text)-len(word)+1): + if text[i:i+len(word)]==word: + break + return i + + def fill(self,l1,l2): + line=[] + for e1 in l1: + if e1==None: + line.append(l2[0]) + del l2[0] + else: + line.append(e1) + return line + + def __call__(self): + self.convert() + return " "*self.indent+self.line + + + +print(algorithm(algorithm)) + +#c=Converter("def test(arg1,arg2):") + +#print(c.between("def test(arg1,arg2):","(",")")) diff --git a/Libraries/mywindow.py b/Libraries/mywindow.py index 8270752..8bdbdb2 100644 --- a/Libraries/mywindow.py +++ b/Libraries/mywindow.py @@ -1,8 +1,6 @@ from __future__ import division -from mymemory2 import * from mycolors import * -from mypencil import * import pygame from pygame.locals import * @@ -59,8 +57,8 @@ class Window: else: self.screen=pygame.display.set_mode(self.size,RESIZABLE) pygame.display.set_caption(self.name) - if text_color is None: - text_color=self.reverseColor(self.background_color) + if self.text_color is None: + self.text_color=self.reverseColor(self.background_color) self.clear() self.flip() self.open=True diff --git a/Othello/Solo/Othello.py b/Othello/Solo/Othello.py index 5cff36c..d3ba4ae 100644 --- a/Othello/Solo/Othello.py +++ b/Othello/Solo/Othello.py @@ -23,7 +23,7 @@ class Othello: self.moves_color=RED self.theme=[self.grid_color,self.pieces_color,self.moves_color] self.board=Board(self.theme) - self.players=[Beast(0,4),Beast(1,3)] + self.players=[Human(0),Beast(1,3)] self.won=False self.state=0 self.input=None diff --git a/Othello/Solo/player.py b/Othello/Solo/player.py index 31558b5..e64dace 100644 --- a/Othello/Solo/player.py +++ b/Othello/Solo/player.py @@ -110,7 +110,7 @@ class Beast(Player): print("sum: ",sum) return sum""" - + #Does exactly the same thing but in one line ;) return sum([sum([(2*side-1)*(int(grid[y][x]==1)-int(grid[y][x]==2))*self.advantage[y][x] for x in range(len(self.advantage[y]))]) for y in range(len(self.advantage))]) diff --git a/Othello/TIPE/Othello.py b/Othello/TIPE/Othello.py new file mode 100755 index 0000000..967cdbb --- /dev/null +++ b/Othello/TIPE/Othello.py @@ -0,0 +1,104 @@ +import mywindow +import mycolors as couleur + +import board as Plateau + +import Player as Joueur +import time +import pygame +from pygame.locals import *##todo +import config as cfg + +from copy import deepcopy + + + +class Othello: + def __init__(self,fenetre, liste_joueur): + self.nom="Othello" + self.fenetre=fenetre + self.fenetre.name=self.nom + self.fenetre.set() + self.fenetre.couleur_de_fond=couleur.VERT + self.couleur_grille=couleur.NOIR + self.couleur_pieces=[couleur.BLANC,couleur.NOIR] + self.couleur_mouvement=couleur.ROUGE + self.theme=[self.couleur_grille,self.couleur_pieces,self.couleur_mouvement] + self.plateau=Plateau.Board(self.theme) + self.joueurs=liste_joueur + for compteur in range(len(self.joueurs)): + self.joueurs[compteur].side=compteur + self.nombre_joueurs=len(self.joueurs) + self.gagne=False + self.state=0 + self.tour=self.state%self.nombre_joueurs + + + def __call__(self): + self.afficher() + + cfg.debug(self.joueurs) + while self.fenetre.open and not self.gagne: + self.fenetre.check() + cfg.debug("10") + self.faireTour() + cfg.debug("11") + self.gagne=self.plateau.testVictoire() + cfg.debug("12") + cfg.debug("13") + #time.sleep(0.2) + cfg.debug("main boucle") + self.finalScene() + print("c'est la fin") + + + def finalScene(self): + """Afficher le resultat de la partie une fois qu'elle est terminee.""" + #self.afficher() + self.tour = self.state % self.nombre_joueurs + joueur_actif=self.joueurs[self.tour] + if self.gagne: + message="Joueur "+str(joueur_actif.side+1)+" won!" + if not self.gagne: #to complete with moves counter + message="Match Nul" + position=list(self.fenetre.centerText(message)) + position[0]-=50 + taille=[int(len(message)*self.fenetre.taille_du_texte/2.7),70] + self.fenetre.print(message,position,taille,color=couleur.NOIR,couleur_de_fond=couleur.BLANC) + self.fenetre.flip() + while self.fenetre.open: + self.fenetre.check()#On attend qu'on ferme la fenetre + #Todo retourner menu principal + + def getInput(self): + """Actualise les parametre du jeu, ou se trouve le curseur, est-ce qu'on clique ?""" + entree=self.entree + while (entree is self.entree) and self.fenetre.open: + self.fenetre.check() + click=self.fenetre.click() + curseur=self.fenetre.point() + entree=(click,curseur) + self.entree=entree + return self.entree + + def afficher(self): + """Affiche tout : le plateau""" + self.fenetre.clear() + self.plateau.afficher(self.fenetre) + self.fenetre.flip() + + def faireTour(self) : + """Faire un tour de jeu""" + self.tour = self.state % self.nombre_joueurs + joueur_actif=self.joueurs[self.tour]#joueur a qui c'est le tour + self.plateau.mouvements=self.plateau.obtenir_mouvements_valides(joueur_actif.side,self.fenetre)#todo pas top + #cfg.debug(self.plateau.mouvements) + self.afficher() + self.state+=1 + if len(self.plateau.mouvements)>=1:#Si des moves sont possibles + choix_du_joueur=joueur_actif.jouer(deepcopy(self.plateau),self.fenetre) + + self.plateau.placer_pion(choix_du_joueur, joueur_actif.side) + else : + #Si aucun mouvement possible on demane l'avis du joueur_actif + pass diff --git a/Othello/TIPE/Player.py b/Othello/TIPE/Player.py new file mode 100755 index 0000000..c5754a3 --- /dev/null +++ b/Othello/TIPE/Player.py @@ -0,0 +1,70 @@ +from copy import deepcopy + +import time +import random +import json +import ia +import config as cfg +import pygame + +# + +class Player: + def __init__(self): + self.choix=None + + +class Robot(Player): + def __init__(self): + Player.__init__(self) + + def jouer(self,plateau,fenetre): + return self.randomPlay(plateau) + #return ia.main(plateau) + + def old_jouer(self,input,plateau,fenetre): + return self.randomPlay(plateau) + + def randomPlay(self,board): + self.choix=random.choice(board.mouvements) + return self.choix + + + + def smartPlay(self,board): + mouvements=board.mouvements + for mouvement in mouvements: + pass + + + + +class Human(Player): + def __init__(self): + Player.__init__(self) + + + def old_jouer(self,input,board,fenetre): + click,cursor=input + if click: + position=board.adjust(cursor,fenetre) + if board.est_dans_grille(position): + if position in board.mouvements: + self.choix=position + return self.choix + + def jouer(self,plateau,fenetre): + while True : + fenetre.check() + cfg.debug(fenetre.point()) + cfg.debug(plateau,bool(pygame.mouse.get_pressed()[0])) + if bool(pygame.mouse.get_pressed()[0]): + cfg.debug("on a clicke") + position=plateau.adjust(fenetre.point(),fenetre)#Donne des coordonnées + cfg.debug("position:",position) + if plateau.est_dans_grille(position): + if position in plateau.mouvements:#On regarde si le clique est une possibilité porpose par le plateau + self.choix=position + break + cfg.debug('while true du joueur huamin pour jouer') + return self.choix diff --git a/Othello/TIPE/board.py b/Othello/TIPE/board.py new file mode 100755 index 0000000..4cfd1e7 --- /dev/null +++ b/Othello/TIPE/board.py @@ -0,0 +1,245 @@ +import mycolors as couleur +import config as cfg + +import pygame + +class Board: + def __init__(self,theme,taille=[8,8]): + """Cree un plateau""" + self.taille=taille + self.createGrid() + self.couleur_grille,self.pieces_couleur,self.mouvements_couleur=theme + self.mouvements=[] + self.gagne=False + self.taille_x, self.taille_y =self.taille + + + def createGrid(self): + """Cree une grille""" + sx,sy=self.taille + self.grille=[[cfg.CASE_VIDE for x in range(sx)] for y in range(sy)] + self.inserer_pion((3,3),0) + self.inserer_pion((3,4),1) + self.inserer_pion((4,3),1) + self.inserer_pion((4,4),0) + + + def est_dans_grille(self,position): + """Verifie si la position est dans la grille""" + sx,sy=self.taille + x,y=position + return (0<=xlen(self.indent_historic): + self.addElementIndentHistoric(i) + if indent=50: + r+=(255-r)*luminosity/100 + g+=(255-g)*luminosity/100 + b+=(255-b)*luminosity/100 + else: + r-=r*luminosity/100 + g-=g*luminosity/100 + b-=b*luminosity/100 + color=r,g,b + return color + + def colorize(self,image, color): + """Return image colorized""" + image = image.copy() + image.fill((0,0,0,255),None,pygame.BLEND_RGBA_MULT) + image.fill(color[0:3]+(0,),None,pygame.BLEND_RGBA_ADD) + return image + + def draw(self): + """Allow user to draw on screen.""" + radius=2 + wavelength=380 + color=self.reverseColor(self.couleur_de_fond) + form=0 + taille=[10,10] + width=0 + while self.open: + self.check() + click=self.click() + position=self.point() + if click: + self.trace(position,taille,self.wavelengthToRGB(wavelength),radius,form,width) + else: + self.hand[0].points=[] + #print(taille) + keys=pygame.key.get_pressed() + if keys[K_LSHIFT] and radius>10: + radius-=1 + if keys[K_RSHIFT] and radius: + radius+=1 + if keys[K_LEFT] and wavelength>380: + wavelength-=1 + if keys[K_RIGHT] and wavelength<780: + wavelength+=1 + if keys[K_q] and taille[0]>0: + taille[0]-=1 + if keys[K_w]: + taille[0]+=1 + if keys[K_e] and taille[1]>0: + taille[1]-=1 + if keys[K_r]: + taille[1]+=1 + if keys[K_s]: + self.screenshot() + if keys[K_t]: + width=(width+1)%2 + if keys[K_SPACE]: + form=(form+1)%4 + print(form) + if keys[K_RETURN]: + self.clear() + self.flip() + + def oldTrace(self,position,color=WHITE,radius=5): + """Trace a point on the screen using position, taille, color.""" + pygame.draw.circle(self.screen,color,position,radius,0) + #print("position: ",position) + + + def trace(self,position,taille,color=WHITE,radius=5,form=0,width=0): + """Trace a point on the screen using position, taille, color.""" + for tool in self.hand: + tool.taille=taille + tool.position=position + tool.points.append(position) + tool.color=color + tool.radius=radius + tool.connect=False + tool.form=form + tool.width=width + tool.draw(self.screen) + #print("position: ",position) + + def wavelengthToRGB(self,wavelength): + """Convert wavelength to rgb color type.""" + gamma,max_intensity=0.80,255 + def adjust(color, factor): + if color==0: return 0 + else: return round(max_intensity*pow(color*factor,gamma)) + if 380<=wavelength<=440: r,g,b=-(wavelength-440)/(440-380),0,1 + elif 440<=wavelength<=490: r,g,b=0,(wavelength-440)/(490-440),1 + elif 490<=wavelength<=510: r,g,b=0,1,-(wavelength-510)/(510-490) + elif 510<=wavelength<=580: r,g,b=(wavelength-510)/(580-510),1,0 + elif 580<=wavelength<=645: r,g,b=1,-(wavelength-645)/(645-580),0 + elif 645<=wavelength<=780: r,g,b=1,0,0 + else: r,g,b=0,0,0 + if 380<=wavelength<=420: factor=0.3+0.7*(wavelength-380)/(420-380) + elif 420<=wavelength<=701: factor=1 + elif 701<=wavelength<=780: factor=0.3+0.7*(780-wavelength)/(780-700) + else: factor=0 + r,g,b=adjust(r,factor),adjust(g,factor),adjust(b,factor) + return (r,g,b) + + def kill(self): + """Quit pygame.""" + pygame.quit() + + def log(self,message): + """Print message with window mention.""" + text="["+self.name+"] "+message + print(text) + + def __del__(self): + """Executed before the window is destroyed.""" + self.log("Window has been closed.") + + +if __name__=="__main__": + w=Window("Game") + #save(w,"grosse fenetre") + #w=load("grosse fenetre") + #print(w.lighten(BLUE)) + #w.alert("test") + w.draw() + w.pause() + w.clear() + w.alert("test2") + w.pause() + w.kill()