Added Othello Game

This commit is contained in:
2019-03-16 15:45:34 +01:00
parent f6ba473a44
commit c76752ae82
36 changed files with 3027 additions and 7 deletions
Vendored
BIN
View File
Binary file not shown.
+126
View File
@@ -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<x<1 and -1<y<1):
break
px=convert(x,[-1,1],[0,wsx])
py=convert(y,[-1,1],[0,wsy])
position=[px,py]
position=self.integer(position)
positions.append(position)
md=1
for i in range(min(len(positions),len(self.positions))):
#print(positions[i],self.positions[i])
x1,y1=positions[i]
x2,y2=self.positions[i]
d=distance(x2-x1,y2-y1)
md=max(d,md)
print(md)
#pygame.draw.circle(self.window.screen,c,positions[i],self.radius,0)
for i in range(min(len(positions),len(self.positions))):
c=self.window.wavelengthToRGB(convert(d,[md,0],[380,780]))
pygame.draw.line(self.window.screen,c,self.positions[i],positions[i],1)
self.delta=0.001/md**10
self.positions=positions[:]
#pygame.draw.lines(self.window.screen,WHITE,0,positions,1)
self.window.flip()
def integer(self,position):
return [int(x) for x in position]
def distance(x,y):
return sqrt(x**2+y**2)
def convert(number,interval1,interval2):
im1,iM1=interval1
im2,iM2=interval2
s=(iM2-im2)/(iM1-im1) #scaling
return (number-im1)*s+im2
if __name__=="__main__":
window=Window()
print(window.inWindow([2,4]))
fx=lambda x,y,t:-x**2+x*t+y
fy=lambda x,y,t:x**2-y**2-t**2-x*y+y*t-x+y
equations=[fx,fy]
chaos=Chaos(window,equations)
chaos()
+18
View File
@@ -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")
+297
View File
@@ -0,0 +1,297 @@
from __future__ import division
from mycolors import *
import pygame
from pygame.locals import *
import time
import json
class Window:
made=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.set()
self.log("Window has been created.")
if build:
self.build()
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.time=time.time()
self.pause_time=0.2
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 press(self):
"""Return all keys."""
return pygame.key.get_pressed()
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 click(self):
"""Return bool value for clicking on screen."""
return bool(pygame.mouse.get_pressed()[0])
def press(self):
"""Return bool value for clicking on screen."""
return pygame.key.get_pressed()
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 inWindow(self,position):
return sum([0<=position[i]<self.size[i] for i in range(len(self.size))])==len(self.size)
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 [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()
BIN
View File
Binary file not shown.
+15
View File
@@ -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#
#-------#
+4 -1
View File
@@ -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)
BIN
View File
Binary file not shown.
+50
View File
@@ -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()
+121
View File
@@ -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()
+49
View File
@@ -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()
+18
View File
@@ -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")
+395
View File
@@ -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)
+14
View File
@@ -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()
+43
View File
@@ -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()
+94
View File
@@ -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))
+10
View File
@@ -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
+72
View File
@@ -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)
+312
View File
@@ -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()
+21
View File
@@ -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
+26
View File
@@ -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))
+8
View File
@@ -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()
+176
View File
@@ -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):","(",")"))
+2 -4
View File
@@ -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
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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))])
+104
View File
@@ -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
+70
View File
@@ -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
+245
View File
@@ -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<=x<sx and 0<=y<sy)
def est_un_coin(self, position):
x,y=position
sx,sy=self.taille
x_=x%(sx-1)
y_=y%(sy-1)
return (x_, y_)==(0,0)
def adjust(self,position_brute,fenetre):
"""Converti les coordonnees du curseur pour obtenir les coordonnees de la case selectionnee"""
wsx,wsy=fenetre.taille
sx,sy=self.taille
rx,ry=position_brute
return (int(rx*sx/wsx),int(ry*sy/wsy))
def testVictoire(self):
"""Test la victoire."""
compteur=cfg.CASE_VIDE
for colonne in self.grille:
compteur+=colonne.count(cfg.CASE_VIDE)
self.gagne=(compteur==cfg.CASE_VIDE)
return self.gagne
def getPieces(self,side):
"""Recup toute les position de toues les piece d'un joueur"""
positions=[]
sx,sy=self.taille
for y in range(sy):
for x in range(sx):
case = self.obtenir_case((x,y))
if case==side:
positions.append((x,y))
return positions
def getAround(self,positions):
"""Prend en parametre une liste de position de case et retourne la liste des postions des cases vide se trouvant juste à cote"""
environment=[]
around=[(x,y) for x in range(-1,2) for y in range(-1,2) if (x,y)!=(0,0)]
for position in positions:
px,py=position
for step in around:
stx,sty=step
x,y=(px+stx,py+sty)
if self.est_dans_grille((x,y)):
if self.est_une_case_vide((x,y)) :
environment.append((x,y))
return environment
def inserer_pion(self, coordonnees, side) :
"""inserer_pion insere un pion dans la grille sans se soucier de conquerir le territoire"""
x,y=coordonnees
self.grille[y][x]=side
def reverse_pion(self, coordonnees) :
"""Retourne le pion se trouvant au coordonnees"""
#Todo pour marc : faire cette foction
#Utiliser cette methode dans la methode 'conquer'
pass
def obtenir_case(self, coordonnees) :
"""Retourn le contenu d'une case"""
x,y=coordonnees
return self.grille[y][x]
def placer_pion(self,coordonnees_pion,side):
"""place un pion sur le plateau"""
self.inserer_pion(coordonnees_pion, side)
self.conquerir(coordonnees_pion,side)
def est_une_case_vide(self, position) :
return self.obtenir_case(position)==cfg.CASE_VIDE
def obtenir_mouvements_valides(self,joueur_side,fenetre):
"""Retourne une liste de tuple qui correspondent aux coordonnées des mouvements possibles pour le joueur_side"""
ennemi_side=1-joueur_side
positions=self.getPieces(ennemi_side)
positions=self.getAround(positions)
mouvements=[]
for position in positions:
if self.est_mouvement_valide(position,joueur_side):
mouvements.append(position)
return mouvements
def est_mouvement_valide(self,position,p_side):
"""Permet de verifier si un mouvement est valide"""
vecteurs=[(x,y) for x in range(-1,2) for y in range(-1,2) if (x,y)!=(0,0)]
resultat=False
for vecteur in vecteurs:
ligne=self.recuperer_ligne(vecteur,position)
if self.est_mouvement_valide_dans_ligne(p_side,ligne):
resultat=True
break
return resultat
def est_mouvement_valide_dans_ligne(self,p_side,ligne):
"""Permet de verifier si un mouvement est valide dans une ligne"""
e_side=1-p_side
valide=True
possible=False
for position in ligne:
if not self.est_dans_grille(position):
break
case=self.obtenir_case(position)
if case==e_side:
possible=True
elif case==p_side and possible:
valide=True
break
else: #Dans ce case la case est vide
break
return valide
def conquerir(self,position,p_side):
"""Permet au nouveau pion à la position 'position' de couleur 'side' de
retouner les autres pions"""
vecteurs=[(x,y) for x in range(-1,2) for y in range(-1,2) if (x,y)!=(0,0)]
for vecteur in vecteurs:
ligne=self.recuperer_ligne(vecteur,position)
self.conquerir_ligne(p_side,ligne)
def recuperer_ligne(self,position,vecteur):
"""Recupere la ligne des valeurs obtenue avec une position et un vecteur."""
line=[]
vx,vy=vecteur
x,y=position
while self.est_dans_grille((x,y)):
x+=vx
y+=vy
line.append((x,y))
return line
def conquerir_ligne(self,p_side,ligne):
"""Permet au nouveau pion a la position position de couleur side de
retouner les autres pions dans une ligne"""
e_side=1-p_side
mangeables=[]
for position in ligne:
if not self.est_dans_grille(position):
break
case=self.obtenir_case(position)
if case==e_side:
mangeables.append(position)
elif case==p_side:
self.manger(mangeables,p_side)
break
else: #Dans ce case la case est vide
break
def manger(self,mangeables,personne):
"""Assigne aux cases mangeables la valeur de pion de la personne"""
for mangeable in mangeables:
self.inserer_pion(mangeable,personne)
def afficher(self,fenetre):
self.showGrid(fenetre)
self.showPieces(fenetre)
self.showMoves(fenetre)
def debugMove(self,position,fenetre,couleur):
#fenetre.clear()
#self.afficher(fenetre)
#self.showMove(position,fenetre,couleur)
#fenetre.flip()
#fenetre.pause()
pass
def showMove(self,move,fenetre,couleur):
wsx,wsy=fenetre.taille
sx,sy=self.taille
radius=int(min(wsx,wsy)/min(sx,sy)/4)
x,y=move
raw_position=(int((x+1/2)*wsx/sx),int((y+1/2)*wsy/sy))
pygame.draw.circle(fenetre.screen,couleur,raw_position,radius,0)
def showMoves(self,fenetre):
for move in self.mouvements:
self.showMove(move,fenetre,self.mouvements_couleur)
def colorer_case(postion, couleur) :
"""permet de colorer une case du plateau d'une certaine couleur
cette fonction est utile pour debug de ia.py"""
pass
def showGrid(self,fenetre):
"""Affiche la grille"""
wsx,wsy=fenetre.taille
sx,sy=self.taille
for y in range(sy):
_y=y*wsy//sy
start=(0,_y)
end=(wsx,_y)
pygame.draw.line(fenetre.screen,self.couleur_grille,start,end,1)
for x in range(sx):
_x=x*wsx//sx
start=(_x,0)
end=(_x,wsy)
pygame.draw.line(fenetre.screen,self.couleur_grille,start,end,1)
def showPieces(self,fenetre):
"""Affiche les pions"""
wsx,wsy=fenetre.taille
sx,sy=self.taille
radius=int(min(wsx,wsy)/min(sx,sy)/2)
for y in range(sy):
for x in range(sx):
case=self.obtenir_case((x,y))
raw_position=(int((x+1/2)*wsx/sx),int((y+1/2)*wsy/sy))
if 0<=case and case<=len(self.pieces_couleur)-1 :
couleur=self.pieces_couleur[case]
pygame.draw.circle(fenetre.screen,couleur,raw_position,radius,0)
+9
View File
@@ -0,0 +1,9 @@
#CASES=[0,1]
CASE_VIDE=-1#Ne pas mettre 0 ou 1
DEBUGING=True
def debug(*txt) :
if DEBUGING :
print(*txt)
+9
View File
@@ -0,0 +1,9 @@
import board
from converter import Converter
print(Converter(board.Board.conquerir_ligne)())
print(Converter(board.Board.est_mouvement_valide_dans_ligne)())
#puissance=lambda x:2**int(math.log(x)/math.log(2))
#print(Converter(puissance)())
+260
View File
@@ -0,0 +1,260 @@
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)
print(lines)
output = []
lines = lines.split("\n")
lines=removeUselessIndent(lines)
lines=Converter(lines)
for line in lines:
output.append(Converter(line)())
#print("output: ",output)
return "\n".join(output)
class Converter:
def __init__(self,name):
self.name=name
self.code=inspect.getsource(name)
print(self.code)
self.lines=self.code.split("\n")
self.indent_historic=[]
self.indent=0
self.cleanCode()
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,"import",None], ["DEPUIS",None,"IMPORTER",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]],
"lambda": [[None,"lambda",None,":",None], [None,":\nDONNEES: ",None," :\nRENVOIE",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"]],
"True": [[None,"True",None], [None,"VRAI",None]],
"False": [[None,"False",None], [None,"FAUX",None]],
"==": [[None,"==",None], [None,"=",None]],
"!=": [[None,"!=",None], [None,"≠",None]],
"=": [[None,"=",None], [None," <- ",None]],
"append": [[None,".append(",None,")"], ["AJOUTER A ",None," LA VALEUR ",None]],
"not": [[None,"not",None], [None,"NON",None]]}
def cleanCode(self):
self.cleanIndents()
def cleanIndents(self):
self.line=self.lines[0]
count=self.countIndent(self.line)
for i in range(len(self.lines)):
self.lines[i]=self.lines[i][4*count:]
def trackIndent(self,i):
print(i)
indent=self.countIndent(self.lines[i])
if indent>len(self.indent_historic):
self.addElementIndentHistoric(i)
if indent<len(self.indent_historic):
self.delElementIndentHistoric(i)
print("i:",i)
print("self.lines[i]:",self.lines[i])
print("indent:",indent)
print("historic:",self.indent_historic)
print("")
self.indent=indent
self.removeIndent(i)
#self.indent_historic.append()
def addElementIndentHistoric(self,i):
l={ " while ":" TANT QUE ",
" for ": " POUR ",
" if ": " SI "}
for e in l:
if e in self.lines[i]:
self.indent_historic.append(l[e])
print(self.lines[i])
print(e)
print(e in self.lines[i])
def delElementIndentHistoric(self,i):
print(len(self.lines))
print(i+1)
self.lines[i]+="\n"+" "*4*(self.countIndent(self.lines[i+1])+1)+"FIN "+self.indent_historic[-1]
del self.indent_historic[-1]
def countIndent(self,line):
i=0
for i in range(len(line)):
if line[i]!=" ":
break
return int(i/4)
def removeIndent(self,i):
count=self.countIndent(self.lines[i])
self.line=self.line[count*4:]
def removeCommentaries(self):
self.commentaries=""
if "#" in self.line:
i=self.next(self.line,"#")
self.commentaries=self.line[i:]
self.line=self.line[:i]
if "\"\"\"" in self.line:
i=self.next(self.line,"\"\"\"")
self.commentaries=self.line[i:]
self.line=self.line[:i]
def convert(self):
breaking=False
for key in self.conversion:
if key=="==":
breaking=True
if key in self.line:
self.apply(key)
if breaking:
break
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 assemble(self):
pass
def __call__(self):
for i in range(len(self.lines)):
if i<len(self.lines)-1:
self.trackIndent(i)
self.indent=self.countIndent(self.lines[i])
self.line=self.lines[i]
self.removeCommentaries()
self.convert()
self.lines[i]= " "*4*self.indent+self.line+" "+self.commentaries
self.cleanCode()
l1,l2=self.lines[0].split("\n")
l1="ALGORITHME: "+l1.upper() +"\n\n"
self.lines[0]=l1+l2
return "\n".join(self.lines)
if __name__=="__main__":
print(Converter(test)())
#c=Converter("def test(arg1,arg2):")
#print(c.between("def test(arg1,arg2):","(",")"))
+35
View File
@@ -0,0 +1,35 @@
ZONE_COIN=0
ZONE_BORD=1
ZONE_ROUGE=2
ZONE_MORT=3
ZONE_BLANCHE=4
PLATEAU_COLORE=[[ZONE_COIN,ZONE_MORT, ZONE_BORD, ZONE_BORD, ZONE_BORD, ZONE_BORD,ZONE_MORT, ZONE_COIN],
[ZONE_MORT,ZONE_MORT,ZONE_ROUGE,ZONE_ROUGE,ZONE_ROUGE,ZONE_ROUGE,ZONE_MORT,ZONE_MORT],
[ ZONE_BORD,ZONE_ROUGE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE,ZONE_ROUGE, ZONE_BORD],
[ ZONE_BORD,ZONE_ROUGE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE,ZONE_ROUGE, ZONE_BORD],
[ ZONE_BORD,ZONE_ROUGE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE,ZONE_ROUGE, ZONE_BORD],
[ ZONE_BORD,ZONE_ROUGE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE, ZONE_BLANCHE,ZONE_ROUGE, ZONE_BORD],
[ZONE_MORT,ZONE_MORT,ZONE_ROUGE,ZONE_ROUGE,ZONE_ROUGE,ZONE_ROUGE,ZONE_MORT,ZONE_MORT],
[ ZONE_COIN,ZONE_MORT, ZONE_BORD, ZONE_BORD, ZONE_BORD, ZONE_BORD,ZONE_MORT, ZONE_COIN]]
class IA() :
def __init__(self, plateau):
self.plateau=plateau
def obtenir_couleur_position(position):
#"""Retourne si coin, zone blanche etc..."""
positions_bord=[(1,0),(self.plateau.taille_x-2,0),
(0,1),(1,1),(self.plateau.taille_x-2,1), (self.plateau.taille_x-1,1),
(0,self.plateau.taille_y-2),(1,self.plateau.taille_y-2), (self.plateau.taille_x-2,self.plateau.taille_y-2),(self.plateau.taille_x-1,self.plateau.taille_y-2),
(1,self.plateau.taille_y-1),(self.plateau.taille_x-2,self.plateau.taille_y-1)
]
return PLATEAU_COLORE[postion[0]][postion[1]]
def main(plateau_objet):
"""fonction obligatoire dans ia.py"""
+20
View File
@@ -0,0 +1,20 @@
import Othello
import mywindow
import Player as Joueur
"""
TOdo :
FAire API pour IA avec des fonctions 'basique' comme :
Replacer les grille[y][x] par des grille[x][y]
Faire la metohde colorer_case dans board.py
Pour marc :
"""
if __name__=="__main__":
fenetre=mywindow.Window([800,800],set=False)
jeu=Othello.Othello(fenetre, [Joueur.Human(),Joueur.Human()])
#jeu=Othello.Othello(fenetre, [Joueur.Robot(),Joueur.Robot()])
jeu()
+26
View File
@@ -0,0 +1,26 @@
BLEU = ( 0, 0,255)
ROUGE = (255, 0, 0)
VERT = ( 0,255, 0)
NOIR = ( 0, 0, 0)
BLANC = (255,255,255)
JAUNE = (255,255, 0)
VIOLET = (100, 0,100)
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")
+376
View File
@@ -0,0 +1,376 @@
from __future__ import division
from mycolors import *
import pygame
from pygame.locals import *
import time
import json
class Window:
made=0
def __init__(self,name="Unnamed Game",taille=[700,600],text_font="monospace",text_size=65,text_color=WHITE,background_color=BLACK,fullscreen=False,set=True):
"""Create a window object using name, taille text_font, text_size, text_color, background and set."""
Window.made+=1
self.number=Window.made
self.name=name
self.taille=taille
self.text_font=text_font
self.taille_du_texte=text_size
self.text_color=text_color
self.couleur_de_fond=background_color
self.fullscreen=fullscreen
self.load()
if set:
self.set()
def load(self):
"""Load builtins attributs of window object."""
self.RIGHT = 0
self.UP = 1
self.LEFT = 2
self.DOWN = 3
if self.taille is None:
self.taille=(self.info.current_w//2,self.info.current_h//2)
#self.mouse_position=pygame.mouse.get_pos()
#self.mouse_click=bool(pygame.mouse.get_pressed()[0])
self.selecter_color=self.reverseColor(self.couleur_de_fond)
self.pausing=False
self.open=False
self.coordonnates=[0,0]+self.taille
self.picture_saved=0
self.pause_cool_down=1
self.time=time.time()
def set(self):
"""Creates apparent window."""
self.log("Window has been created.")
pygame.init()
self.info = pygame.display.Info()
self.font = pygame.font.SysFont(self.text_font, self.taille_du_texte)
if self.fullscreen:
self.screen=pygame.display.set_mode(self.taille,FULLSCREEN)
else:
self.screen=pygame.display.set_mode(self.taille,RESIZABLE)
pygame.display.set_caption(self.name)
self.clear()
self.flip()
self.open=True
def clear(self,color=None):
"""Clear to background color."""
if color is None:
color=self.couleur_de_fond
self.screen.fill(color)
def scale(self,picture,taille):
"""Return scaled picture using picture and taille."""
return pygame.transform.scale(picture,taille)
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."""
self.pausing=True
while self.pausing and self.open:
self.check()
keys=pygame.key.get_pressed()
if keys[K_SPACE]:
self.pausing=False
if self.open:
time.sleep(0.1)
def sleep(self,waiting_time): #useless
"""Wait for giving time."""
import time
time.sleep(waiting_time)
def press(self):
"""Return all keys."""
return pygame.key.get_pressed()
def direction(self):
"""Return keys for arrows pressed. Trigonometric orientation is used."""
keys=pygame.key.get_pressed()
if keys[K_LEFT]:
left=True
else:
left=False
if keys[K_RIGHT]:
right=True
else:
right=False
if keys[K_UP]:
up=True
else:
up=False
if keys[K_DOWN]:
down=True
else:
down=False
return (right,up,right,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 click(self):
"""Return bool value for clicking on screen."""
return bool(pygame.mouse.get_pressed()[0])
def press(self):
"""Return bool value for clicking on screen."""
return pygame.key.get_pressed()
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,taille=None):
sx,sy=self.taille
if taille is None:
taille=self.taille_du_texte
l=len(message)
letter_size=taille/4
x=sx//2-letter_size*l//2
y=sy//2-taille/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,taille=None,color=None,couleur_de_fond=None,font=None):
"""Display text on screen using position, taille, color and font."""
sx,sy=taille
x,y=position
pygame.draw.rect(self.screen,self.reverseColor(couleur_de_fond),position+taille,0)
pygame.draw.rect(self.screen,couleur_de_fond,(x+1,y+1,sx-2,sy-2),0)
if taille is None:
taille=self.taille_du_texte
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.taille
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 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()