Пример #1
0
 def shape(self):
     """
     Returns the `Shape` associated to self. Namely, it "forgets" the labels of the leafs.
     :return: `Shape` instance.
     """
     if self.is_leaf:
         return Shape(None)
     else:
         return Shape([x.shape() for x in self.children])
Пример #2
0
    def start(self, sides, centre=True):
        """

        Starts with a polygon, optionally connected to the centre

        """

        self.shapes = []

        self.points = []

        self.symetry = sides

        if sides < 3:

            raise "At least 3 sides are required"

        dt = math.pi / sides

        self.points = [
            SPoint.SPoint(math.cos(i * dt), math.sin(i * dt))
            for i in range(1, 2 * sides, 2)
        ]

        if centre:

            self.points.append(SPoint.SPoint(0, 0))

            for i in range(sides):

                s = Shape.Shape()

                s.addPoint(self.points[i])

                s.addPoint(self.points[(i + 1) % sides])

                s.addPoint(self.points[sides])

                self.shapes.append(s)

        else:

            s = Shape.Shape()

            for i in range(sides):

                s.addPoint(self.points[i])

            self.shapes.append(s)

        self.findLines()
Пример #3
0
    def assemblePoints(self, p1, p2, p11, p12, p21, p22):
        """

        Common part of the two expand functions

        """

        new_s1 = Shape.Shape()

        new_s2 = Shape.Shape()

        new_s3 = Shape.Shape()

        new_s1.addPoint(p1)

        new_s1.addPoint(p11)

        new_s1.addPoint(p12)

        new_s2.addPoint(p11)

        new_s2.addPoint(p12)

        new_s2.addPoint(p22)

        new_s2.addPoint(p21)

        new_s3.addPoint(p2)

        new_s3.addPoint(p21)

        new_s3.addPoint(p22)

        self.new_shapes.append(new_s1)

        self.new_shapes.append(new_s2)

        self.new_shapes.append(new_s3)

        # Add the new points to our list

        self.addPoint(p11)

        self.addPoint(p12)

        self.addPoint(p21)

        self.addPoint(p22)
Пример #4
0
 def merge_shapes(self,slist,merged_name,replace=True):
     """
     Merges a set of shapes, by taking the average of their points.
     
     Args
         slist is a python list of the ShapeSet.shapes keys of the Shapes to
         merge.
         merged_name is a name of the merged Shape that will be added to the
         dataset.
         replace: if True, the original shapes will be removed from the 
         ShapeSet (default), if False, they will be left in
     
     The ShapeSet must be aligned before merging.
     
     Missing landmarks (with nan coordinates) will be ignored for 
     calculating the average of that landmark.
     """
     if self.__is_aligned__==False:
         raise Exception("ShapeSet must be aligned before shapes can be merged.")
     if len(slist)<2:
         raise Exception("Must be at least two shapes in slist to merge.")
     mean_lms = np.nanmean(np.array([self.shapes[i].landmarks for i in slist]), axis=0)
     merged_shape = Shape.Shape(data = mean_lms.tolist(),shape_name=merged_name)
     if replace==True:
         for s in slist:
             self.shapes.pop(s)
             self.n_shapes = self.n_shapes-1
     self.append_shape(merged_shape)
Пример #5
0
def estimate_from_symmetry(shape, lm_pairs, **kwargs):
    """
    Estimates missing landmarks by reflecting through a plane of symmetry.
    
    Args:
        shape is a Shape object.
        lm_pairs is a list of lists/tuples of pairs of integers that specify
        which points are pairs.
        
        In addition either plane or midpoints needs to be specified.
        plane : a list of four numbers specifying a plane
        midpoints : a list of the integer indices of the landmarks that lie on
        the plane of symmetry.
    """
    assert ('plane' in kwargs.keys() or 'midpoints' in kwargs.keys())
    if 'plane' in kwargs.keys():
        plane = kwargs['plane']
    else:
        mid_lms = []
        for idx, lm in enumerate(shape.landmarks):
            if idx in kwargs['midpoints']:
                mid_lms.append(lm)
        plane = linear.fit_plane(mid_lms)
    new_lms = shape.landmarks
    for idx, p in enumerate(shape.landmarks):
        if __point_present__(p) == False:
            opp = __opposite_lm__(idx, lm_pairs)
            if opp != -1 and __point_present__(shape.landmarks[opp]) == True:
                new_lms[idx] = __symm_point__(shape.landmarks[opp], plane)
    filled_shape = Shape.Shape(data=new_lms,
                               shape_name=shape.name,
                               lm_names=shape.lm_names)
    return filled_shape
Пример #6
0
    def getDual(self):
        """

        Return the dual of this pattern

        """

        dual = SPattern()

        for pt in self.points:

            shape = Shape.Shape()

            if len(pt.shapes) == len(pt.lines):

                for s in pt.shapes:

                    s.findCentre()

                    newpt = dual.findPoint(s.centre)

                    shape.addPoint(newpt)

                shape.sortPoints()

                dual.shapes.append(shape)

        dual.findLines()

        return dual
Пример #7
0
def kmeans_D2():
    ''' Was used to do kmeans on GPS-D2 '''
    l_d2 = []

    list_files = [
        "camel-collapse/camel-collapse-01.obj",
        "camel-gallop/camel-gallop-01.obj", "cat-poses/cat-01.obj",
        "elephant-gallop/elephant-gallop-01.obj",
        "elephant-poses/elephant-01.obj", "face-poses/face-01-anger.obj",
        "head-poses/head-01-anger.obj",
        "horse-collapse/horse-collapose-01.obj",
        "horse-gallop/horse-gallop-01.obj", "horse-poses/horse-01.obj",
        "lion-poses/lion-01.obj"
    ]
    list_shapes = []

    for name in list_files:
        t = time.time()
        list_shapes.append(Shape(name))
        list_shapes[-1].compute_D2(k=20, N=50000, nb_cases=3, m=5)
        l_d2.append(list_shapes[-1].histogram)
        list_shapes[-1].clear()
        print("Computed D2-distrib for ", name, "in ", time.time() - t)

    print("Training k-means")
    kmeans = KMeans(init='k-means++', n_clusters=2, n_init=100)
    kmeans.fit(l_d2)
    print("Trained.")

    for i in range(len(list_files)):
        print("File ", list_files[i], "is associated to cluster ",
              kmeans.predict(l_d2[i].reshape(1, -1)))
Пример #8
0
def estimate_from_mean(shapeset, shapes=None):
    """
    Estimates missing landmarks in a ShapeSet from present values in other 
    specimens.
    
    Args:
        shapeset: the ShapeSet to be filled.
        shapes: an optional list of Shapes to have missing data imputed for. 
        If left as the default (None), then any taxa with missing data will be 
        estimated.
    
    Note: the shapeset must be aligned before using this function.
    """
    assert (shapeset.__is_aligned__ == True)
    mean_vals = np.nanmean(shapeset.__kmn__(typeof='np_array'),
                           axis=0).tolist()
    new_shapeset = ShapeSet.ShapeSet(shapeset_name=shapeset.name)
    if shapes == None:
        shapes = shapeset.shapes.keys()
    for t in shapeset.shapes.keys():
        new_data = np.array(shapeset.shapes[t].landmarks)
        for idx, lm in enumerate(shapeset.shapes[t].landmarks):
            if __point_present__(lm) == False:
                new_data[idx] = mean_vals[idx]
        new_shape = Shape.Shape(data=new_data.tolist(), shape_name=t)
        new_shapeset.append_shape(new_shape)
    return new_shapeset
Пример #9
0
def kmeans_Shape_DNA():
    ''' Was used to do kmeans on Shape DNA '''
    l_eig = []

    list_files = [
        "camel-poses/camel-01.obj",
        "camel-poses/camel-02.obj",
        "camel-poses/camel-03.obj",
        #"flamingo-poses/flam-04.obj", "flamingo-poses/flam-02.obj", "flamingo-poses/flam-03.obj", #buggy
        "lion-poses/lion-01.obj",
        "lion-poses/lion-02.obj",
        "lion-poses/lion-03.obj",
    ]
    list_shapes = []

    for name in list_files:
        t = time.time()
        list_shapes.append(Shape(name))
        list_shapes[-1].compute_shape_dna(10)
        l_eig.append(list_shapes[-1].eigenvalues)
        list_shapes[-1].clear()
        #print(l_eig[-1])
        print("Computed shape DNA for ", name, "in ", time.time() - t)

    print("Training k-means")
    kmeans = KMeans(init='k-means++', n_clusters=2, n_init=100)
    kmeans.fit(l_eig)
    print("Trained.")

    for i in range(len(list_files)):
        print("File ", list_files[i], "is associated to cluster ",
              kmeans.predict(l_eig[i].reshape(1, -1)))
def __detect_shape(img, height, width, shape):
    """
    The process to detect the shape.

    It detects the number of shape's edges. If a shape has 3 edges, it's a triangle.

    Parameters
    ----------
    img : numpy.ndarray
        The image whose shapes we want to detect
    height : int
        Image's height
    width : int
        Image's width
    shape : Shape
        The shape we want to detect
    Returns
    -------
    detected : Shape
        The detected shape
    last_cont : numpy.ndarray
        Contours of the shape.
    detected_shapes : list
        The detected shapes.
    center : tuple of float
        Center of the detected shape.
    angle : float
        Angle of rotation of the detected shape.
    """
    font = cv2.FONT_HERSHEY_SIMPLEX
    contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    hull_list = __convex_hull(contours)
    minimal_area = 200
    maximal_area = (height * width) - 2000
    detected = None
    detected_shapes = []
    last_cont = np.array([])
    center = None
    angle = None
    for cont in hull_list:
        area = cv2.contourArea(cont)
        #continue if area is too small(noise) or too big
        if area < minimal_area or area >= maximal_area:
            continue
        approx = __approx_poly(cont, img)
        detected = __check_partial(detected, approx, width, height)
        if detected != Shape.Shape.PARTIAL.value:
            detected = __check_non_partial_shape(cont, area, approx)
        shape_name = Shape.Shape(detected).name
        detected_shapes.append(shape_name)
        if shape == Shape.Shape.ALL.value or detected == shape:
            x = cont[0][0][0]  #x value of a point of the shape
            y = cont[0][0][1]  #y value of a point of the shape
            cv2.putText(img, shape_name, (x, y), font, 0.5, (255))
            if detected == shape:
                last_cont = approx
                center, _, angle = cv2.minAreaRect(cont)
                break
    return detected, last_cont, detected_shapes, center, angle
Пример #11
0
def read(filepath, filetype="Landmark.exe", shapename=None):
    if shapename == None:
        shapename == filepath
    if filetype == "Landmark.exe":
        n, p = __parse_landmarkexe__(filepath)
        return Shape.Shape(data=p, shape_name=shapename, lm_names=n)
    else:
        raise Exception("Trying to import an unknown file type: %s" % filepath)
Пример #12
0
 def __init__(self, p, v, ttl, size):
     self.ttl = ttl
     s = [(-size, -size, size, size, None),
          (-size, size, size, -size, None)]
     self.shape = Shape(s)
     WorldObject.__init__(self, OBJECT_TYPE_NONE, p, 0, v, 0)
     if random.random() < .5:
         self.spin = 5
     else:
         self.spin = -5
Пример #13
0
def push_and_close():
    i = 0
    while i < len(temporary_shapes):
        if len(temporary_shapes[i].new_entries) != 0:
            temporary_shapes[i].push_entries()
        else:
            temporary_shapes[i].close_entries()
            shapes_list.append(Shape(temporary_shapes[i].point_list))
            del temporary_shapes[i]
            i -= 1
        i += 1
Пример #14
0
    def __init__(self, signal):
        self.signal = signal
        self.curX = 0
        self.curY = 0
        self.curShape = Shape()  # 当前Shape
        self.isCurShapeDropped = False  # 当前shape是否落下完成
        self.board = []  # 游戏区域  Col * Row

        self.num_lines_removed = 0  # 消除的行数

        self.clear_board()
Пример #15
0
    def __init__(self, parent, dummy=False, maxTick=-1, train=False):
        #print("Board called")
        self.isdummy = dummy
        self.maxTick = maxTick
        self.istrain = train

        # if dummy, don't make the window.
        if not dummy:
            wx.Panel.__init__(self, parent, style=wx.WANTS_CHARS)
            self.verbose = True
            self.visualize = True
        else:
            self.verbose = False
            self.visualize = False

        # 1. initiate timer for timer.
        if (not self.isdummy) and (not self.istrain):
            self.timer = wx.Timer(self, Board.ID_TIMER)

        # 2. bind event handlers.
        if (not self.isdummy) and (not self.istrain):
            self.Bind(wx.EVT_PAINT, self.OnPaint)
            self.Bind(wx.EVT_TIMER, self.OnTimer, id=Board.ID_TIMER)

        # 3. pointers to Current Piece and the next Piece
        self.curPiece = Shape()
        self.nextPiece = Shape()
        self.next2Piece = Shape()
        self.next3Piece = Shape()
        self.next4Piece = Shape()
        self.next5Piece = Shape()

        # 4. initBoard()
        self.initBoard()
Пример #16
0
 def __init__(self):
     s = [(-5, 5, 10, 0, None), (-5, -5, 10, 0, None),
          (-5, -5, -5, 5, None)]
     self.shape = Shape(s)
     self.fireCannon = False
     self.fireTorpedo = False
     self.rounds = 50.0
     self.fuel = 50.0
     self.torpedos = 50.0
     self.torpedoDelay = 0
     WorldObject.__init__(self, OBJECT_TYPE_SHIP,
                          Point(SCREEN_WIDTH * .75, SCREEN_HEIGHT / 2), PI,
                          None, 7, SHIP_MASS)
Пример #17
0
    def nextpiece(self):
        self.curPiece, self.nextPiece, self.next2Piece, self.next3Piece, self.next4Piece = \
         (self.nextPiece, self.next2Piece, self.next3Piece, self.next4Piece, self.next5Piece)
        self.next5Piece = Shape()
        newShape = self.newPiece()
        self.next5Piece.setShape(newShape)

        self.curX = Board.BoardWidth // 2 + 1
        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()

        #when cannot place new piece, GAME OVER !
        if not self.tryMove(self.curPiece, self.curX, self.curY):
            self.game_over()
Пример #18
0
    def startGrid(self, n):
        """

        Starts with a square grid, n x n

        """

        self.shapes = []

        self.points = []

        self.symetry = 4

        if n < 1:

            raise "At least 1 square is required"

        for i in range(n + 1):

            for j in range(n + 1):

                self.points.append(SPoint.SPoint(i, j))

        for i in range(n):

            for j in range(n):

                s = Shape.Shape()

                pos = (n + 1) * i + j

                s.addPoint(self.points[pos])

                s.addPoint(self.points[pos + 1])

                s.addPoint(self.points[pos + n + 2])

                s.addPoint(self.points[pos + n + 1])

                self.shapes.append(s)

        self.findLines()
Пример #19
0
    def evaluate_opening(self):

        res = 0
        black = 0
        white = 0

        territory = Territory.Territory(self._board, self._black_moves,
                                        self._white_moves, self._black_goban,
                                        self._white_goban)
        shape = Shape.Shape(self._board, self._black_moves, self._white_moves,
                            self._black_goban, self._white_goban)

        for move in self._black_moves:
            ufcoord = Goban.Board.name_to_coord(move)
            x = ufcoord[0]
            y = ufcoord[1]

            if (1 <= x <= 7) and (
                    1 <= y <=
                    7):  # pierres sur la deuxième ligne pour l'ouverture
                black = black + 3000

        for move in self._white_moves:
            ufcoord = Goban.Board.name_to_coord(move)
            x = ufcoord[0]
            y = ufcoord[1]

            if (1 <= x <= 7) and (
                    1 <= y <=
                    7):  # pierres sur la deuxième ligne pour l'ouverture
                white = white + 3000

        # On maximise le nombre de territoires cardinaux conquéris
        black = black + territory.count_territories_black()
        white = white + territory.count_territories_white()

        if self._mycolor == Goban.Board._BLACK:
            res = black - white
        else:
            res = white - black

        return res
Пример #20
0
def initSim(nbobj, rad, pos1):
    # créé le sol
    p.createCollisionShape(p.GEOM_PLANE)
    basePlane = p.createMultiBody(0, 0)
    # met une seed au rng
    random.seed(time.time())
    # random.seed("Thibault")
    # créé la sphere qui sera le point centrale de la "Shape"
    nbPop = 100
    pop = []
    for i in range(0, nbPop - 1):
        body = p.createCollisionShape(p.GEOM_SPHERE, radius=rad * 4)
        temp = s.Shape(body, pos1)
        temp.createRandom(nbobj, rad)
        idtmp = temp.createBody()
        pop.append(temp)

        pop[i].setId(idtmp)

    for i in range(-1, nbobj):
        for j in range(-1, nbobj):
            for elem1 in range(0, nbPop - 1):
                for elem2 in range(elem1 + 1, nbPop - 1):
                    p.setCollisionFilterPair(pop[elem1].getId(),
                                             pop[elem2].getId(), i, j, 0)
        print((i + 2) / (nbobj + 1))

    # ==========================================================
    # Truc lié a la simulation
    # ==========================================================
    for elem in pop:
        for i in range(0, nbobj):
            p.setJointMotorControl2(bodyUniqueId=elem.getId(),
                                    jointIndex=i,
                                    controlMode=p.VELOCITY_CONTROL,
                                    targetVelocity=random.randint(0, 3))

    # met la gravité
    p.setGravity(0, 0, -9.81)

    return pop
Пример #21
0
    def getCopy(self):

        copy = SPattern()

        for shape in self.shapes:

            newshape = Shape.Shape()

            for pt in shape.points:

                newpt = copy.findPoint(pt)

                newshape.addPoint(newpt)

            newshape.sortPoints()

            copy.shapes.append(newshape)

        copy.findLines()

        return copy
Пример #22
0
from Shape import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
import sys
import time

DEBUG = True

shape = Shape()
SCALE = 500
FPS = 100
RATE = 1


# Specify the color and the dimension of the window
def init():
    glClearColor(1.0, 1.0, 1.0, 0.0)
    gluOrtho2D(-1.0, 1.0, -1.0, 1.0)


# Take a matrix of input and add it into Shape object
def input_matrix():
    global shape
    print('Enter the number of point: ')
    number_of_points = int(input())
    for i in range(number_of_points):
        shape.add_point(input())

    glutDisplayFunc(draw_plane)
Пример #23
0
def procrustes_align(shapes):
    shape_set = shapes.shapes
    ### Separate into complete and incomplete
    complete = {}
    incomplete = {}
    for shape in shape_set.keys():
        missing = False
        for point in shape_set[shape].landmarks:
            try:
                if np.isnan(point).any():
                    missing = True
                    break
            except TypeError:
                raise Exception("Unknown datatype in landmarks. Cannot align.")
        if missing == True:
            incomplete[shape] = shape_set[shape].landmarks
        else:
            complete[shape] = shape_set[shape].landmarks
    
    ### Align the complete shapes
#    print complete.keys()
    aligned, consensus = gpa(complete)
    
    ### Align each incomplete shape to the complete shape consensus shape
    for shape in incomplete.keys():
        ### Make subset of shape and consensus with points that are present
        points_existing = [1 for i in xrange(len(incomplete[shape]))]
        for i, point in enumerate(incomplete[shape]):
            if np.isnan(point).any():
                points_existing[i] = 0
        sub_consensus = []
        sub_incomplete = []
        for i, presence in enumerate(points_existing):
            if presence == 1:
                sub_consensus.append(list(consensus[i]))
                new_p = []
                for val in incomplete[shape][i]:
                    new_p.append(float(val))
                sub_incomplete.append(new_p)
        sub_consensus = np.array(sub_consensus)
        sub_incomplete = np.array(sub_incomplete)
        scale_factor = __centroid_size__(sub_consensus)
        aligned_incomplete = __rotate__(__reposition__(sub_consensus), __rescale__(__reposition__(sub_incomplete), scale=scale_factor))
        
        ### Calculate translation
        sub_consensus_trans = __reposition__(sub_consensus)
        translation = sub_consensus[0] - sub_consensus_trans[0]
        
        ### Reconstruct full shape including missing (and with translation)
        full_aligned_incomplete = []
        counter = 0
        for i, presence in enumerate(points_existing):
            if presence == 1:
                p = aligned_incomplete[counter] + translation
                p = [np.float(i) for i in p]
                full_aligned_incomplete.append(p)
                counter += 1
            else:
                missing_p = [np.nan for i in xrange(len(aligned_incomplete[0]))]
                full_aligned_incomplete.append(missing_p)
        full_aligned_incomplete = np.array(full_aligned_incomplete)
        ### Add to full point set
        aligned[shape] = full_aligned_incomplete

    aligned_shapeset = ShapeSet.ShapeSet(shapeset_name=str(shapes.name)+"_aligned")
    for t in aligned.keys():
        aligned_shapeset.append_shape(Shape.Shape(data=aligned[t].tolist(),
                                            shape_name=shapes.shapes[t].name,
                                            lm_names=shapes.shapes[t].name))
    aligned_shapeset.__is_aligned__ = True
    return aligned_shapeset
Пример #24
0
    N = 50000
    nb_cases = 20
    m = 5

    with open(
            "result " + type_file + " k=" + str(k) + " N=" + str(N) +
            " nb_cases=" + str(nb_cases) + " m=" + str(m) + ".txt",
            "w") as output_file:

        output_file.write("k=" + str(k) + " N=" + str(N) + " nb_cases=" +
                          str(nb_cases) + " m=" + str(m) + "\n")

        for name in list_files:

            t = time.time()
            list_shapes.append(Shape(name))

            list_shapes[-1].compute_D2(
                k, N, nb_cases, m)  #this method also computes the shape_dna

            l_eig.append(list_shapes[-1].eigenvalues)
            l_d2.append(list_shapes[-1].histogram)

            print("Computed  ", name, "in ", time.time() - t)
            output_file.write(name + "\n")
            output_file.write("eigenvalues begin  \n")
            output_file.write(
                np.array2string(
                    list_shapes[-1].eigenvalues, precision=8, separator=',') +
                "\n")
            output_file.write("eigenvalues end  \n")
Пример #25
0
 def appStarted(self):
     self.the_shape = Shape()
Пример #26
0
def new_shape():
    return Shape(SHAPE_START_X, SHAPE_START_Y, random.choice(shapes))
Пример #27
0
 def load(self):
     self.shape = Shape.Shape(self)
     self.mouth = Mouth.Mouth(self)
     self.eyes = Eyes.Eyes(self)
     self.nose = Nose.Nose(self)
     self.ear = Ear.Ear(self)
Пример #28
0
def StartGame():
    global objects
    global walls
    global bullets
    global forces
    global RUNNING
    global PAUSED
    global playerPoly
    global startPos
    global P1_COLOR
    global ledge
    global shootingCD
    global firingRate
    global dropRate
    global timeSinceLastDrop
    global shapesByScore
    objects = []
    forces = []
    walls = []
    bullets = []
    shootingCD = 1
    firingRate = 0.2  # 5 shots per second
    dropRate = 1
    timeSinceLastDrop = dropRate  #drop immediately
    startPos = [400, 500]
    localOffsets = [[0, 0], [20, -40], [40, 0]]
    playerPoly = Polygon(localOffsets=localOffsets,
                         pos=startPos,
                         color=P1_COLOR,
                         width=0,
                         normals_length=0,
                         velo=[0, 0],
                         mass=1,
                         angle=0,
                         momentInertia=1)

    ledgeOffsets = [[-400, 0], [-400, -100], [400, -100], [400, 400]]
    ledge = Polygon(localOffsets=ledgeOffsets,
                    pos=[400, 600],
                    color=const.GREEN,
                    width=0,
                    normals_length=0,
                    velo=[0, 0],
                    mass=1,
                    angle=0,
                    momentInertia=1)
    #vertical walls:
    walls.append(Wall([0, 200], [0, 0], const.BLACK))
    walls.append(Wall([800, 0], [800, 200], const.BLACK))
    #Horizontal walls:
    #walls.append(Wall( [0,0] , [800,0], const.BLACK))
    #walls.append(Wall( [800,600],[0,600], const.BLACK))

    #triangle
    shape1Offsets = [[0, 0], [20, -40], [40, 0]]
    #square
    shape2Offsets = [[0, 0], [0, -40], [40, -40], [40, 0]]
    #rombus
    shape3Offsets = [[0, 0], [20, -40], [60, -40], [40, 0]]
    #long rect
    shape4Offsets = [[0, 0], [0, -40], [20, -40], [20, 0]]
    #pentagon
    shape5Offsets = [[0, 0], [0, -40], [20, -50], [40, -40], [40, 0]]

    #localOffsets=list(reversed(shape1Offsets))
    shape1 = Shape(listOffsets=shape1Offsets, color=const.WIND_COLOR)
    shape2 = Shape(listOffsets=shape2Offsets, color=const.ORANGE)
    shape3 = Shape(listOffsets=shape3Offsets, color=const.PINK)
    shape4 = Shape(listOffsets=shape4Offsets, color=const.LIGHT_GREEN)
    shape5 = Shape(listOffsets=shape5Offsets, color=const.WHITE)

    shapesByScore = [shape1, shape2, shape3, shape4, shape5]

    forces.append(Friction(const.FRICTION_G, const.MEW, objects=[playerPoly]))

    RUNNING = True
    PAUSED = False
    GAMEOVER = False
    READ_FOR_PLAY_AGAIN = False
    startTime = time.time()
Пример #29
0
    def evaluation(self):

        # Gestion des territoires
        territory = Territory.Territory(self._board, self._black_moves,
                                        self._white_moves, self._black_goban,
                                        self._white_goban)

        # Gestion des formes
        shape = Shape.Shape(self._board, self._black_moves, self._white_moves,
                            self._black_goban, self._white_goban)
        black = 0
        white = 0
        """""" """""" """""" """""" """""
        Heuristique pour Noir
        """ """""" """""" """""" """""" ""

        if (self._black_goban != []):

            # Mise d'une pierre adverse en Atari
            for move in self._white_moves:
                if shape._is_atari_white(Goban.Board.name_to_coord(move)):
                    black += 900

            # On parcourt l'ensemble des coups joués par Noir
            for move in self._black_moves:

                # La forme en diamant est plutôt avantagée, dans le cas où elle ne fait pas baisser les libertés
                if shape._diamond(move, "BLACK") and self.liberties(
                        Goban.Board.name_to_coord(move))[0] >= 2:
                    black += 400

                for white_move in self._white_goban:
                    # Une pièce blanche a trop de libertés, il faut l'encercler
                    if ((self.liberties(
                            Goban.Board.name_to_coord(white_move))[0] >= 2)
                            and (move in self.liberties(
                                Goban.Board.name_to_coord(move))[1])):
                        black += 900
                    # Si elle n'a plus qu'une seule liberté, il faut la capturer pour capturer des pierres blanches
                    if ((self.liberties(
                            Goban.Board.name_to_coord(white_move))[0] == 1)
                            and (move in self.liberties(
                                Goban.Board.name_to_coord(white_move))[1])):
                        black += 900

                # On évite que les pierres soient placés près des bords
                if not territory._in_border(move):
                    black += 400

            # Si coup joué par Noir se retrouve en atari, on augmente ses libertés en ajoutant une pierre
            for move in self._black_goban:
                black_coord = Goban.Board.unflatten(move)
                if shape._is_atari_black(black_coord):
                    for move in self._black_moves:
                        ufcoord = Goban.Board.name_to_coord(move)
                        x_black = ufcoord[0]
                        y_black = ufcoord[1]
                        # On fait un Nobi pour augmenter les libertés, tout en faisant attention à ne pas
                        # se remettre Atari
                        if ufcoord in self.liberties(black_coord)[
                                1] and self.liberties(black_coord)[0] >= 2:
                            black = black + 1000
        """""" """""" """""" """""" """""
        Heuristique pour Blanc
        """ """""" """""" """""" """""" ""
        if (self._white_goban != []):

            # Mise d'une pierre adverse en Atari
            for move in self._black_moves:
                if shape._is_atari_black(Goban.Board.name_to_coord(move)):
                    white += 900

            # On parcourt l'ensemble des coups joués par Blanc
            for move in self._white_moves:

                # La forme en diamant est plutôt avantagée, dans le cas où elle ne fait pas baisser les libertés
                if shape._diamond(move, "WHITE") and self.liberties(
                        Goban.Board.name_to_coord(move))[0] >= 2:
                    white += 400

                # Une pièce Noir a trop de libertés, il faut l'encercler
                for black_move in self._black_goban:
                    if ((self.liberties(
                            Goban.Board.name_to_coord(black_move))[0] >= 2)
                            and (move in self.liberties(
                                Goban.Board.name_to_coord(move))[1])):
                        white += 900
                    # Si elle n'a plus qu'une seule liberté, il faut la capturer pour capturer des pierres noires
                    if ((self.liberties(
                            Goban.Board.name_to_coord(black_move))[0] == 1)
                            and (move in self.liberties(
                                Goban.Board.name_to_coord(black_move))[1])):
                        white += 900

                # On évite que les pierres soient placés près des bords
                if not territory._in_border(move):
                    white += 400

            # Si coup joué par Blanc se retrouve en atari, on augmente ses libertés en ajoutant une pierre
            for move in self._white_goban:
                white_coord = Goban.Board.unflatten(move)
                if shape._is_atari_white(white_coord):
                    for move in self._white_moves:
                        ufcoord = Goban.Board.name_to_coord(move)
                        x_white = ufcoord[0]
                        y_white = ufcoord[1]
                        # On fait un Nobi pour augmenter les libertés tout en faisant attention à ne pas
                        # se remettre Atari
                        if ufcoord in self.liberties(white_coord)[
                                1] and self.liberties(white_coord)[0] >= 2:
                            white = white + 1000
        """""" """""" """""" """""" """""
        Calcul des pondérations
        """ """""" """""" """""" """""" ""
        if self._count < 15:  #Milieu de partie
            black = black + 100 * self.liberties_black(
            ) + 1000 * territory._count_controled_intersection_black()

            white = white + 100 * self.liberties_white(
            ) + 1000 * territory._count_controled_intersection_white()
        else:  #Fin de partie
            black = black + 1000 * self.liberties_black(
            ) + 500 * territory._count_controled_intersection_black()

            white = white + 1000 * self.liberties_white(
            ) + 500 * territory._count_controled_intersection_white()

        if self._mycolor == Goban.Board._BLACK:
            return black - white
        else:
            return white - black
Пример #30
0
# Defining a class only works from ipython within
import Shape
test = Shape.Shape(2,4)   # test = Module.Class()