Beispiel #1
0
def where_did_it_go(cfg: configuration.Configuration, movie, index):
    path = cfg.path.points
    cheerio = path[index]
    box_size = cfg.cheerio_radius * 6
    safety_distance = cfg.cheerio_radius * 3 + cfg.stone_size
    start_x = cheerio.x + safety_distance
    box1 = rectangle.Rectangle(start_x, cheerio.y - box_size, start_x + box_size, cheerio.y)
    box2 = rectangle.Rectangle(start_x, cheerio.y, start_x + box_size, cheerio.y + box_size)

    while index < len(path) and path[index].x < cheerio.x + cfg.cheerio_radius:
        index += 1
    if index == len(path):
        return "done"
    if abs(path[index].y - cheerio.y) < cfg.cheerio_radius / 8:
        return "skip"
    density1 = box_density(cfg, box1)
    density2 = box_density(cfg, box2)
    if abs(density1 - density2) < 0.1:
        return "skip"

    if movie:
        if density1 > density2:
            color1 = "red"
            color2 = "blue"
        else:
            color1 = "blue"
            color2 = "red"
        movie.background([(box1, color1), (box2, color2),
                          (circle.Circle(cheerio, cfg.cheerio_radius / 3), "green")])

    return (density1 > density2) == (path[index].y > cheerio.y)
Beispiel #2
0
    def __init__(self, width, height, fps):
        game_mouse.Game.__init__(self, "Shapes", width, height, fps)

        self.sun = circle.Circle(0, 0, 150, (255, 255, 0))
        self.sky = rectangle.Rectangle(600, 400, 0, 0, (20, 160, 255))
        self.houseBody = rectangle.Rectangle(400, 250, 100, 200,
                                             (247, 210, 45))
        self.door = rectangle.Rectangle(70, 150, 265, 300, (64, 52, 12))
        self.roof = triangle.Triangle([(300, 50), (550, 200), (50, 200)],
                                      (117, 8, 8))
        return
Beispiel #3
0
def main():
    rec1 = rectangle.Rectangle(10, 20)
    print(rec1)

    rec2 = rectangle.Rectangle(height=40, width=20)
    print(rec2)

    print('Width = ', rec1.get_width())
    print('Height = ', rec1.get_height())

    rec1.set_width(50)
    rec1.set_height(100)
    print(rec1)

    print('Area = ', rec1.get_area())
    def domination_rectangle(self, p, r, ref_rect):
        """
        Given two points, returns the rectangle area in 
        which point p dominates point r. 

            Input: p->[x1,y1] & r->[x2,y2]

            Output: Rectangle(bottom_left, top_right)
                    or None otherwise
        """

        # Find the domination segments for every query dimension
        domination_segs = []
        for dimension in self.dims:
            domination_segs.append(
                self.domination_segment(p, r, dimension, ref_rect))

        # Construct the rectangle
        if None not in domination_segs:
            # Rectangle's points
            bottom_left = []
            top_right = []
            for indx, segment in enumerate(domination_segs):

                bottom_left.append(segment[0][indx])
                top_right.append(segment[1][indx])

            # Build a Rectangle instance
            domination_rect = rect.Rectangle(bottom_left, top_right)
        else:

            domination_rect = None

        # Return
        return domination_rect
    def game_logic(self, keys, newkeys, buttons, newbuttons, mouse_position):
        x = mouse_position[0]
        y = mouse_position[1]

        if pygame.K_c in newkeys:
            self.circles.append(circle.Circle(x, y, self.width, self.height))
        if pygame.K_r in newkeys:
            self.rectangles.append(
                rectangle.Rectangle(x, y, self.width, self.height))
        if pygame.K_p in newkeys:
            self.polygons.append(polygon.Polygon(x, y, self.width,
                                                 self.height))

        if 1 in newbuttons:
            print("button clicked")

        for c in self.circles:
            c.move_logic(x, y)
            for c2 in self.circles:
                if c2 is not c:
                    if c.collision_logic_c(c2):
                        print("boom-c")
            for r in self.rectangles:
                if c.collision_logic_p(r):
                    print("boom-c")
            for p in self.polygons:
                if c.collision_logic_p(p):
                    print("boom-c")
        for r in self.rectangles:
            r.move_logic()
        for p in self.polygons:
            p.move_logic()

        return
Beispiel #6
0
    def __init__(self, filename, x, y, h, w):
        '''
		Constructs a surface object
		paramlist: filename (file name for image file), x (x coordinate), y (y coordinate), h (height), w (width)
		return: none
		'''
        self.image = filename
        self.rect = rectangle.Rectangle(x, y, h, w)
Beispiel #7
0
    def CalculRectangleActif(self, centre, rayon, direction, d):

        p = [
            centre[0] + rayon * sin(direction),
            centre[1] - rayon * cos(direction)
        ]
        rec = rectangle.Rectangle(p[0], p[1], direction, d + rayon, 2 * rayon)
        return rec
Beispiel #8
0
 def __init__(self):
     '''
     '''
     self._parent = None
     self._batch = None
     self._bg_group = None
     self._fg_group = None
     self._background = rectangle.Rectangle(filled=True)
     self._foreground = rectangle.Rectangle(filled=False)
     self._focusable = False
     self._activable = False
     self._style = theme.default
     self._state = state.default
     self._minimum_size = [0,0]
     self._size_request = [0,0]
     self._size_allocation = [0,0]
     self._expand = [True,True]
     self._position = [0,0]
     self._deleted = True
Beispiel #9
0
def test_rectangle_10_20():
    rect = rectangle.Rectangle(10.0, 20.0)
    rect.print()
    area = rect.area()
    perimeter = rect.perimeter()
    assert 200.0 == area and 60.0 == perimeter


# test_circle_0()
# test_circle_10()
# test_rectangle_10_20()
Beispiel #10
0
def crea_figura(tipus):
    if (tipus == 'C'):
        fig = cercle.Cercle()
    elif (tipus == 'T'):
        fig = triangle.Triangle()
    elif (tipus == 'R'):
        fig = rectangle.Rectangle()
    else:
        raise Exception('Tipus de figura no valid')
    fig.llegeix()
    return fig
Beispiel #11
0
    def inicializeMap(self, matrix, mode=None):
        if mode == 'creation':
            grassImg = config.Config.GRASS_IMAGE
            regPathImg = config.Config.REGULAR_PATH_IMAGE
            spawnImg = config.Config.SPAWN_IMAGE
            desPawnImg = config.Config.DESPAWN_IMAGE
            centralPathImg = config.Config.CENTRAL_PATH_IMAGE
            changeDirImg = config.Config.CHANGEDIR_IMAGE
        else:
            grassImg = config.Config.GRASS_IMAGE
            regPathImg = config.Config.REGULAR_PATH_IMAGE
            spawnImg = config.Config.REGULAR_PATH_IMAGE
            desPawnImg = config.Config.REGULAR_PATH_IMAGE
            centralPathImg = config.Config.REGULAR_PATH_IMAGE
            changeDirImg = config.Config.REGULAR_PATH_IMAGE

        x, y = 0, 0
        for i in range(0, self._dimension[0]):
            x = 0
            for j in range(0, self._dimension[1]):
                if matrix[i][j] == config.Config.MAP_NUMBMATRIX_GRASS:
                    self._map[i][j] = (0,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(), grassImg))

                elif matrix[i][j] == config.Config.MAP_NUMBMATRIX_PATH:
                    self._map[i][j] = (1,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(), regPathImg))

                elif matrix[i][j] == config.Config.MAP_NUMBMATRIX_SPAWN:
                    self._map[i][j] = (2,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(), spawnImg))

                elif matrix[i][j] == config.Config.MAP_NUMBMATRIX_DESPAWN:
                    self._map[i][j] = (3,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(), desPawnImg))

                elif matrix[i][j] == config.Config.MAP_NUMBMATRIX_CENTRALPATH:
                    self._map[i][j] = (4,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(),
                                           centralPathImg))

                elif matrix[i][
                        j] == config.Config.MAP_NUMBMATRIX_CHANGEDIRECTION:
                    self._map[i][j] = (5,
                                       rectangle.Rectangle(
                                           (x, y), self.getRectWidth(),
                                           self.getRectHeight(), changeDirImg))

                x += self.getRectWidth()
            y += self.getRectHeight()
Beispiel #12
0
def boxes_stats(cfg, box_size_in_cheerio_radii=6):
    size = box_size_in_cheerio_radii * cfg.cheerio_radius
    index = 0
    path = cfg.path.points
    result = []
    while index < len(path) and path[index].x < 1 - size:
        p = path[index]
        box = rectangle.Rectangle(p.x, p.y - size / 2, p.x + size, p.y + size / 2)
        r, ant_res = run.Run(run.AntRunner(cfg, index), containing_box=box).run()
        result.append((box_density(cfg, box), ant_res, MotionPath(r).length()))
        while index < len(path) and path[index].x < box.qx:
            index += 1
    return result
Beispiel #13
0
def main():
    s1 = circle.Circle(10)
    s2 = rectangle.Rectangle(10, 5)
    s3 = rectangle.Square(5)

    triangles = [
        triangle.IsocelesTriangle(10, 10),
        triangle.EquilateralTriangle(5)
    ]

    shapes = [s1, s2, s3] + triangles
    for s in shapes:
        s.print_all()
Beispiel #14
0
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("n",
                        type=int,
                        help="Number of squares to attempt to fit")
    parser.add_argument("--up-to",
                        action="store_true",
                        default=False,
                        help="Show results in csv format up to n")
    args = parser.parse_args()

    if args.up_to:
        for i in range(1, args.n):
            square = rectangle.Rectangle(Fraction(1, 1))
            solution = square.solve(i)
            print("%s,%s,%s" % (i, float(solution), str(solution)))

    else:
        square = rectangle.Rectangle(Fraction(1, 1))
        solved = square.solve(args.n)
        print("Efficieny of %s tiles is %s (%s)" %
              (args.n, float(solved), str(solved)))
Beispiel #15
0
def boxes(cfg, box_size_in_cheerio_radii=6, draw=True):
    if draw:
        movie = Movie()
        movie.background([(cfg, "black")])
    size = box_size_in_cheerio_radii * cfg.cheerio_radius

    index = 0
    path = cfg.path.points
    result = []
    while index < len(path) and path[index].x < 1 - size:
        p = path[index]
        box = rectangle.Rectangle(p.x, p.y - size / 2, p.x + size, p.y + size / 2)

        good = 0
        times = 10
        for i in range(times):
            cfg.start = p
            cfg.reset_runseed()
            r, sim_res = run.Run(run.SimulationRunner(cfg), containing_box=box).run()
            if sim_res:
                good += 1
            if draw:
                if sim_res:
                    color = "green"
                else:
                    color = "black"
                movie.background([(MotionPath(r), color)])

        r, ant_res = run.Run(run.AntRunner(cfg, index), containing_box=box).run()
        if draw:
            if ant_res:
                color = "green"
            else:
                color = "black"
            movie.background([(MotionPath(r), "blue")])
            box.add_text('{:.0f}%,{:.0f}%'.format(box_density(cfg, box) * 100, good / times * 100))
            movie.background([(box, color)])

        result.append((box_density(cfg, box), ant_res, good / times))
        while index < len(path) and path[index].x < box.qx:
            index += 1

    if draw:
        movie.save_figure(cfg.file_name + "_boxes")
        movie.close()
        # movie.just_draw()
    return result
def startApp():

    width = 0
    length = 0

    try:
        width = float(input('Please specify the width: '))
        length = float(input('Please specify the length: '))
    except ValueError:
        print('Please type digits only')

        return startApp()

    rec = r.Rectangle(width,length)

    rec.display_area()
    rec.display_perimeter()
    print()

    startApp()
Beispiel #17
0
def transformLineInMap(line_matrix, x, y, widht, height, imageList):
    if (is_empty(line_matrix)):
        return empty
    if first(line_matrix) == config.Config.MAP_NUMBMATRIX_GRASS:
        return cons(
            (0, rectangle.Rectangle((x, y), widht, height, imageList[0])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))
    elif first(line_matrix) == config.Config.MAP_NUMBMATRIX_PATH:
        return cons(
            (1, rectangle.Rectangle((x, y), widht, height, imageList[1])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))

    elif first(line_matrix) == config.Config.MAP_NUMBMATRIX_SPAWN:
        return cons(
            (2, rectangle.Rectangle((x, y), widht, height, imageList[2])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))

    elif first(line_matrix) == config.Config.MAP_NUMBMATRIX_DESPAWN:
        return cons(
            (3, rectangle.Rectangle((x, y), widht, height, imageList[3])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))

    elif first(line_matrix) == config.Config.MAP_NUMBMATRIX_CENTRALPATH:
        return cons(
            (4, rectangle.Rectangle((x, y), widht, height, imageList[4])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))

    elif first(line_matrix) == config.Config.MAP_NUMBMATRIX_CHANGEDIRECTION:
        return cons(
            (5, rectangle.Rectangle((x, y), widht, height, imageList[5])),
            transformLineInMap(rest(line_matrix), x + widht, y, widht, height,
                               imageList))
Beispiel #18
0
    def __init__(self, width, height, fps):
        game_mouse.Game.__init__(self, "Shapes", width, height, fps)

        self.r = rectangle.Rectangle(200, 100, 0, 0, (255, 255, 255))
        self.r2 = rectangle.Rectangle(300, 50, 200, 300, (0, 255, 0))
        return
Beispiel #19
0
def test_rectangle_20_10():
    rect = rectangle.Rectangle(20.0, 10.0)
    rect.print()
    area = rect.area()
    perimeter = rect.perimeter()
    assert 200.0 == area and 60.0 == perimeter
Beispiel #20
0
def test_rectangle_10_10():
    rect = rectangle.Rectangle(10.0, 10.0)
    rect.print()
    area = rect.area()
    perimeter = rect.perimeter()
    assert 100.0 == area and 40.0 == perimeter
Beispiel #21
0
 def setUp(self):
     self.RectangleA = rectangle.Rectangle(-1, -1, 1, 1)
     self.RectangleB = rectangle.Rectangle(0, 0, 2, 2)
Beispiel #22
0
def main():

    # Initialize window object and set size
    window = pyglet.window.Window()
    window.set_size(576, 432)

    # Images
    background = pyglet.resource.image('magic8_blank.jpg')
    ask_img = pyglet.resource.image('ask.png')
    clear_img = pyglet.resource.image('clear.png')
    quit_img = pyglet.resource.image('quit.png')

    # Button rectangles
    ask = rectangle.Rectangle(20, 30, 100, 30)
    clear = rectangle.Rectangle(140, 30, 100, 30)
    quit = rectangle.Rectangle(260, 30, 100, 30)

    # Replies
    replies = [
        'Definitely!', 'Possibly.', 'It\'s in the stars.', 'Nope.', 'Sorry.',
        'No way.', 'No.', 'Yes', 'Try again.', 'Not this time.'
        'Hmmm.', 'Of course.', 'Ha. ..Ha. Ha.', 'Oh yeah. Big time.',
        'Can\'t say', 'Totally!', 'Yep.', 'Naturally, yes.', 'Ohh yeah.'
    ]

    # 8 Ball Result
    answer = pyglet.text.Label('',
                               font_name="Arial",
                               font_size=36,
                               x=window.width // 2,
                               y=window.height // 2,
                               anchor_x='center',
                               anchor_y='center')

    # Drawing event handler
    @window.event
    def on_draw():
        window.clear()
        background.blit(0, 0)
        ask_img.blit(ask.x, ask.y)
        clear_img.blit(clear.x, clear.y)
        quit_img.blit(quit.x, quit.y)
        answer.draw()

    # Button Press event handler
    @window.event
    def on_mouse_press(x, y, button, modifiers):
        within_ask = ask.in_rect(x, y)
        within_clear = clear.in_rect(x, y)
        within_quit = quit.in_rect(x, y)

        if within_ask:
            answer.text = replies[random.randrange(len(replies))]
        if within_clear:
            answer.text = ''
        if within_quit:
            pyglet.app.exit()

    # Displays all events to console - find event names/parameters - debugging
    # window.push_handlers(pyglet.window.event.WindowEventLogger())

    pyglet.app.run()
Beispiel #23
0
class World:
    def __init__(self, position, width, height, layout_file=None):
        self.position = position
        self.width = self.safe_assign("Width", width, int, WORLD_DEFAULT_WIDTH)
        self.height = self.safe_assign("Height", height, int,
                                       WORLD_DEFAULT_HEIGHT)
        self.cell_width = TILE_WIDTH
        self.cell_height = TILE_HEIGHT
        self.occupied_locations = []
        self.layout = []
        self.tile_types = []
        self.waypoints = []
        self.start_cell = None
        if layout_file is not None:
            self.load_from_file(layout_file)
        self.start = self.get_cell_top_left(
            self.loc_to_cell(self.start_cell[0], self.start_cell[1]))
        self.order_waypoints()

    def get_position(self):
        return self.position

    def get_dims(self):
        return (self.width, self.height)

    def get_width(self):
        return self.width

    def get_height(self):
        return self.height

    # attempts to assign a variable called var_name (for debugging)
    # to a value of value but assigns it to value: default
    # if the original type cannot be casted into desired_type
    def safe_assign(self, var_name, value, desired_type, default):
        if type(desired_type) != type(type(int)):
            print "Desired_type was not a valid type"
            print "Defaulting to type(str)"
            desired_type = str
        if type(value) != desired_type:
            print str(var_name) + " expected to be " + str(desired_type)
            print "Attempting Cast..."
            try:
                value = desired_type(value)
            except:
                print "Unable to convert ", type(
                    value), " to type " + str(desired_type)
                print "Defaulting to", default
                value = default
            print "Type-cast completed"
        return value

    # attempts to open the world file and store the information
    # does nothing if the file was invalid in any way
    def load_from_file(self, layout_file):
        # locate the file
        if not os.path.exists(layout_file):
            print "Error loading world file " + layout_file + ": File was not found."
            print "File will not be loaded"
            return

        # open and read the file
        f = open(layout_file, 'rb')
        fin = [line.strip() for line in f.readlines()]
        f.close()

        # skip past the non-world data
        fin = fin[4:]  # skips money, lives, and towers
        skip = int(fin[0])
        fin = fin[skip + 1:]

        # grab the dimensions of the world and the starting
        # tile of the path
        data = fin[0].split()
        dim = [0, 0]
        try:
            dim[0] = int(data[0])
            dim[1] = int(data[1])
            if len(data) != 4:
                raise Exception("Invalid layout description\n" + str(dim))
            self.start_cell = (int(data[2]), int(data[3]))

            # verify dimensions
            layout = []
            fin = fin[1:]
            for line in fin:
                if len(line) != dim[0]:
                    raise Exception("Invalid/Mismatched width\n" + str(line))
                else:
                    layout.append(line)
            if len(layout) != dim[1]:
                l = ""
                for i in layout:
                    l += i + '\n'
                l = l.strip()
                raise Exception("Invalid/Mismatched height\n" + l)
        except Exception, e:
            print "Error loading world file " + layout_file + ": Invalid formatting"
            print e
            return False

        # fills remaining tiles to fill world size
        row_size = self.width / self.cell_width
        col_size = self.height / self.cell_height
        filled_rows = int(dim[0])
        filled_cols = int(dim[1])
        empty_rows = row_size - filled_rows
        empty_cols = col_size - filled_cols
        for i in range(len(layout)):
            fill = empty_rows * str(GRASS)
            layout[i] = layout[i] + fill
        for i in range(empty_cols):
            fill = row_size * str(GRASS)
            layout.append(fill)

        # records each tile and its type
        self.layout = []
        waypoints = []
        for j in range(len(layout)):
            r_row = []
            t_row = []
            t_locations = []
            for i in range(len(layout[j])):
                tile = layout[j][i]
                if tile == str(GRASS):
                    img = GRASS_IMG
                elif tile == str(ROCK):
                    img = ROCK_IMG
                else:
                    img = PATH_IMG
                    if tile == str(WAYPOINT):
                        waypoints.append((i, j))
                x = self.position[0] + (i) * self.cell_width
                y = self.position[1] + (j) * self.cell_height
                t_row.append(int(tile))

                # tower location default to 0
                t_locations.append(0)

                r_row.append(
                    rectangle.Rectangle(KIND_TILE, (x, y), self.cell_width,
                                        self.cell_height, img))
            self.layout.append(r_row)
            self.tile_types.append(t_row)
            self.occupied_locations.append(t_locations)
        for point in waypoints:
            self.waypoints.append(
                self.get_cell_top_left(self.loc_to_cell(point[0], point[1])))
        return True
def main():
    """This is the main function of the demo"""

    clock = pygame.time.Clock()

    # list of all nodes
    nodes: typing.List[rt.Rectangle] = []

    # variables used in handling drag event
    mouse_x = 0
    mouse_y = 0
    _node: rt.Rectangle = None
    horizontal_aligned_node: rt.AlignPoint = None
    vertical_aligned_node: rt.AlignPoint = None

    # Create a triangle
    nodes.append(rt.Rectangle(200, 100, 60, 40))
    nodes.append(rt.Rectangle(300, 400, 80, 40))
    nodes.append(rt.Rectangle(170, 300, 80, 80))
    nodes.append(rt.Rectangle(600, 200, 100, 100))

    # Initial the Rectangle
    rt.Rectangle.screen = screen
    rt.Rectangle.nodes = nodes

    is_draging = False
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == K_ESCAPE:
                    running = False

            elif event.type == pygame.MOUSEBUTTONDOWN:
                position = (click_x, click_y) = event.pos

                # Check if a node is clicked
                for node in nodes:
                    if node.collidepoint(position):
                        is_draging = True
                        mouse_x = click_x
                        mouse_y = click_y
                        _node = node
                        break

            elif event.type == pygame.MOUSEBUTTONUP:
                is_draging = False
                _node = None
                horizontal_aligned_node = None
                vertical_aligned_node = None

            elif event.type == pygame.MOUSEMOTION:
                if is_draging:
                    (click_x, click_y) = event.pos
                    horizontal_aligned_node = \
                        _node.move_horiontally(click_x - mouse_x)
                    vertical_aligned_node = \
                        _node.move_vertically(click_y - mouse_y)

                    mouse_x = click_x
                    mouse_y = click_y

            # if the user click the window close button.
            elif event.type == pygame.QUIT:
                running = False

        # Refresh screen with white color
        screen.fill((255, 255, 255))

        # Draw all rectangles
        for node in nodes:
            node.draw()

        # If two nodes are aligned, hightlight them and draw the line
        if _node is not None:
            # Horizontal direction
            if horizontal_aligned_node is not None:
                pygame.draw.rect(screen, HIGHTLIGHT_COLOR, _node)
                if horizontal_aligned_node.node != "window":
                    pygame.draw.rect(screen, HIGHTLIGHT_COLOR,
                                     horizontal_aligned_node.node)
                    draw_line(horizontal_aligned_node, _node)
                else:
                    draw_line(horizontal_aligned_node, None)
            # Vertical direction
            if vertical_aligned_node is not None:
                pygame.draw.rect(screen, HIGHTLIGHT_COLOR, _node)
                if vertical_aligned_node.node != "window":
                    pygame.draw.rect(screen, HIGHTLIGHT_COLOR,
                                     vertical_aligned_node.node)
                    draw_line(vertical_aligned_node, _node, 'vertical')
                else:
                    draw_line(vertical_aligned_node, None, 'vertical')

        # Update the screen
        pygame.display.flip()

        # - constant game speed / FPS
        clock.tick(FPS)
Beispiel #25
0
 def setUp(self):
     self.square = rectangle.Rectangle(Fraction(1, 1))
Beispiel #26
0
    def start(self):
        self.group = pygame.sprite.LayeredDirty()
        self.game_group = pygame.sprite.LayeredDirty()
        self.ui_group = pygame.sprite.LayeredDirty()
        
        self.time = 0

        galaxy = self.game.run_info.get_current_level_galaxy()
        self.galaxy = galaxy
        alien_code = galaxy['alien']
        alien_obj = alien.ALIENS[alien_code]
        self.nametext = typewriter.Typewriter(alien_obj.title, "huge", V2(50, 31) + self.game.game_offset, multiline_width=500, center=False, time_offset = -1)
        self.group.add(self.nametext)
        self.group.add(typewriter.Typewriter("ALIEN FORCES", "big", V2(50, 15) + self.game.game_offset, PICO_LIGHTGRAY, multiline_width=300, center=False))
        self.loading_text = Text("Loading...", "small", V2(game.RES[0] - 70, 326) + self.game.game_offset, center=False)
        self.loading_text.offset = (0.5, 0)
        self.group.add(self.loading_text)

        self.portrait = SimpleSprite(V2(50, 65) + self.game.game_offset, "assets/%sgraphic.png" % alien_code)
        pygame.draw.rect(self.portrait.image, PICO_BLACK, (0,0,self.portrait.width, self.portrait.height), 1)
        self.group.add(self.portrait)
        self.portrait.pos = (0,-1000)
        #self.portrait.visible = False

        self.tips = []
        self.quote = None

        difficulty_width = 150
        difficulty_pos = V2(game.RES[0] / 2 - difficulty_width / 2, 175) + self.game.game_offset

        if galaxy['difficulty'] > 1:
            difficulty_pos = V2(game.RES[0] * 0.3 - difficulty_width / 2, 215) + self.game.game_offset       

        labels = ['Mining Rate', 'Attack Power', 'Tech Level']
        images = ['econ', 'attack', 'tech']
        elements = []
        for i in range(3):
            pos = difficulty_pos + V2(0, i * 20)
            t = Text(labels[i], "small", pos + V2(60, 0), PICO_ORANGE)
            t.offset = (1,0)
            self.group.add(t)
            t.visible = False
            elements.append(t)
            maxelem = 5
            if i == 2: maxelem = 3
            for z in range(maxelem):
                f = FrameSprite(pos + V2(70 + z * 14, -3), "assets/enemystrength-%s.png" % images[i], 11)
                if z >= DIFFICULTY_VALUES[galaxy['difficulty']][i]:
                    f.frame = 1
                else:
                    f.frame = 0
                self.group.add(f)
                f.visible = False
                elements.append(f)

        self.tips.append(elements)

        if galaxy['difficulty'] > 1:
            tw = 150
            if galaxy['difficulty'] < 3: i = 0
            elif galaxy['difficulty'] < 6: i = 1
            else: i = 2
            tip = alien_obj.tips[i]
            x = game.RES[0] * 0.7
            img = pygame.image.load(resource_path(tip[0]))
            s = SimpleSprite(V2(x, 165) + self.game.game_offset, img)
            s.offset = (0.5, 0)
            self.group.add(s)
            t = Text(tip[1], "small", V2(x - tw / 2, 240) + self.game.game_offset, multiline_width=tw, center=False)
            self.group.add(t)
            s.visible = False
            t.visible = False
            r = rectangle.Rectangle(V2(x - tw / 2, 169) + self.game.game_offset, (19, 11), PICO_YELLOW)
            t2 = Text("TIP", "small", V2(x - tw / 2 + 2, 171) + self.game.game_offset, PICO_BLACK)
            r.visible = False
            t2.visible = False
            self.group.add(r)
            self.group.add(t2)
            self.tips.append((r, t2))
            self.tips.append((s, t))
        else:
            self.quote = Text(alien_obj.get_quote(), "pixolde", V2(game.RES[0] / 2, 270) + self.game.game_offset, PICO_YELLOW, multiline_width=400)
            self.quote.offset = (0.5, 0)
            self.group.add(self.quote)
            self.quote.visible = False


        if galaxy['mods']:
            self.group.add(SimpleSprite(V2(61, 322) + self.game.game_offset, "assets/exclamation.png"))
            self.group.add(Text("DANGER", "small", V2(79, 320) + self.game.game_offset, PICO_YELLOW, multiline_width=400, center=False))
            self.group.add(Text(MOD_STRINGS[galaxy['mods'][0]], "small", V2(79, 330) + self.game.game_offset, PICO_WHITE, multiline_width=400, center=False))
            self.warnings = self.group.sprites()[-3:]
            for warning in self.warnings:
                warning.visible = False

        self.sm = Machine(UIEnabledState(self))
        self.game.load_in_thread(self.load_level, self.on_loaded_level)
Beispiel #27
0
import rectangle

r = rectangle.Rectangle(
    0,
    0,
    3,
    3,
)
Beispiel #28
0
 def test_eq_rectangle(self):
     self.assertTrue(self.RectangleA == rectangle.Rectangle(-1, -1, 1, 1))
     self.assertTrue(self.RectangleB == rectangle.Rectangle(0, 0, 2, 2))
    def range_skyline_computation(self):
        """
        The backbone of the algorithm implementation
        """
        # Import the root's keys into the main heap
        for key in self.rtree.root.entries:
            cur_rect = rect.Rectangle(self.qs, self.qe)
            heapq.heappush(self.main, [
                self.priority_main(key, self.mindist_point(cur_rect)),
                id(key), key, cur_rect
            ])

        # Check maximum heap size
        if len(self.main) > self.maximum_main_size:
            self.maximum_main_size = len(self.main)

        # Iterate through secondary heap
        sec_heap_empty = False
        while not sec_heap_empty:
            # Iterate through main heap
            while len(self.main) != 0:
                # Remove top entry
                e, qe = list(heapq.heappop(self.main))[2:]
                # Logfile
                self.logfile.write_log_file(
                    "e:",
                    str(e.rect.min_x) + "," + str(e.rect.min_y) + " - " +
                    str(e.rect.max_x) + "," + str(e.rect.max_y))
                self.logfile.write_log_file("Qe:", str(qe))
                # Find non dominated rectangle area by RSS points
                qee = self.iterate_rss(self.get_point_closest_to_qs(e), qe)
                if qee != None:

                    # Different mindist points
                    if not self.same_mindist(qe, qee):
                        self.logfile.write_log_file("Qee: ", str(qee))
                        self.logfile.write_log_file("Diff starts:",
                                                    "qees != qes")
                        # Insert into secondary heap
                        if e.is_leaf:
                            # Data Point
                            heapq.heappush(self.secondary, [
                                self.priority_secondary(
                                    self.mindist_point(qee)),
                                id(e), e, qee
                            ])
                        else:
                            # MBR
                            #heapq.heappush(self.secondary, [self.priority_secondary(self.mindist_point(qee)), id(e), e, qe])
                            for ee in e.child.entries:
                                heapq.heappush(self.secondary, [
                                    self.priority_secondary(
                                        self.mindist_point(qee)),
                                    id(ee), ee, qe
                                ])
                        # Check maximum heap size
                        if len(self.secondary) > self.maximum_secondary_size:
                            self.maximum_secondary_size = len(self.secondary)

                    # Same mindist points
                    else:
                        # Logfile
                        self.logfile.write_log_file("Qee:", str(qee))
                        self.logfile.write_log_file("Same starts",
                                                    "qees == qes")
                        # MBR
                        if not e.is_leaf:
                            # Logfile
                            self.logfile.write_log_file("e", "is an MBR")
                            qee = qe
                            # Iterate throuhg the child nodes of e
                            for ee in e.child.entries:

                                qeee = self.iterate_rss(
                                    self.get_point_closest_to_qs(ee), qee)

                                if qeee != None:

                                    # Different mindist points
                                    if not self.same_mindist(qee, qeee):
                                        if ee.is_leaf:
                                            # Data Point
                                            heapq.heappush(
                                                self.secondary, [
                                                    self.priority_secondary(
                                                        self.mindist_point(
                                                            qeee)),
                                                    id(ee), ee, qeee
                                                ])
                                        else:
                                            # MBR
                                            for eee in ee.child.entries:
                                                heapq.heappush(
                                                    self.secondary, [
                                                        self.
                                                        priority_secondary(
                                                            self.mindist_point(
                                                                qeee)),
                                                        id(eee), eee, qee
                                                    ])

                                    # Same mindist points
                                    else:
                                        if ee.is_leaf:
                                            # Data Point
                                            heapq.heappush(
                                                self.main, [
                                                    self.priority_main(
                                                        ee,
                                                        self.mindist_point(
                                                            qeee)),
                                                    id(ee), ee, qeee
                                                ])
                                        else:
                                            # MBR
                                            for eee in ee.child.entries:
                                                heapq.heappush(
                                                    self.main, [
                                                        self.priority_main(
                                                            ee,
                                                            self.mindist_point(
                                                                qeee)),
                                                        id(eee), eee, qee
                                                    ])

                                    # Check maximum heap size
                                    if len(self.main) > self.maximum_main_size:
                                        self.maximum_main_size = len(self.main)
                                    if len(self.secondary
                                           ) > self.maximum_secondary_size:
                                        self.maximum_secondary_size = len(
                                            self.secondary)

                        # Data Point
                        else:
                            # Logfile
                            self.logfile.write_log_file(
                                "e", "is a LEAF - Data Point")
                            # Update the RSS entries' rectangle area
                            self.update_RSS_items(self.get_minDim(e), qee)
                            # Insert e into the RSS
                            self.RSS.append([self.get_minDim(e), qee])
                            # Clean entries with None as rectangle area
                            self.RSS = self.clean_RSS(self.RSS)
                            # Logfile
                            self.logfile.write_log_file("RSS", str(self.RSS))

            if len(self.secondary) > 0:
                self.push_to_main()
            else:
                sec_heap_empty = True
Beispiel #30
0
 def test_ne_rectangle(self):
     self.assertTrue(self.RectangleA != rectangle.Rectangle(-2, -2, 2, 2))