Exemplo n.º 1
0
def main():
    print("Python module")
    #############################
    ## Pure C++ object wrapped
    c1 = shapes.Circle()
    c = shapes.Circle()
    print(c.X)  # Prints 0
    print(c.R)  # prints 1
    print(c.V)  # prints None
    c.X = 1234  # changes value
    print(c.X)  # Prints 1234

    #############################
    ## Totaly dynamic C++ object wrapped
    o = shapes.Object()
    o.X = 456  #
    print(o.X)  # Prints 1234
    ## NEED a better way to add symbols and avoid duplicates
    s = shapes.Symbol("Gromit")
    s = shapes.Symbol("Gromit")
    s = shapes.Symbol("Gromit")
    o.Gromit = 12
    o.Gromit = 13
    o.Gromit = 14
    print(o.Gromit)
Exemplo n.º 2
0
def fit_circle(points):
    """
    fits a circle to the given points. The method has been adapted from
        http://wiki.scipy.org/Cookbook/Least_Squares_Circle
    The function returns an instance of Circle
    """
    def calc_dist(xc, yc):
        """ calculate the distance of each point from the center (xc, yc) """
        return np.linalg.norm(points - np.array([[xc, yc]]), axis=0)
    
    def circle_implicit(beta, x):
        """ implicit definition of the circle """
        return (x[0] - beta[0])**2 + (x[1] - beta[1])**2 - beta[2]**2

    # coordinates of the bary center
    x_m, y_m = np.mean(points, axis=0)

    # initial guess for parameters
    R_m = calc_dist(x_m, y_m).mean()
    beta0 = [x_m, y_m, R_m]    
    
    # for implicit function :
    #       data.x contains both coordinates of the points (data.x = [x, y])
    #       data.y is the dimensionality of the response
    lsc_data  = odr.Data(points.T, y=1)
    lsc_model = odr.Model(circle_implicit, implicit=True)
    lsc_odr   = odr.ODR(lsc_data, lsc_model, beta0)
    lsc_out   = lsc_odr.run()
    
    # collect result
    xc, yc, R = lsc_out.beta
    return shapes.Circle(xc, yc, R)
Exemplo n.º 3
0
def place_random_creature(environment):
    if False:
        environment.queue_creature(create_master_creature())
    else:
        r_pos = gen.random_pos(width, height, creature_radius)
        name = str(r.randint(0, 1000000))
        name = "0" * (4 - len(name)) + name
        body = gen.Body(start_mass, shapes.Circle(r_pos, creature_radius))
        brain = gen.Brain()
        legs = gen.Legs()
        mouth = gen.Mouth(3, 0)
        fission = gen.Fission(mutation_model, init_mutation_model)

        creature = gen.Creature(body, name)
        creature.add_organ(brain)
        creature.add_organ(legs)
        creature.add_organ(mouth)
        creature.add_organ(fission)

        for organ in creature.organs:
            organ.mutate(init_mutation_model)

        r_pos = gen.random_pos(width, height, creature_radius)
        creature.pos = [r_pos[0], r_pos[1]]
        environment.queue_creature(creature)
Exemplo n.º 4
0
    def __init__(self):
        super(App, self).__init__(caption="Quadtrees", width=512, height=512)
        self.set_mouse_visible(False)
        self.set_location(0, 900 - self.height)
        self.keys = pyglet.window.key.KeyStateHandler()
        self.push_handlers(self.keys)

        self.paused = True
        self.operation = None

        self.terrain = terrain.TerrainTree(0, 0, 512, max_level=5)
        self.player = obj.GameObject(self.terrain.root.rect.width // 2,
                                     self.terrain.root.rect.height // 2)
        self.brush = shapes.Circle(0, 0, 128)
        self.brush_type = 1
        self.highlight = collections.deque()
        self.highlight_cursor = None

        self.render_mode = 0

        self.debug_label = pyglet.text.Label(text='LABEL',
                                             font_size=18,
                                             x=self.width - 20,
                                             y=self.height - 20,
                                             anchor_x='right',
                                             anchor_y='top',
                                             color=(255, 255, 255, 255))

        self.play()
        self.fps_display = pyglet.clock.ClockDisplay()
Exemplo n.º 5
0
    def __init__(self):
        gtk.DrawingArea.__init__(self)
        self.__checkerBoard = graphics.getCheckerPattern(16)

        self.shapes = []
        vPoly = shapes.Polygon([
            shapes.Point(10, 10),
            shapes.Point(10, 86),
            shapes.Point(40, 86),
            shapes.Point(86, 10),
        ])
        iPoly = shapes.Polygon([
            shapes.Point(106, 10),
            shapes.Point(96, 86),
            shapes.Point(140, 86),
            shapes.Point(120, 50),
            shapes.Point(160, 10),
        ])
        circle = shapes.Circle(35)
        circle.setCenter(shapes.Point(200, 48))
        self.shapes.append(vPoly)
        self.shapes.append(iPoly)
        self.shapes.append(circle)

        self.set_size_request(256, 96)
Exemplo n.º 6
0
def chair_constructor(side, leg_side, name):
    """Footprint of a four legged classic chair"""
    leg1 = shapes.Circle(leg_side)
    leg1.color("r")
    leg2 = shapes.Circle(leg_side)
    leg2.traslate(side, 0)
    leg2.color("r")
    leg3 = shapes.Circle(leg_side)
    leg3.traslate(side, side)
    leg3.color("k")
    leg4 = shapes.Circle(leg_side)
    leg4.traslate(0, side)
    leg4.color("r")

    legs = [leg1, leg2, leg3, leg4]
    chair = shapes.CompoundShape(legs, name)
    return chair
Exemplo n.º 7
0
 def mount_sensor(self, name: str, beam: float, range: float, accuracy: float, mnt_pt: Point, mnt_orient: float):
     """Base behaviour is to update safe-radius of the vehicle taking into
     account sensor accuracy
     """
     if accuracy > self.max_sensor_accuracy:
         self.max_sensor_accuracy = accuracy
     self.safe_radius = self.shape.outer_radius() + self.max_sensor_accuracy
     
     # Update safe region shape
     self.safe_region = shapes.Circle(self.safe_radius, res=1)
Exemplo n.º 8
0
    def create_god(self):
        from components import component
        god_id = self.create_entity()

        self.create_component(god_id, component.God)
        self.create_component(god_id, component.Position)
        self.create_component(
            god_id, component.Render,
            shapes.Circle(color=pygame.color.THECOLORS['darkred'], radius=20))
        return god_id
Exemplo n.º 9
0
 def __init__(self, controller, maxX, maxY):
     ShapeTool.__init__(self, controller, maxX, maxY)
     self.__drawing = False
     self.__circle = shapes.Circle(
         int(self.getController().mapTileSize() / 2),
         int(self.getController().mapTileSize() / 2))
     self.setSnapInterval(int(self.getController().mapTileSize() / 2))
     # A good default value, since the radius can't be negative
     self.__oldRadius = -1
     self.setInstructions("Click to set the center point. Click" +
                          " again to set the radius")
Exemplo n.º 10
0
 def create_bot(self, position, radius=15):
     from components import component
     bot_id = self.create_entity()
     self.create_component(bot_id, component.Brain)
     self.create_component(bot_id, component.Position, position=position)
     self.create_component(bot_id, component.Render,
                           shapes.Circle(color=colors.red, radius=radius))
     self.create_component(bot_id, component.Boundary, radius=radius)
     self.create_component(bot_id, component.Vision, radius=(radius * 8))
     self.create_component(bot_id, component.Log, bot_id)
     return bot_id
Exemplo n.º 11
0
 def mouseButtonPress(self, button, time):
     if self.__drawing:
         controller = self.getController()
         action = undo.ShapeAddAction(controller, self.__circle)
         controller.addUndoAction(action)
         controller.addShape(self.__circle)
         self.__circle = shapes.Circle(int(controller.mapTileSize() / 2),
                                       int(controller.mapTileSize() / 2))
         self.__drawing = False
     else:
         if button == 1:
             self.__circle.setCenter(shapes.Point(self.x(), self.y()))
             self.__drawing = True
Exemplo n.º 12
0
    def __init__(self, name: str, chassis_shape: ChassisShape):
        """
        Defines dimensions and graphical aspect of the vehicle
        
        Parameters
        ----------
        name : str
            name of the vehicle

        color : str
            color string as allowed by matplotlib's plot method
        """
        # Position defaults to the origin of the reference system
        self.position = Point(0, 0)

        # Orientation is taken from the x (horizontal) axis and is stored
        # in radian
        self.orientation = 0 # rad
        
        # Vehicle path.
        # List of vehicle position and orientation after every movement
        self.path = []
        self.seq_counter = 0

        # Dimensions
        self.length = 0.0
        self.width = 0.0
        self.color = "r"

        # Vehicle name will be shown at vehicle position
        self.name = name

        # Vehicle Shape. 
        self.shape = chassis_shape
        
        # Calculate safe region with a margin
        self.safe_radius = chassis_shape.outer_radius()
        
        # Safe region shape
        self.safe_region = shapes.Circle(self.safe_radius, res=1)

        # Sensor list as dictionay; this way you can read sensor by name
        self.sensors = dict()
        self.max_sensor_accuracy = 0
        
        # Flatland Environment 
        self.flatland = None
        
        # Tracing flag
        self.tracing = False
Exemplo n.º 13
0
def testGrad():
    N = 50
    rad = constants.R_inner
    L = 4 * rad + 2

    shapecoll = shapes.ShapeCollection()
    circ1 = shapes.Circle((0.5, 0), rad)
    circ2 = shapes.Circle((-0.5, 0), rad)
    shapecoll.addShape(circ1)
    shapecoll.addShape(circ2)
    circ_ls = level_set.LevelSet(N, N, L, L, shapecoll)

    SDF = circ_ls.getSDF()

    circ_ls.reinitialize()

    grad1 = circ_ls.computeGrad(level_set.GradientMode.UPWIND_FIRST)
    # grad2 = circ_ls.computeGrad(level_set.GradientMode.UPWIND_SECOND)

    for i in range(100):
        circ_ls.advance(1)
        grad = circ_ls.computeGrad()
        print(np.max(grad[circ_ls.getInsidePoints()]))
        # circ_ls.make_plot(thing_to_plot = grad)

    grad_final = circ_ls.computeGrad()

    circ_ls.make_plot(thing_to_plot=grad_final)
    circ_ls.make_plot()

    plt.show()
    #
    # axes[0].set(aspect='equal')
    # axes[1].set(aspect='equal')
    # axes[2].set(aspect='equal')

    plt.show()
Exemplo n.º 14
0
def create_master_creature():
    name = "Genesis"
    body = gen.Body(start_mass, shapes.Circle((100, 100), creature_radius))
    body.rotation = 90
    brain = gen.Brain()
    legs = gen.Legs()
    mouth = gen.Mouth(1, 0, 10, 1)
    fission = gen.Fission(mutation_model)
    eye_left = gen.EuclideanEye(10, 40, 6)
    eye_right = gen.EuclideanEye(10, -40, 6)

    creature = gen.Creature(body, name)
    creature.add_organ(brain)
    creature.add_organ(legs)
    creature.add_organ(mouth)
    creature.add_organ(fission)
    creature.add_organ(eye_left)
    creature.add_organ(eye_right)

    fission_hn = brain.hidden_layer[1]
    body.age_neuron.connect_to_neuron(fission_hn, 1)
    body.mass_neuron.connect_to_neuron(fission_hn, 1)
    fission_hn.connect_to_neuron(fission.fission_neuron, 1)

    eye_left_hn = brain.hidden_layer[2]
    eye_left.vision_neuron.connect_to_neuron(eye_left_hn, 1)
    eye_left_hn.connect_to_neuron(legs.turn_clockwise_neuron, 1)

    eye_right_hn = brain.hidden_layer[3]
    eye_right.vision_neuron.connect_to_neuron(eye_right_hn, 1)
    eye_right_hn.connect_to_neuron(legs.turn_clockwise_neuron, -1)

    has_eaten_hn = brain.hidden_layer[4]
    mouth.has_eaten_neuron.connect_to_neuron(has_eaten_hn, 1)
    has_eaten_hn.connect_to_neuron(legs.forward_neuron, -0.9)
    has_eaten_hn.connect_to_neuron(mouth.eat_neuron, 2)

    distance_moved_hn = brain.hidden_layer[5]
    legs.distance_moved_neuron.connect_to_neuron(distance_moved_hn, 1)
    brain.bias_input_layer.connect_to_neuron(distance_moved_hn, -1)
    distance_moved_hn.connect_to_neuron(legs.turn_clockwise_neuron, 1)

    brain.bias_hidden_layer.connect_to_neuron(fission.fission_neuron, -0.7)
    brain.bias_hidden_layer.connect_to_neuron(legs.forward_neuron, 1)
    brain.bias_hidden_layer.connect_to_neuron(mouth.eat_neuron, 0.1)

    r_pos = gen.random_pos(width, height, creature_radius)
    creature.pos = [r_pos[0], r_pos[1]]
    return creature
Exemplo n.º 15
0
    def computeCircVals(num, show_plot=False):
        # make circle
        shapecoll = shapes.ShapeCollection()
        circ = shapes.Circle((1, 1), rad)
        shapecoll.addShape(circ)
        circ_ls = level_set.LevelSet(num, num, L, L, shapecoll)
        if show_plot:
            circ_ls.make_plot()

        circ_area = circ_ls.computeArea()
        circ_perim = circ_ls.computePerim()

        gradNorm = circ_ls.computeUpwindGrad()

        return circ_area, circ_perim
Exemplo n.º 16
0
 def __parseCircle(self, circle):
     c = shapes.Circle(0.0)
     if "center" in circle:
         c.setCenter(
             shapes.Point(circle["center"]["x"], circle["center"]["y"]))
     else:
         log.error("Circle specified with no center")
     if "radius" in circle:
         c.setRadius(circle["radius"])
     else:
         log.error("Circle specified with no radius")
     if "damage" in circle:
         c.damage = circle["damage"]
     if "friction" in circle:
         c.friction = circle["friction"]
     if "restitution" in circle:
         c.restitution = circle["restitution"]
     return c
Exemplo n.º 17
0
def create_visualise_bounding_button():
    button_area = shapes.Rectangle(0, 0, 30, 30)
    button = rendering.Button(button_area)
    icon_shapes = [
        shapes.Circle((8, 10), 7),
        shapes.LineSegment((5, 28), (28, 18))
    ]
    for shape in icon_shapes:
        if shape.has_area():
            shape_graphic = rendering.SimpleMonoColouredGraphic(
                shape, colours.BLUE)
        else:
            shape_graphic = rendering.SimpleOutlineGraphic(shape, colours.BLUE)
        button.add_canvas(shape_graphic)
        button.add_canvas(
            rendering.SimpleOutlineGraphic(shape.to_bounding_rectangle(),
                                           colours.RED))

    return button
Exemplo n.º 18
0
    def load_from_file(self):
        """Загрузить распределение из файла."""

        try:
            loaded_file, _ = QtWidgets.QFileDialog.getOpenFileName(
                None, 'Введите имя файла', self.work_dir,
                'Файлы распределений частиц (*.tsv)')

            self.loaded_files.append(loaded_file)

            import shapes

            with open(loaded_file, 'r') as f:
                loaded = []
                for strings_list in csv.reader(f, delimiter='\t'):
                    numbers_list = []
                    for string in strings_list:
                        numbers_list.append(float(string))
                    loaded.append(tuple(numbers_list))

                # определение размерности задачи
                for i in loaded:
                    if i[2]:  # хотя бы один параметр z != 0
                        self.options['dim_ind'] = 1
                        break

                for i in loaded:
                    if self.options['dim_ind'] == 0:  # 2D
                        self.loaded_particles.append(
                            shapes.Circle(x=i[0], y=i[1], d=i[3]))
                    elif self.options['dim_ind'] == 1:  # 3D
                        self.loaded_particles.append(
                            shapes.Sphere(x=i[0], y=i[1], z=i[2], d=i[3]))

                self.message('Загружен файл: {0}'.format(loaded_file))

            self.all_particles.extend(self.loaded_particles)

            self.cleanDistributions.setEnabled(True)

        except FileNotFoundError:
            self.message(
                'Распределение не загружено!\nПричина: не введено имя файла')
Exemplo n.º 19
0
    def calc_regular_distribution(self):
        """Calculation regular distribution."""

        import shapes

        self.regular_particles = []  # очистка

        x0 = self.options['regular_distribution'][0][0]
        dx = self.options['regular_distribution'][1][0]
        nx = self.options['regular_distribution'][2][0]

        y0 = self.options['regular_distribution'][0][1]
        dy = self.options['regular_distribution'][1][1]
        ny = self.options['regular_distribution'][2][1]

        if self.options['dim_ind'] == 1:  # 3D
            z0 = self.options['regular_distribution'][0][2]
            dz = self.options['regular_distribution'][1][2]
            nz = self.options['regular_distribution'][2][2]

        for x in [x0 + dx * i for i in range(nx)]:
            for y in [y0 + dy * i for i in range(ny)]:
                if self.options['dim_ind'] == 1:  # 3D
                    for z in [z0 + dz * i for i in range(nz)]:
                        particle = shapes.Sphere(
                            x, y, z,
                            self.options['regular_distribution_diameter'])
                        self.regular_particles.append(particle)
                else:  # 2D
                    # z = 0
                    particle = shapes.Circle(
                        x, y, self.options['regular_distribution_diameter'])
                    self.regular_particles.append(particle)

        self.all_particles.extend(
            self.regular_particles)  # расширить список всех частиц

        self.button_save.setEnabled(True)
        self.clean_distributions.setEnabled(True)

        self.message('Регулярное распределение частиц посчитано')
Exemplo n.º 20
0
def readShapesFromJson(data):
    shapes_list = []
    if 'Figures' not in data.keys():
        return []
    palette = data['Palette']
    i = 1
    for shape in data['Figures']:
        if (validate.validateShape(shape)):
            color = ''
            if 'color' in shape:
                if validate.validateColor(shape['color'], palette):
                    color = shape['color']
            if shape['type'] == 'point':
                shapes_list.append(shapes.Point(shape['x'], shape['y']))
            elif shape['type'] == 'polygon':
                points = []
                for point in shape['points']:
                    points.append(shapes.Point(point[0], point[1]))
                shapes_list.append(shapes.Polygon(points, color))
            elif shape['type'] == 'rectangle':
                point = shapes.Point(shape['x'], shape['y'])
                rect = shapes.Rectangle(point, shape['width'], shape['height'],
                                        color)
                shapes_list.append(rect)
            elif shape['type'] == 'square':
                point = shapes.Point(shape['x'], shape['y'])
                shapes_list.append(
                    shapes.Square(point, shape.get('size'), color))
            elif shape['type'] == 'circle':
                point = shapes.Point(shape['x'], shape['y'])
                shapes_list.append(
                    shapes.Circle(point, shape.get('radius'), color))
            else:
                print('Wrong type in Figure number', i, 'in file.')
        else:
            print('Wrong parameters in Figure number', i, 'in file.')
        i = i + 1
    return shapes_list
Exemplo n.º 21
0
def main():
    bates_srm = BatesSRM()

    shapecoll = shapes.ShapeCollection()
    circ = shapes.Circle((0, 0), R_inner)
    shapecoll.addShape(circ)

    bates_grain_ls = LevelSetSRM(shapecoll)

    theta = np.arange(0, 4) * np.pi / 4.
    lines_c = []

    lines = [
        shapes.LineSegment(
            [finocyl_spoke_len * np.cos(t), finocyl_spoke_len * np.sin(t)],
            [-finocyl_spoke_len * np.cos(t), -finocyl_spoke_len * np.sin(t)],
            width=finocyl_spoke_width) for t in theta
    ]
    [shapecoll.addShape(l) for l in lines]
    finocyl_grain_ls = LevelSetSRM(shapecoll)

    sustainer_assembly = SRM_Assembly({bates_grain_ls: 5})

    booster_assembly = SRM_Assembly({finocyl_grain_ls: 2, bates_grain_ls: 5})

    Pb, Tb, Ab, xb, tb = runAndTimeSRM(booster_assembly, "Booster", True)

    np.savetxt("results/Pb.txt", Pb)
    np.savetxt("results/Tb.txt", Tb)
    np.savetxt("results/Ab.txt", Ab)
    np.savetxt("results/xb.txt", xb)

    Psus, Tsus, Asus, xsus, tsus = runAndTimeSRM(sustainer_assembly,
                                                 "Sustainer", True)
    np.savetxt("results/Psus.txt", Psus)
    np.savetxt("results/Tsus.txt", Tsus)
    np.savetxt("results/Asus.txt", Asus)
    np.savetxt("results/xsus.txt", xsus)
Exemplo n.º 22
0
#!/usr/bin/python3

import shapes

square1 = shapes.Square(3.0)
circle1 = shapes.Circle(4.0)

print("length of square1 = " + str(square1.getSide()))
print("radius of circle1 = " + str(circle1.getRadius()))
Exemplo n.º 23
0

class View2D:
    """View2D."""
    def __init__(self, edge, data):
        plt.close('all')
        plt.figure(num='Микроструктура', figsize=(7, 7), dpi=100)

        ax = plt.axes()
        FrontView(axes=ax, data=data, matrix_edge=edge)

        plt.tight_layout()
        plt.show()


if __name__ == '__main__':

    import shapes

    m = shapes.CubeMatrix(edge=100.)

    p1 = shapes.Sphere(x=0., y=20., z=40., d=10.)
    p2 = shapes.Sphere(x=50., y=50., z=50., d=20.)

    View3D(m.edge, [p1, p2])

    p3 = shapes.Circle(x=10., y=40, d=30.)
    p4 = shapes.Circle(x=50., y=75., d=15.)

    View2D(m.edge, [p3, p4])
Exemplo n.º 24
0
 def make_components(self):
     shape = shapes.Circle(self.pos, self.radius, 10)
     component = Component(shape, self.water_color)
     self.components.append(component)
Exemplo n.º 25
0
 def make_components(self):
     shape = shapes.Circle(self.pos, self.radius, 5, angle=math.pi)
     c = Component(shape, self.hill_color)
     self.components.append(c)
Exemplo n.º 26
0
import shapes
import base

xy = [0, 0]

triangle = shapes.Triangle(xy, 1, 4)
circle = shapes.Circle(xy, 2)
square = shapes.Square(xy, 1)
ellipse = shapes.Ellipse(xy, 3, 2)
rectangle = shapes.Rectangle(xy, 14, 3)

mylist = [triangle, square, rectangle, circle, ellipse]

for item in mylist:
    if isinstance(item, base.Polygon):
        print(f"{item} located at {item.center} of size {item._size}")
    else:
        print(f"{item} located at {item.center} of radius {item.radius}")
Exemplo n.º 27
0
def create_obstacle_circle(center, radius):
    o = Obstacle(lambda r: dist(r, center) - radius,
                 lambda r: normalize(r - center),
                 shapes.Circle(center, radius))
    o.center = center
    return o
Exemplo n.º 28
0

class Program(object):
    def run(self, new_shapes):
        while 1:
            command = input(
                "Please enter a shape (cube, triangular pyramid, circle, quadrilateral, pentagon or triangle). Type 'exit' to quit the program: "
            )

            for shape in new_shapes:
                if command in shape.name:
                    shape.get_shape_ui().get_details()
                    print("Area/Volume: ", shape.algorithm1(),
                          "\nPerimeter/Surface area: ", shape.algorithm2())
                elif "exit" in command:
                    sys.exit("Seeya!")


SHAPES = [
    shapes.TwoDAdapter(shapes.Circle("circle")),
    shapes.TwoDAdapter(shapes.Quadrilateral("quadrilateral")),
    shapes.TwoDAdapter(shapes.Pentagon("pentagon")),
    shapes.TwoDAdapter(shapes.Triangle("triangle")),
    tridshapes.TriDAdapter(tridshapes.RectangularPrism('cube')),
    tridshapes.TriDAdapter(tridshapes.TriPyramid('triangular pyramid'))
]

program = Program()

program.run(SHAPES)
Exemplo n.º 29
0
r1.get_name()
print("side is ", end="")
r1.get_side()
print("\n")


s1 = shapes.Square()
s1.set_name()
s1.get_name()
print("side is ", end="")
s1.get_side()
print("\n")


ell1 = shapes.Ellipse()
ell1.set_name()
ell1.get_name()
ell1.set_params(40, 80)
print("Area is ", end="")
ell1.get_area()
print("\n")


c1 = shapes.Circle()
c1.set_name()
c1.get_name()
c1.set_radius(20)
print("Area is ", end="")
c1.get_area()
print("\n")
Exemplo n.º 30
0
def main():
    width = int(sys.argv[1])
    height = int(sys.argv[2])
    max_obstacles = int(sys.argv[3])
    num_approx_points = int(sys.argv[4])
    file_name = str(sys.argv[5])

    if os.path.exists(file_name):
        print(
            'The map with the give name already exists. Please delete it manually before proceeding to overwrite it.'
        )

    boundary_offset = 10
    min_length = 40
    max_length = 70
    obstacles_list = []
    obstacles_type = []

    # Dummy obstacle to prevent the starting point of seekers
    # from getting blocked by some obstacle
    obs = shapes.Square((30, 30), 60)
    obstacles_list.append(obs)
    obstacles_type.append('square')

    num_obstacles = 0
    while num_obstacles < max_obstacles:
        obs_valid = False
        while not obs_valid:
            cx = random.randint(max_length + boundary_offset,
                                width - max_length - boundary_offset)
            cy = random.randint(max_length + boundary_offset,
                                height - max_length - boundary_offset)
            length = random.randint(min_length, max_length)
            choice = random.randint(0, 1)
            choice = 1
            if choice == 0:
                obs = shapes.Square((cx, cy), length)
                obs_type = 'square'
            else:
                obs = shapes.Circle((cx, cy), length, num_approx_points)
                obs_type = 'circle'

            collision = False
            for other in obstacles_list:
                if obs.check_aabb_collision(other, 20):
                    collision = True
                    break
            if not collision:
                obstacles_list.append(obs)
                obstacles_type.append(obs_type)
                obs_valid = True
                num_obstacles += 1

    f = open(file_name, 'w+')

    f.write(str(width) + ', ' + str(height) + '\n')
    for obs, obs_type in zip(obstacles_list[1:], obstacles_type[1:]):
        centre = obs.get_centre()
        token = obs_type + ': ' + str(centre[0]) + ', ' + str(centre[1])
        if obs_type == 'circle':
            token += ', ' + str(
                obs.get_radius()) + ',' + str(num_approx_points)
        elif obs_type == 'square':
            token += ', ' + str(obs.get_length())

        token += '\n'
        f.write(token)