예제 #1
0
파일: Game.py 프로젝트: AmbBAI/JunkCode
 def run(self,msg):
     if msg == self.LEFT:
         self.nowpos[1] -= 1
         if self.__errmove__():
             self.nowpos[1] += 1
     elif msg == self.RIGHT:
         self.nowpos[1] += 1
         if self.__errmove__():
             self.nowpos[1] -= 1
     
     elif msg == self.STEPDOWN:
         self.nowpos[0] += 1
         if self.__errmove__():
             self.nowpos[0] -= 1
             self.freeze()
             self.newblock()
     elif msg == self.ROTATE:
         self.now = Blocks.rotate(self.now)
         if self.__errmove__():
             self.now = Blocks.undorotate(self.now)
     elif msg == self.DOWN:
         self.nowpos[0] += 1
         while not self.__errmove__():
             self.nowpos[0] += 1
         else:
             self.nowpos[0] -= 1
         self.freeze()
         self.newblock()
     self.clearline()
    def compute(self):
        """
        Fungsi untuk menghitung karakteristik blok citra
        :return: None
        """
        print "Step 2/4: Menghitung fitur karakteristik"

        imageWidthOverlap = self.imageWidth - self.blockDimension
        imageHeightOverlap = self.imageHeight - self.blockDimension

        time.sleep(0.1)
        if self.isRGB:
            for i in tqdm(range(0, imageWidthOverlap + 1, 1)):
                for j in range(0, imageHeightOverlap + 1, 1):
                    imageBlockRGB = self.image.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlockGrayscale = self.imageGrayscale.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlock = Blocks.Blocks(imageBlockGrayscale,
                                               imageBlockRGB, i, j,
                                               self.blockDimension)
                    self.featureContainer.addBlock(imageBlock.computeBlock())
        else:
            for i in range(imageWidthOverlap + 1):
                for j in range(imageHeightOverlap + 1):
                    imageBlockGrayscale = self.image.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlock = Blocks.Blocks(imageBlockGrayscale, None, i, j,
                                               self.blockDimension)
                    self.featureContainer.addBlock(imageBlock.computeBlock())
    def block(self, options=Map()):
        if self.options.gradient:
            color = self.color(options)
            if (type(color) == tuple and len(color) == 3) or (type(color)
                                                              == str):
                block_obj = Blocks.closest_by_color(color,
                                                    self.options + options)
            else:
                error_string = "Error - Texture1D block color (\"" + str(
                    color) + "\") not recognized"
                if Blocks.DEBUG_MODE == 1:
                    raise ValueError(error_string)
                else:
                    print(error_string)

                block_obj = Blocks.block_by_id(0)
        else:
            if self.blocks and self.chances:
                block = weighted_choice(self.chances, self.blocks)
            elif self.blocks:
                block = rnd.choice(self.blocks)
            else:
                block = self.material
            block_obj = Blocks.block(block)

        return block_obj
    def compute(self):
        """
        To compute the characteristic features of image block
        :return: None
        """
        print "Step 2 of 4: Computing characteristic features"

        imageWidthOverlap = self.imageWidth - self.blockDimension
        imageHeightOverlap = self.imageHeight - self.blockDimension

        if self.isThisRGBImage:
            for i in tqdm(range(0, imageWidthOverlap + 1, 1)):
                for j in range(0, imageHeightOverlap + 1, 1):
                    imageBlockRGB = self.imageData.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlockGrayscale = self.imageGrayscale.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlock = Blocks.Blocks(imageBlockGrayscale,
                                               imageBlockRGB, i, j,
                                               self.blockDimension)
                    self.featuresContainer.addBlock(imageBlock.computeBlock())
        else:
            for i in range(imageWidthOverlap + 1):
                for j in range(imageHeightOverlap + 1):
                    imageBlockGrayscale = self.imageData.crop(
                        (i, j, i + self.blockDimension,
                         j + self.blockDimension))
                    imageBlock = Blocks.Blocks(imageBlockGrayscale, None, i, j,
                                               self.blockDimension)
                    self.featuresContainer.addBlock(imageBlock.computeBlock())
예제 #5
0
def Decoder(inputTensor, outputSize, blockName):
    with tf.variable_scope(blockName):
        conv1x1_1 = bs.SmallUniteConvolutionBlock(
            inputTensor,
            kernalSize=1,
            outChannels=128,
            gNum=4,
            blockName="Conv1x1_Decoder_First_Step")
        conv1x1_2 = bs.SmallUniteConvolutionBlock(
            conv1x1_1,
            kernalSize=1,
            outChannels=64,
            gNum=4,
            blockName="Conv1x1_Decoder_Second_Step")
        globalPooling = keras.layers.GlobalAvgPool2D(
            data_format="channels_first", name="AVG_Global_Decoder")(conv1x1_2)
        weight1 = bf.WeightCreation(shape=[64, 128], name="TransWeight1")
        bias1 = tf.constant(value=0.,
                            dtype=tf.float32,
                            shape=[128],
                            name="Bias1")
        layer1 = keras.layers.PReLU(trainable=True)(tf.add(
            tf.matmul(globalPooling, weight1), bias1))
        weight2 = bf.WeightCreation(shape=[128, outputSize],
                                    name="TransWeight2")
        bias2 = tf.constant(value=0.,
                            dtype=tf.float32,
                            shape=[outputSize],
                            name="Bias2")
        outputTensor = tf.add(tf.matmul(layer1, weight2), bias2)
    return outputTensor
def decorate_outside(obj, options=Map()):

    obj.points = []
    obj.points_edges = []
    obj.material_clear = Blocks.AIR

    border = flatten_list_of_lists(
        [vg.get_line_from_points(l[0], l[1]) for l in options.lines])

    if options.options.outside == "flowers":
        flowers_1 = []
        flowers_2 = []
        for i, b in enumerate(border):
            # TODO: Refactor to have multiple numbers of flowers

            if (i % 2) == 0:
                flowers_1.append(b)
            else:
                flowers_2.append(b)

        colors = Blocks.kind("Flower")
        np.random.shuffle(colors)

        obj.features.append(
            Feature("flowers", flowers_1, Map(material=colors[0])))
        obj.features.append(
            Feature("flowers", flowers_2, Map(material=colors[1])))

    elif options.options.outside == "trees":
        trees = []
        for i, b in enumerate(border):
            if (i % 3) == 0:
                trees.append(b)

        colors = Blocks.kind("Sapling")
        np.random.shuffle(colors)

        obj.features.append(Feature("flowers", trees, Map(material=colors[0])))

    elif options.options.outside == "grass":
        trees = []
        for i, b in enumerate(border):
            if (i % 3) == 0:
                trees.append(b)

        obj.features.append(
            Feature("flowers", trees, Map(material=Blocks.DOUBLETALLGRASS)))

    elif options.options.outside == "fence":
        fence_type = np.random.random_integers(188, 192)
        obj.features.append(Feature("fence", border, Map(material=fence_type)))

    return obj
예제 #7
0
파일: Game.py 프로젝트: AmbBAI/JunkCode
 def start(self, level):
     self.isover = False
     
     self.next = Blocks.randblock(self.shapen)
     self.now = Blocks.randblock(self.shapen)
     self.nowpos = [0,self.size[1]/2-2]
     for ph in xrange(self.size[0]):
         for pw in xrange(self.size[1]):
             self.map[ph][pw] = -1
             
     self.level = level
     self.line = 0
     self.score = 0
예제 #8
0
파일: Drawer.py 프로젝트: AmbBAI/JunkCode
def draw_tips(scr,block):
    scr.fill(Colors.WHITE)
    brect = Blocks.getminirect(block)
    lh = brect[2] - brect[0] + 1
    lw = brect[3] - brect[1] + 1
    sh = (Blocks.BLOCKH - lh) * RECTH / 2 + 10
    sw = (Blocks.BLOCKW - lw) * RECTW / 2 + 10
    shape = Blocks.getshape(block)
    for th in range(lh):
        for tw in range(lw):
            if shape[brect[0] + th][brect[1] + tw] == 0: continue
            rect = [sw + tw * RECTW, sh + th * RECTH, RECTW, RECTH]
            draw_rect(scr, Colors.color[block[0]], rect)
예제 #9
0
def scan(show_location=False):
    direction = my_rot()
    target = vg.up(my_pos())

    # print("Facing:", direction)
    if direction == 'w':
        x_range = [1]
        z_range = [-2, -1, 0, 1, 2]
    elif direction == 'e':
        x_range = [-1]
        z_range = [2, 1, 0, -1, -2]
    elif direction == 's':
        x_range = [-3, -2, -1, 0, 1]
        z_range = [0]
    else:
        # n
        x_range = [-2, -1, 0, 1, 2]
        z_range = [-2]

    blocks = []
    for y in [2, 1, 0, -1, -2]:
        text = ""
        for x in x_range:
            for z in z_range:
                new_point = target + V3(x, y, z)
                b = mc.getBlockWithData(new_point.x, new_point.y, new_point.z)

                name = Blocks.name_by_id(b.id, b.data)
                loc = str(new_point.x) + "," + str(new_point.y) + "," + str(
                    new_point.z) + " : " if show_location else ""
                line = "(" + loc + str(b.id) + "," + str(b.data) + ": " + name + ")  "

                text += line.ljust(28)
                blocks.append(b)
        print(text)
예제 #10
0
    def __create_blocks(self,file_name):
        coil_points = read_and_transform.extract_coil_samples(self.normalized_points)
        #print "Tamano coil: %s" %len(coil_points)

        #Get file name
        temp = file_name.split('/')
        lastone = len(temp)
        newfile = temp[lastone-1]
        csvfile="calib_data/calib_points/"+newfile

        #Save file with calib coil_points
        with open(csvfile, "w") as output:
            writer = csv.writer(output, lineterminator='\n')
            writer.writerows([coil_points])

        #Generate new coil points
        self._create_csv(csvfile)
        coil_points=self._create_new_data(coil_points,csvfile)
        #print 'Nuevos datos coil'
        #print coil_points

        #Generate blocks to visualize
        blocks_indices = Blocks.get_blocks(coil_points, 7)

        # remove small blocks
        blocks_indices = filter(lambda x: len(x) > 5, blocks_indices)
        blocks = []
        for bi in blocks_indices:
            #print 'Creating blocks'
            points = [coil_points[i] for i in bi]
            b = TmsBlock(points)
            b.calculate_sphere_intersection(self.sphere_radius, self.sphere_center)
            b.find_hemisphere(self.calibration_points, self.sphere_center)
            blocks.append(b)
        self.blocks = blocks
예제 #11
0
파일: Game.py 프로젝트: AmbBAI/JunkCode
 def freeze(self):
     shape = Blocks.getshape(self.now)
     for tph in range(Blocks.BLOCKH):
         for tpw in range(Blocks.BLOCKW):
             if shape[tph][tpw] == 0: continue
             ph = self.nowpos[0] + tph
             pw = self.nowpos[1] + tpw
             self.map[ph][pw] = self.now[0]
예제 #12
0
파일: Game.py 프로젝트: AmbBAI/JunkCode
 def __errmove__(self):
     shape = Blocks.getshape(self.now)
     for tph in range(Blocks.BLOCKH):
         for tpw in range(Blocks.BLOCKW):
             if shape[tph][tpw] == 0: continue
             if self.nowpos[0]+tph < 0: return True
             if self.nowpos[1]+tpw < 0: return True
             if self.nowpos[0]+tph >= self.size[0]: return True
             if self.nowpos[1]+tpw >= self.size[1]: return True
             if self.map[self.nowpos[0]+tph][self.nowpos[1]+tpw] != -1: return True
     return False
예제 #13
0
    def build_map_array(self):
        """ Bulding this array of cells helps programming movement
            and space indications."""
        map_array = []
        border_list = []
        B_unbreakable_list = []
        B_breakable_list = []
        for column in range(0, 25):  # Adds top and bottom borders.
            border_list.append([column, 0])
            border_list.append([column, 18])
        for row in range(1, 18):  # Adds left and right borders.
            border_list.append([0, row])
            border_list.append([24, row])
        for x in range(0, 25):
            for y in range(0, 19):
                if [x, y] in border_list:
                    """
                        Creates array based on x and y values in
                        for and fills them with solid blocks if the
                        cells are inside of the 'border_list' list,
                        making them incapable of being stepped on.
                    """
                    map_array.append(Cells.Cells([x, y], Blocks.Blocks()))
                elif (x % 2) == 0 and (y % 2) == 0:
                    map_array.append(
                        Cells.Cells([x, y], Blocks.B_unbreakable()))
                    B_unbreakable_list.append([x, y])
                else:
                    if x > 3 and y > 3:
                        B_breakable_list.append([x, y])
                    map_array.append(Cells.Cells([x, y], None))

        B_breakable_list = random.choices(B_breakable_list, k=60)
        for cell in range(len(B_breakable_list)):
            for cell2 in range(len(map_array)):
                if map_array[cell2].position == B_breakable_list[cell]:
                    map_array[cell2].content = Blocks.B_breakable()

        self.map_array = map_array
        self.B_unbreakable_list = B_unbreakable_list
        self.B_breakable_list = B_breakable_list
예제 #14
0
 def __Decoder_Net_Build(self,mediumActiveMap):
     with tf.variable_scope("DECODER"):
             mediumActiveMap_2 = bs.SmallResBlockWith2xUpSampling(mediumActiveMap,kernelSize=1,gNum=4,outChannels=512,
                                                                  blockName="ActiveMap2xUp")
             mediumActiveMap_4 = bs.SmallResBlockWith2xUpSampling(mediumActiveMap_2,kernelSize=2,gNum=4,outChannels=256,
                                                                  blockName="ActiveMap4xUp")
             mediumActiveMap_8 = bs.SmallResBlockWith2xUpSampling(mediumActiveMap_4,kernelSize=3,gNum=4,outChannels=128,
                                                                  blockName="ActiveMap8xUp")
             mediumActiveMap_16 = bs.SmallResBlockWith2xUpSampling(mediumActiveMap_8,kernelSize=4,gNum=4,outChannels=64,
                                                                  blockName="ActiveMap16xUp")
             self.ActivityMap = bs.SmallResBlockWith2xUpSampling(mediumActiveMap_16,kernelSize=5,gNum=4,outChannels=32,
                                                                  blockName="ActiveMap32xUp")
             print("Activity Map :",self.ActivityMap)
             globalPoolingTensor = keras.layers.GlobalAveragePooling2D(name="FinalGlobalAVGPooling")(self.ActivityMap)
             self.ActivityWeight = tf.get_variable(name="ActivityWeights" , shape=[32 , self.__outLabelNum],
                                                   dtype=tf.float32,
                                                   initializer=tf.truncated_normal_initializer(
                                                       stddev=math.pow(1.25 / np.sum([32 , self.__outLabelNum]),0.5))
                                                   ,trainable=True)
             self.Final_D_OUT = tf.matmul(globalPoolingTensor,self.ActivityWeight,name="FinalOp")
             print("Final Output :",self.Final_D_OUT)
def decorate_roof(obj, options=Map()):
    settings = options.options
    if not settings.roof:
        return obj

    material = Blocks.match(settings.roof_material)
    if material:
        obj.material = material

    if str.startswith(settings.roof, "pointy"):
        height = settings.roof_pointy_multiplier * options.radius
        pointy = V3(options.center.x,
                    options.center.y + options.height + height,
                    options.center.z)

        for i, vec in enumerate(options.corner_vectors):
            roof_line = vg.getLine(vec.x, vec.y + 1, vec.z, pointy.x,
                                   pointy.y + 1, pointy.z)
            obj.points_edges += roof_line

            if not settings.roof == "pointy_lines":
                next_roof_point = options.corner_vectors[(i + 1) % len(
                    options.corner_vectors)]

                # Triangle to pointy face
                triangle_face = [vec, pointy, next_roof_point]
                roof_face = vg.unique_points(
                    vg.getFace([V3(v.x, v.y + 1, v.z) for v in triangle_face]))
                obj.points = obj.points.union(roof_face)

    elif str.startswith(settings.roof, "triangular"):
        obj.decorations.append("roof_triangular")
    elif str.startswith(settings.roof, "battlement"):
        height = settings.roof_battlement_height or 1
        spacing = settings.roof_battlement_space or 2

        for i, vec in enumerate(options.corner_vectors):
            next_roof_point = options.corner_vectors[(i + 1) % len(
                options.corner_vectors)]
            # TODO: Add X,Z outward from center as option
            roof_line = vg.getLine(vec.x, vec.y + height, vec.z,
                                   next_roof_point.x,
                                   next_roof_point.y + height,
                                   next_roof_point.z)

            obj.points = obj.points.union(
                vg.points_spaced(roof_line, Map(every=spacing)))

    elif str.startswith(settings.roof, "shape"):
        obj.decorations.append("roof_floating_shape")
    return obj
예제 #16
0
def Encoder(inputTensor, outputChannels, blockName):
    with tf.variable_scope(blockName):
        conv1x1_1 = bs.SmallUniteConvolutionBlock(
            inputTensor,
            kernalSize=1,
            outChannels=64,
            gNum=4,
            blockName="Conv1x1_Encoder_First_Step")
        Transformer_E_2 = bs.TransformerEncoderBlock(
            conv1x1_1,
            outputChannels=64,
            blockName="Transformer_Encoder_Second_Step")
        conv1x1_3 = bs.TransChannelsConvolutionBlock(
            Transformer_E_2,
            kernalSize=1,
            outChannels=outputChannels,
            blockName="Conv1x1_Encoder_Third_Step")
        pool_Down = bf.Pooling(conv1x1_3,
                               windowShape=[2, 2],
                               poolingType="MAX",
                               stride=[2, 2],
                               name="Pooling_Encoder_Fourth_Step")
    return conv1x1_1, Transformer_E_2, conv1x1_3, pool_Down
def hex_to_rgb(color):
    """ "#FFFFFF" -> [255,255,255] '''
    Note: Pass 16 to the integer function for change of base"""

    try:
        # out = [int(hex[i:i+2], 16) for i in range(1,6,2)]
        out_rgb = Blocks.color_as_rgb(color)
        out = [out_rgb[0], out_rgb[1], out_rgb[2]]

    except ValueError:
        print("Hex invalid", color)
        out = color

    return out
    def color(self, options=Map()):
        options = self.options + options
        if self.options.gradient:
            hex_colors = self.get_calculated_steps(options)
            if options.step:
                step = options.step
            elif options.point and options.bounds:

                if self.axis == "y":
                    bounds_lowest = options.bounds.lowest
                    # bounds_highest = options.bounds.highest
                    step = options.point.y - bounds_lowest
                elif self.axis == "x":
                    bounds_lowest = options.bounds.x_low
                    # bounds_highest = options.bounds.x_high
                    step = options.point.x - bounds_lowest
                else:
                    # if self.axis == "z":
                    bounds_lowest = options.bounds.z_low
                    # bounds_highest = options.bounds.z_high
                    step = options.point.z - bounds_lowest

                step = int(step)

                # step_range = bounds_highest - bounds_lowest + 1
                # step = dist_from_low
            else:
                step = 0

            if "hex" in hex_colors:
                hex_colors = hex_colors["hex"]

            if step > len(hex_colors) - 1:
                step = len(hex_colors) - 1
            elif step < 0:
                step = 0
            return hex_colors[step]

        else:
            if self.blocks and self.chances:
                block = weighted_choice(self.chances, self.blocks)
            elif self.blocks:
                block = rnd.choice(self.blocks)
            else:
                block = self.material

            block_obj = Blocks.block(block)
            return block_obj["main_color"]
예제 #19
0
파일: Drawer.py 프로젝트: AmbBAI/JunkCode
def draw_blocks(scr, size, gamemap, block = None, blockpos = None):
    scr.fill(Colors.WHITE)
    for ph in xrange(size[0]):
        for pw in xrange(size[1]):
            if gamemap[ph][pw] == -1: continue
            draw_rect(scr, Colors.color[gamemap[ph][pw]], block_rect(ph,pw))

    if block != None and blockpos != None:
        shape = Blocks.getshape(block)
        for tph in range(Blocks.BLOCKH):
            for tpw in range(Blocks.BLOCKW):
                if shape[tph][tpw] == 0: continue
                ph = blockpos[0] + tph
                pw = blockpos[1] + tpw
                if ph < 0 or ph > size[0]: continue
                if pw < 0 or pw > size[1]: continue
                draw_rect(scr, Colors.color[block[0]], block_rect(ph,pw))
def decorate_roof_shape(obj, options=Map()):
    settings = options.options

    if settings.roof_shape_color_pattern == "RainbowGlass":
        material = Texture1D.COMMON_TEXTURES.RainbowGlass
    elif settings.roof_shape_color_pattern == "OldStoneWall":
        material = Texture1D.COMMON_TEXTURES.OldStoneWall
    elif settings.roof_shape_color_pattern == "WoodBlends":
        material = Texture1D.COMMON_TEXTURES.WoodBlends
    elif settings.roof_shape_color_pattern == "Glow":
        material = Texture1D.COMMON_TEXTURES.Glow
    else:
        material = Blocks.match(settings.roof_material)

    if not material:
        material = obj.material

    boundaries = vg.bounds(options.corner_vectors)

    min_radius = min(boundaries.x_radius, boundaries.z_radius)

    pos = boundaries.center
    if settings.roof_shape_object == "cylinder":
        func = vg.cylinder
        height = min_radius * (settings.roof_shape_height_multiplier or 1)
    elif settings.roof_shape_object == "cone":
        func = vg.cone
        height = min_radius * (settings.roof_shape_height_multiplier or 1)
    elif settings.roof_shape_object == "box":
        func = vg.box
        height = min_radius * (settings.roof_shape_height_multiplier or 1)
    else:  # sphere
        func = vg.oblate_sphere
        height = None
        if settings.roof_shape_floating:
            pos = vg.up(boundaries.center, min_radius)

    sides = func(pos, min_radius, tight=settings.roof_shape_tight, height=height,
                 options=Map(min_y_pct=.5, x_radius=boundaries.x_radius, z_radius=boundaries.z_radius))

    roof_lists = list()
    roof_lists.append(Map(blocks=sides, material=material))
    obj.features.append(Feature("roof", boundaries.center, Map(block_lists=roof_lists)))

    obj.points_edges = []
    return obj
 def set_options(self, options=Map()):
     self.options = options
     if options.gradient:
         self.axis = options.gradient_axis or "y"
         self.gradient_type = options.gradient_type or "linear"
         self.colors_names = options.colors or rand_hex_color(2)
         self.colors = [
             Blocks.color_as_rgb(color_name)
             for color_name in self.colors_names
         ]
     elif options.blocks:
         self.blocks = options.blocks
         if options.chances:
             self.chances = options.chances
     else:
         self.material = options.color or options.material or rand_hex_color(
             1)
예제 #22
0
def decorate_roof_triangular(obj, options=Map()):
    settings = options.options

    material = Blocks.match(settings.roof_material)
    if material:
        obj.material = material

    p1, p2, radius, ends, sides = vg.best_points_for_triangular_roof(
        options.corner_vectors)
    chop_pct = settings.roof_triangular_chop_pct or 0

    radius += settings.roof_triangular_overhang

    height = radius
    if round(height) == int(height):
        height += 1

    if settings.roof_triangular_stairs or settings.roof_triangular_end_cap_in:
        # It's a more complex roof, build it as a Feature
        roof_lists = vg.prism_roof(
            p1,
            p2,
            height=height,
            radius=radius,
            chop_pct=chop_pct,
            sloped=settings.roof_triangular_sloped,
            material=obj.material,
            endpoint_out=settings.roof_triangular_end_cap_out)

        obj.features.append(Feature("roof", p1, Map(block_lists=roof_lists)))

    else:
        # Nothing fancy, color each block all the same type
        roof = vg.triangular_prism(p1,
                                   p2,
                                   height=height,
                                   radius=radius,
                                   chop_pct=chop_pct,
                                   sloped=settings.roof_triangular_sloped)
        obj.points.update(roof)

    obj.points_edges = []

    return obj
예제 #23
0
    def compute(self):
        """
        To compute the characteristic features of image block
        :return: None
        """
        print("Step 2 of 4: Computing feature vectors")

        for i in tqdm(range(0, self.imageWidth, self.blockDimension)):
            # print (i)
            for j in range(0, self.imageHeight, self.blockDimension):
                imageBlockRGB = self.imageData.crop(
                    (i, j, i + self.blockDimension, j + self.blockDimension))
                imageBlockGrayscale = self.imageGrayscale.crop(
                    (i, j, i + self.blockDimension, j + self.blockDimension))
                imageBlock = Blocks.Blocks(imageBlockGrayscale, imageBlockRGB,
                                           i, j, self.blockDimension)
                keypoints, descriptors = imageBlock.computeBlock()
                self.blockPairContainer.addBlock([i, j])
                self.featuresContainerKeypoints.addBlock(keypoints)
                self.featuresContainerDescriptors.addBlock(descriptors)
예제 #24
0
 def __init__(self, x, y):
     Blocks.__init__(x,y)
     
예제 #25
0
def main(time1):
    pygame.init()
    run = True
    screen = pygame.display.set_mode(DISPLAY)
    pygame.display.set_caption('Labirint')
    bg = Surface((WIN_WIDTH, WIN_HEIGHT))
    bg.fill(Color(BACKGROUND_COLOR))
    left = right = up = down = False
    entities = pygame.sprite.Group()
    entities_exit = pygame.sprite.Group()
    pf_exit = []
    platforms = []
    level = [
        "----------------------------------------",
        "-  -                           -       -",
        "- --  ---------------   -  --  ------  -",
        "-     - -  -            -  -   -       -",
        "- --  - -  -   -------  -  -   -    -  -",
        "- -   - -      -        -  -   -    -  -",
        "- -   - -   ----        -  -        -  -",
        "- -   -        -  -------------------  -",
        "- -   ------   -        --             -",
        "---   -    -   ----     -    -----------",
        "- -        -      -             -   -  -",
        "- -  -     -----  - -----    -         -",
        "- -  -                  -------------  -",
        "- -  --------- -------             -   -",
        "-    -               ---------------   -",
        "- ----  --------------             -   -",
        "-    -                  - ----------   -",
        "-    --------------------        -   ---",
        "-         -   -   -     - -- -----   - -",
        "--------  -   -   -  -  - -  -       - -",
        "-      -  -   -   -  -  - -  -  ------ -",
        "-  -   -  -   -   -  -  - -  -         -",
        "-  -      -          -  - -  --------- -",
        "-  -----  ------------  ---            -",
        "-                               --------",
        "- --- ---------------------------      -",
        "- -    --     -           -            -",
        "- -     --- ---- -------  -  -  ----   -",
        "- -- --            -   -  -  -  -  -   -",
        "- -   -------      -   -  -  -  -  -   -",
        "- - -   -   ------     -  -  -  -  -   -",
        "- - -   -   -  - ----  - --  -  -  -   -",
        "- - -   -   -  -    ---      -  -  -   -",
        "- - -   -   -  -   -- ----   -  -  -   -",
        "- - -   -      -    -    --------      -",
        "- - -   -   -  -    -          -----   -",
        "- - -   -   -  -    -    ----     ---- -",
        "- - -   ------ ---  - ----  -   ---    -",
        "-           -          -               -",
        "----------------------------------------"
    ]
    start_x = start_y = x = y = q = i = 0

    k1 = int(random.uniform(1, 38))
    while k1 == 3 or k1 == 31:
        k1 = int(random.uniform(1, 38))
    k2 = int(random.uniform(1, 38))
    while k2 == 12 or k2 == 23:
        k2 = int(random.uniform(1, 38))
    for row in level:
        for col in row:
            if col == "-" and q == k1 and i == 0:
                pf_exit = Blocks.Platform(x, y)
                entities_exit.add(pf_exit)
            elif col == "-" and q == k2 and i == 39:
                start_x = x
                start_y = y
                pf = Blocks.Platform(x, y)
                entities.add(pf)
                platforms.append(pf)
            elif col == "-":
                pf = Blocks.Platform(x, y)
                entities.add(pf)
                platforms.append(pf)
            x += PLATFORM_WIDTH
            q += 1
        y += PLATFORM_HEIGHT
        q = 0
        x = 0
        i += 1

    movements = 0
    font = pygame.font.SysFont('arial', 30)

    hero = Player_L.Player(start_x, start_y - 15, run, COLOR)
    entities.add(hero)
    entities_exit.add(hero)
    while run:
        time = pygame.time.get_ticks() // 1000 - time1
        clock.tick(60)
        for e in pygame.event.get():
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_q):
                raise SystemExit
            if e.type == KEYDOWN and e.key == K_a:
                time1 = pygame.time.get_ticks() // 1000
                main(time1)
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
                movements += 1
            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
                movements += 1
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True
                movements += 1
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
                movements += 1
            if e.type == KEYUP and e.key == K_LEFT:
                left = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False

        screen.blit(bg, (0, 0))
        hero.update(left, right, up, down, platforms, pf_exit)
        if hero.run == False:
            run = False
        entities.draw(screen)
        text_m2 = font.render(str(movements), 1, (50, 205, 50))
        text_m1 = font.render("шаги:", 1, (50, 205, 50))
        text_time1 = font.render("время:", 1, (50, 205, 50))
        text_time2 = font.render(str(time), 1, (50, 205, 50))
        text_finish = font.render("Чтобы завершить игру нажмите q", 1,
                                  (50, 205, 50))
        text_repeat = font.render("Чтобы начать игру заново нажмите a", 1,
                                  (50, 205, 50))
        place_m2 = text_m2.get_rect(center=(585, 620))
        place_m1 = text_m1.get_rect(center=(540, 620))
        place_time1 = text_time1.get_rect(center=(530, 660))
        place_time2 = text_time1.get_rect(center=(610, 660))
        place_finish = text_finish.get_rect(center=(300, 700))
        place_repeat = text_finish.get_rect(center=(300, 750))
        screen.blit(text_m1, place_m1)
        screen.blit(text_m2, place_m2)
        screen.blit(text_time1, place_time1)
        screen.blit(text_time2, place_time2)
        screen.blit(text_finish, place_finish)
        screen.blit(text_repeat, place_repeat)
        pygame.display.update()
    while True:
        clock.tick(60)
        font = pygame.font.SysFont('arial', 20)
        screen.blit(bg, (0, 0))
        text_end = font.render(
            "Вы выйграли,нажмите а, чтобы начать сначала или q, чтобы выйти",
            1, (50, 205, 50))
        place_end = text_end.get_rect(center=(300, 400))
        screen.blit(text_end, place_end)
        for e in pygame.event.get():
            if e.type == QUIT or (e.type == KEYDOWN and e.key == K_q):
                raise SystemExit
            if e.type == KEYDOWN and e.key == K_a:
                time1 = pygame.time.get_ticks() // 1000
                main(time1)
        pygame.display.update()
예제 #26
0
파일: Main.py 프로젝트: Voveka98/Game
entities.add(player)
level = [
    "-                        ", "-   -                    ",
    "-      ------            ", "-     -                  ",
    "-    -                ---", "-- -- ---      ----------",
    "-------------------------"
]

bg = pygame.image.load('/home/vovek/PythonGame/assets/fon.jpg')
clock = pygame.time.Clock()

x = y = 0
for row in level:
    for col in row:
        if col == '-':
            block = Blocks.Blocks((50, 50, 50), x, y)
            entities.add(block)
            blocks.append(block)
        x += Blocks.Blocks_Width
    y += Blocks.Blocks_Height
    x = 0


def play_music():
    pygame.mixer.music.load('/home/vovek/PythonGame/music/Led')
    pygame.mixer.music.set_volume(0.45)
    pygame.mixer.music.play(-1, 0.0)


def drawWindow():
예제 #27
0
def find_block_info(material, data=None, options=Map()):
    if type(material) == list:
        global BLOCK_DRAW_INCREMENTER
        if options.choice_type == "rotate":
            block_id = BLOCK_DRAW_INCREMENTER % (len(material))
            material = material[block_id]
            BLOCK_DRAW_INCREMENTER += 1
        elif options.choice_type == "rebound":
            group = math.ceil(BLOCK_DRAW_INCREMENTER / (len(material)))
            block_id = BLOCK_DRAW_INCREMENTER % (len(material))
            if group % 2 == 0:
                block_id = len(material) - 1 - block_id
            material = material[block_id]
            BLOCK_DRAW_INCREMENTER += 1
        else:  # Random
            material = np.random.choice(material)

    elif type(material) == Texture1D.Texture1D:
        block_obj = material.block(options=options)
        data = block_obj["data"]
        material = block_obj["id"]

    elif type(material) == Map and "id" in material:
        data = material["data"] if "data" in material else None
        material = material["id"]

    elif type(material) == tuple:
        if len(material) == 2:
            data = material[1]
            material = material[0]
        elif len(material) == 3:
            block_color = Blocks.closest_by_color(material)
            data = block_color["data"]
            material = block_color["id"]

    if type(material) == dict:
        block_id = material["id"]
        data = material["data"] or data or None
        material = block_id

    if type(material) == tuple and len(material) == 2:
        material, data = material

    if material is None:
        print("ERROR - material is None")
    elif type(material) == Map:
        print("ERROR - Map material passed in:", material)
    elif type(material) == block.Block:
        material = material.id
    else:
        try:
            material = int(material)
        except:
            print("ERROR CONVERTING MATERIAL", type(material))

    if type(data) == Map:
        print("ERROR - Map material Data passed in:", data)
    elif data is None:
        # do nothing
        pass

    if data is not None:
        data = int(data)
    return material, data
예제 #28
0
import Blocks

# define a variable that contains the name of your image file
input_image_file = 'mountain.jpg'

#define a variable that contains the name of output file
output_image_file = 'mountain_out.jpg'

# open your input file for binary read with the 'with' statement
with open(input_image_file, 'rb') as infile:
    
    # read the contents of the file into a variable 
    file_contents = infile.read()
    
    # pass the contents to Blocks.start() as a parameter, the result should
    # be stored in a new variable
    new_contents = Blocks.start(file_contents)
    
    # open a file for binary write with the 'with' statement
    with open(output_image_file, 'wb') as outfile:
        
        # write the new contents to the output file 
        outfile.write(new_contents)
예제 #29
0
파일: Game.py 프로젝트: AmbBAI/JunkCode
 def newblock(self):
     if self.isover: return
     self.now = self.next
     self.next = Blocks.randblock(self.shapen)
     self.nowpos = [0,self.size[1]/2-2]
     if self.__errmove__(): self.isover = True
예제 #30
0
 def __init__(self, x, y):
     Blocks.__init__(x, y)
예제 #31
0
파일: Game.py 프로젝트: Yahnit/Bomberman
from Enemy import *
from Person import *
from getchunix import *
from Wall import *
from Board import *
from alarmexception import *
getch = GetchUnix()
'''
The following code initializes the Game
'''
bomb = None
b = board()
Board = b.makeBoard()
wall = Wall()
wall.insertWall(Board)
blocks = Blocks()
player = Bomberman()
blocks.insertBlocks(Board, player)
player.placeBomberman(player.getX(), player.getY(), Board)
enemy = Enemy()
enemy.generateEnemy(Board, enemy.getNumEnemies())


def hello():
    print("Hello")


def alarmHandler(signum, frame):
    raise AlarmException

예제 #32
0
    def __Encoder_Net_Build(self):
        with tf.variable_scope("ENCODER"):

            ######################
            ### Bottom to Up
            ######################

            ### 32 channels
            with tf.variable_scope("C1_Block"):
                C1_M = bs.SmallUniteConvolutionBlock(self.inPlaceHolder, kernalSize=8,
                                                     outChannels=16, gNum=4, blockName="Initial_Conv6x6_C1")
                C1_M = bs.MimicTransformerEncoder(C1_M,outputChannels=32,blockName="Transformer_0")
                self.C1 = C1 = bf.Pooling(C1_M, windowShape=[2, 2], poolingType="AVG", stride=[2, 2],
                                padding="VALID", name="DownSampling_1")
                print("C1 ",C1)
            ### 64 channels
            with tf.variable_scope("C2_Block"):
                C2_M = bs.SmallUniteConvolutionBlock(C1,kernalSize=4,
                                                     outChannels=32,gNum=4,blockName="Initial_Conv5x5_C2")
                C2_M = bs.MimicTransformerEncoder(C2_M, outputChannels=64, blockName="Transformer_1")
                self.C2 = C2 = bf.Pooling(C2_M, windowShape=[2, 2], poolingType="MAX", stride=[2, 2],
                                padding="VALID", name="DownSampling_2")
                print("C2 ",C2)
            ### 128 channels
            with tf.variable_scope("C3_Block"):
                C3_M = bs.SmallUniteConvolutionBlock(C2,kernalSize=4,
                                                     outChannels=64,gNum=4,blockName="Initial_Conv4x4_C3")
                C3_M = bs.MimicTransformerEncoder(C3_M, outputChannels=128, blockName="Transformer_2")
                self.C3 = C3 = bf.Pooling(C3_M, windowShape=[2, 2], poolingType="MAX", stride=[2, 2],
                                padding="VALID", name="DownSampling_3")
                print("C3 ",C3)
            ### 256 channels
            with tf.variable_scope("C4_Block"):
                C4_M = bs.SmallUniteConvolutionBlock(C3,kernalSize=2,
                                                     outChannels=128,gNum=4,blockName="Initial_Conv3x3_C4")
                C4_M = bs.MimicTransformerEncoder(C4_M, outputChannels=256, blockName="Transformer_3")
                self.C4 = C4 = bf.Pooling(C4_M, windowShape=[2, 2], poolingType="MAX", stride=[2, 2],
                                padding="VALID", name="DownSampling_4")
                print("C4 ",C4)
            ### 512 channels
            with tf.variable_scope("C5_Block"):
                C5_M = bs.SmallUniteConvolutionBlock(C4,kernalSize=1,
                                                     outChannels=256,gNum=4,blockName="Initial_Conv2x2_C5")
                C5_M = bs.MimicTransformerEncoder(C5_M, outputChannels=512, blockName="Transformer_5")
                self.C5 = C5 = bf.Pooling(C5_M, windowShape=[2, 2], poolingType="MAX", stride=[2, 2],
                                padding="VALID", name="DownSampling_5")
                print("C5 ",C5)


            #####################
            ### Up to Bottom
            #####################

            ### 512
            with tf.variable_scope("P5_Block"):
                self.P5 = P5_Out = bs.SmallUniteConvolutionBlock(C5, kernalSize=1,
                                                       outChannels=512, gNum=4, blockName="P5_Out")
                print("P5 ",P5_Out)

            ### 256
            with tf.variable_scope("P4_Block"):
                P5_Trans = bs.TransChannelsConvolutionBlock(P5_Out, kernalSize=1, outChannels=256
                                                            , blockName="P5_Trans")
                P5_Up = keras.layers.UpSampling2D(size=(2, 2),
                                                  name="UpSam_P5")(P5_Trans)
                P4_M = bs.SmallUniteConvolutionBlock(C4, kernalSize=1, outChannels=256, gNum=4,
                                                     blockName="P4_M")
                self.P4 = P4_Out = tf.add(P4_M, P5_Up, name="P4_Out")
                print("P4 ",P4_Out)

            ### 128
            with tf.variable_scope("P3_Block"):
                P4_Trans = bs.TransChannelsConvolutionBlock(P4_Out, kernalSize=1, outChannels=128,
                                                            blockName="P4_Trans")
                P4_Up = keras.layers.UpSampling2D(size=(2, 2),
                                                  name="UpSam_P4")(P4_Trans)
                P3_M = bs.SmallUniteConvolutionBlock(C3, kernalSize=1, outChannels=128, gNum=4,
                                                     blockName="P3_M")
                self.P3 = P3_Out = tf.add(P4_Up, P3_M, name="P3_Out")
                print("P3 ",P3_Out)

            ### 64
            with tf.variable_scope("P2_Block"):
                P3_Trans = bs.TransChannelsConvolutionBlock(P3_Out, kernalSize=1, outChannels=64,
                                                            blockName="P3_Trans")
                P3_Up = keras.layers.UpSampling2D(size=(2, 2),
                                                  name="UpSam_P3")(P3_Trans)
                P2_M = bs.SmallUniteConvolutionBlock(C2, kernalSize=1, outChannels=64, gNum=4,
                                                     blockName="P2_M")
                self.P2 = P2_Out = tf.add(P3_Up, P2_M, name="P2_Out")
                print("P2 ",P2_Out)


            ##########################
            ### sub process
            ##########################
            with tf.variable_scope("P2_D_Block"):
                P2_D = bs.SmallResBlockWithAVG2xDownSampling(self.P2,kernalSize=4,gNum=4,
                                                                   outChannels=64,blockName="P2_D_C1")
                P2_D = bs.SmallResBlockWithAVG2xDownSampling(P2_D,kernalSize=3,gNum=4,
                                                                   outChannels=128,blockName="P2_D_C2")
                P2_D = bs.SmallResBlockWithAVG2xDownSampling(P2_D,kernalSize=2,gNum=4,
                                                                   outChannels=256,blockName="P2_D_C3")
                self.P2_D_OUT  = bs.SmallUniteConvolutionBlock(P2_D, kernalSize=1,
                                                     outChannels=512, gNum=4, blockName="P2_D_C4")
            with tf.variable_scope("P3_D_Block"):
                P3_D = bs.SmallResBlockWithAVG2xDownSampling(self.P3,kernalSize=3,gNum=4,
                                                                   outChannels=128,blockName="P3_D_C1")
                P3_D = bs.SmallResBlockWithAVG2xDownSampling(P3_D,kernalSize=2,gNum=4,
                                                                   outChannels=256,blockName="P3_D_C2")
                self.P3_D_OUT  = bs.SmallUniteConvolutionBlock(P3_D,kernalSize=1,outChannels=512,
                                                     gNum=4,blockName="P3_D_C3")
            with tf.variable_scope("P4_D_Block"):
                P4_D = bs.SmallResBlockWithAVG2xDownSampling(self.P4,kernalSize=2,gNum=4,
                                                                   outChannels=256,blockName="P4_D_C1")
                self.P4_D_OUT = bs.SmallUniteConvolutionBlock(P4_D,kernalSize=1,outChannels=512,gNum=4,
                                                     blockName="P4_D_C2")
            with tf.variable_scope("P5_D_Block"):
                self.P5_D_OUT = bs.SmallUniteConvolutionBlock(self.P5,kernalSize=1,outChannels=512,gNum=4,
                                                     blockName="P5_D_C1")
            with tf.variable_scope("ImagesAdd"):
                ###2
                p2_weight = tf.Variable(initial_value=1.,dtype=tf.float32,name="p2_weight")
                p2_trans = tf.nn.sigmoid(p2_weight)
                p2_weight_out = tf.scalar_mul(scalar=p2_trans,x=self.P2_D_OUT)
                ###3
                p3_weight = tf.Variable(initial_value=1.,dtype=tf.float32,name="p3_weight")
                p3_trans = tf.nn.sigmoid(p3_weight)
                p3_weight_out = tf.scalar_mul(scalar=p3_trans,x=self.P3_D_OUT)
                ###4
                p4_weight = tf.Variable(initial_value=1.,dtype=tf.float32,name="p4_weight")
                p4_trans = tf.nn.sigmoid(p4_weight)
                p4_weight_out = tf.scalar_mul(scalar=p4_trans,x=self.P4_D_OUT)
                ###5
                p5_weight = tf.Variable(initial_value=1.,dtype=tf.float32,name="p5_weight")
                p5_trans = tf.nn.sigmoid(p5_weight)
                p5_weight_out = tf.scalar_mul(scalar=p5_trans,x=self.P5_D_OUT)
                mediumActiveMap = tf.concat(values=[p2_weight_out,p3_weight_out,p4_weight_out,p5_weight_out],axis=-1
                                            ,name = "FinalConcatInfor")
        return mediumActiveMap
#======打印训练集和测试集的大小======
print('train size: %s ,test size:%s' % (len(train_x), len(test_x)))

#======分批次 每个批次取100张======
batch_size = 100  #批的大小
num_batch = len(train_x) // batch_size  #完整地把训练集训练完,至少需要多少批

#======占位符======
x = tf.placeholder(tf.float32, [None, size, size, 3])  #占位符,图片
y_ = tf.placeholder(tf.float32, [None, 2])  #占位符,标签
keep_prob_5 = tf.placeholder(tf.float32)
keep_prob_75 = tf.placeholder(tf.float32)

#======网络======
Conv1 = Blocks.Conv(x, 3, 1, 32, keep_prob_5)
Conv2 = Blocks.Conv(Conv1, 3, 1, 64, keep_prob_5)
Conv3 = Blocks.Conv(Conv2, 3, 1, 64, keep_prob_5)
#print(Conv3.shape)
Conv3 = tf.reshape(
    Conv3,
    [-1, int(Conv3.shape[1]) * int(Conv3.shape[2]) * int(Conv3.shape[3])])
#print(Conv3.shape)
Affine = Blocks.Affine(Conv3, int(Conv3.shape[1]), 512, keep_prob_75)
Output = Blocks.Output(Affine, 512, 2)

#======损失函数======
#print(Output.shape)
#print(y_.shape)
cross_entropy = tf.reduce_mean(
    tf.nn.softmax_cross_entropy_with_logits(logits=Output, labels=y_))