class MathPower(MultiItem): """Container for inline maths""" def __init__(self): MultiItem.__init__(self) self.style = 'math-var', 1 def resizePDF(self, pdf, x = 0, y = 0): if len(self.items) < 2 or not self.items[0] or not self.items[1]: raise Exception('MathPower must have two items.') self.rect = Rect(x,y,x,y) dx = pdf.get_string_width(' ') * self.style[1] base = self.items[0] if hasattr(base,'style'): setFontPDF(pdf, base.style, self.styles) base.resizePDF(pdf,x,y) index = self.items[1] index.scaleFont(0.8) if hasattr(index,'style'): setFontPDF(pdf, index.style, self.styles) index.resizePDF(pdf, base.rect.x1() + dx, y - base.rect.height() * 0.4) self.rect.unite(base.rect) self.rect.unite(index.rect) self.refit()
class InlineMathBlock(MultiItem): """Container for inline maths""" def __init__(self, *items): MultiItem.__init__(self) self.style = ('math-var',1) for item in items: self.appendItem(item) def resizePDF(self, pdf, x = 0, y = 0): self.rect = Rect(x,y,x,y) dx = pdf.get_string_width(' ') dx *= self.style[1] rectList = [] width = 0.0 style = '' for item in self.items: if item: if hasattr(item,'style') and item.style != style: setFontPDF(pdf, item.style, self.styles) item.resizePDF(pdf,x,y) rectList.append(item.rect) width += item.rect.width() + dx rect.alignLeft(rectList, x, x+width, dx) for r in rectList: self.rect.unite(r) self.refit()
def __init__(self, x, y, w, h, objects = [], creatures = [], start = False): self.inner_rect = Rect.from_dimensions(x + WALL_WIDTH, y + int(WALL_WIDTH * 1.25), w + WALL_WIDTH, h + int(WALL_WIDTH * 1.5)) self.outer_rect = Rect.from_dimensions(x, y, 2 * WALL_WIDTH + w, 2 * WALL_WIDTH + h)
def dredgeRiverSingle(nature,direction,CX,CY): rivert=[] # This is the start coordinate of the river, perpendicular to the # axis of the river. N/S rivers choose positions on the E/W axis, # and vice-versa axis_size = CX if direction else CY line_pos=random.randint(0, axis_size) #river width, no more than half the map river_size=min(random.randint(3,120), axis_size//2) for i in range(0,axis_size): if direction: element=Rect(Point(i,line_pos),Point(i,line_pos+river_size)) else: element=Rect(Point(line_pos,i),Point(line_pos+river_size,i)) element.set_name('RIVER') rivert.append(element) prev=0; for f in rivert: prev=prev+random.randint(-1,1) f.move(direction+2,prev) # in rect, 1=up, 2=right nature.extend(rivert)
def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.moving = False self.teleport = False self.to_x = self.x self.to_y = self.y if ( random.random() < 0.1): self.value = 4 else: self.value = 2 self.color = COLORS[self.value] self.child = None self.font_size = math.floor(72/96 * (self.width / len(str(self.value)) *.95)) self.rect = Rect(self.x, self.y, self.width, self.height) self.label = pyglet.text.Label(str(self.value), font_name='Calibri', font_size=self.font_size, color=(0,0,0,255), x=self.x + self.width // 2, y=self.y + self.height // 2, anchor_x='center', anchor_y='center') print(self.label.width)
def fill(self, color=(0, 0, 0), rect=None): """ Fill surface with color. """ try: g2d = self._g2d surface_graphics = True except AttributeError: g2d = self.createGraphics() surface_graphics = False color = Color(color) #0.23 g2d.setColor(color) if not rect: rect = Rect(0, 0, self.width, self.height) x, y, w, h = rect.x, rect.y, rect.width, rect.height else: try: x, y, w, h = rect.x, rect.y, rect.width, rect.height except AttributeError: rect = Rect(rect[0], rect[1], rect[2], rect[3]) x, y, w, h = rect.x, rect.y, rect.width, rect.height g2d.fillRect(x, y, w, h) if not surface_graphics: g2d.dispose() return rect
def circle(self, surface, color, position, radius, width=0): """ Draw circular shape, and returns bounding Rect. Argument include surface to draw, color, position and radius. Optional width argument of outline, which defaults to 0 for filled shape. """ surface.beginPath() surface.arc(position[0], position[1], radius, 0, 2 * pi, False) if width: surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() else: if hasattr(color, 'a'): surface.setFillStyle(color) else: surface.setFillStyle(Color(color)) surface.fill() if surface._display: return surface._display._surface_rect.clip( Rect(position[0] - radius, position[1] - radius, 2 * radius, 2 * radius)) else: return surface.get_rect().clip( Rect(position[0] - radius, position[1] - radius, 2 * radius, 2 * radius))
def __init__(self, game, zone): self.game = game self.zone = zone self.screen = self.game.screen self.battles = [x for x in game.battles if x.zone == self.zone] self.targets = [x for x in game.targets if x.zone == self.zone] self.terrain = [x for x in game.terrain if x.zone == self.zone] # Determine the size required for the map surface map_size_rect = Rect() for ter in self.terrain: map_size_rect.union(ter.rect) self.map_surface = pygame.Surface(map_size_rect.size) # Draw all static terrain and targets to the map surface for ter in self.terrain: if ter.static: self.map_surface.fill((255, 0, 0), ter) ter.draw(self.map_surface) for tar in self.targets: if tar.static: tar.draw(self.map_surface)
def update(self): last = Rect(*(self.pos + self.size)) dx = 0 if keys.get(Keyboard.keycodes['left']): dx -= 2 * params.scale if keys.get(Keyboard.keycodes['right']): dx += 2 * params.scale if keys.get(Keyboard.keycodes['spacebar']) and self.resting: self.dy = 9 * params.scale self.resting = False self.dy = max(-8 * params.scale, self.dy - .5 * params.scale) self.x += dx self.y += self.dy new = Rect(*(self.pos + self.size)) for cell in self.map.layers['objects'].collide(new, 'blocker'): blocker = cell['blocker'] if 'l' in blocker and last.right <= cell.left and new.right > cell.left: new.right = cell.left if 'r' in blocker and last.left >= cell.right and new.left < cell.right: new.left = cell.right if 't' in blocker and last.bottom >= cell.top and new.bottom < cell.top: self.resting = True new.bottom = cell.top self.dy = 0 if 'b' in blocker and last.top <= cell.bottom and new.top > cell.bottom: new.top = cell.bottom self.dy = 0 self.pos = new.bottomleft
def lines(self, surface, color, closed, pointlist, width=1): """ Draw interconnected lines, and returns Rect bound. Argument include surface to draw, color, closed, and pointlist. Optional width argument of line. """ surface.beginPath() surface.moveTo(*pointlist[0]) for point in pointlist[1:]: surface.lineTo(*point) if closed: surface.closePath() surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() xpts = [pt[0] for pt in pointlist] ypts = [pt[1] for pt in pointlist] xmin, xmax = min(xpts), max(xpts) ymin, ymax = min(ypts), max(ypts) if surface._display: return surface._display._surface_rect.clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)) else: return surface.get_rect().clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
def test_center(): r = Rect(0, 0, 2, 2) Hb = Hitbox(r) t = CollideTransformable() t.set_hit_box(Hb) assert t.get_hit_box().get_world_rect() == Rect(0, 0, 2, 2) assert t.get_position() == Vector(1, 1)
def subarea(self, *rect): """ Return Surface and Rect that represents a subsurface that shares data with this surface. The rect argument is the area of the subsurface. """ try: x, y, w, h = rect[0].x, rect[0].y, rect[0].width, rect[0].height except AttributeError: try: x, y, w, h = rect[0] except ValueError: x, y = rect[0] w, h = rect[1] rect = Rect(x, y, w, h) try: subsurf = self.getSubimage(rect.x, rect.y, rect.width, rect.height) except RasterFormatException: try: clip = self.get_rect().createIntersection(rect) rect = Rect(clip.x, clip.y, clip.width, clip.height) subsurf = self.getSubimage(rect.x, rect.y, rect.width, rect.height) except: #rect outside surface subsurf = None return subsurf, rect
class MathSubSuperscript(MultiItem): """An item with a subscript""" def __init__(self, base, subscript = None, superscript = None): MultiItem.__init__(self) self.appendItem(base) self.base = base self.subscript = subscript self.superscript = superscript if subscript: subscript.scaleFont(0.8) self.appendItem(subscript) if superscript: superscript.scaleFont(0.8) self.appendItem(superscript) def resizePDF(self, pdf, x = 0, y = 0): self.resizeItemsPDF(pdf, x, y) dx = pdf.get_string_width(' ') * self.style[1] self.rect = Rect(x,y,x,y) h = self.base.rect.height() w = self.base.rect.width() + dx if self.subscript: self.subscript.rect.translate(w, h*0.5) self.rect.unite(self.subscript.rect) if self.superscript: self.superscript.rect.translate(w, - h*0.5) self.rect.unite(self.superscript.rect) self.refit()
def test_class_rect(): r1 = Rect(10, 10, 50, 50) r2 = eval(repr(r1)) print(r1, str(r1.area()), sep=':') print(r2, str(r2.area()), sep=':') r1.draw() r2.draw()
def __init__(self, matrix, fertile_symbol): self.matrix = matrix self.active_rects = [] self.largest_rect = Rect(1, 0) self.active_row = 0 self.fertile_symbol = fertile_symbol self.all_rects = [self.largest_rect]
def fill(self, color=None, rect=None): """ Fill surface with color. """ if color is None: HTML5Canvas.fill(self) return self.beginPath() if color: if hasattr(color, 'a'): self.setFillStyle(color) else: self.setFillStyle(Color(color)) if not rect: _rect = Rect(0, 0, self.width, self.height) else: if self._display: surface_rect = self._display._surface_rect else: surface_rect = self.get_rect() if hasattr(rect, 'width'): _rect = surface_rect.clip(rect) else: _rect = surface_rect.clip(Rect(rect)) if not _rect.width or not _rect.height: return _rect self.fillRect(_rect.x, _rect.y, _rect.width, _rect.height) else: _rect = Rect(0, 0, self.width, self.height) self.clear() return _rect
def resizePDF(self, pdf, x = 0, y = 0): if len(self.items) == 0: raise Exception('MathAboveAndBelow must have at least one item.') self.rect = Rect(x,y,x,y) base = self.items[0] self.setFontPDF(pdf, base) base.resizePDF(pdf,x,y) self.rect.unite(base.rect) if len(self.items) > 1 and self.items[1]: below = self.items[1] self.setFontPDF(pdf, below) below.resizePDF(pdf,x,y) below.rect.translate(0, base.rect.height()) below.rect.alignXCenter( base.rect ) self.rect.unite(below.rect) if len(self.items) > 2 and self.items[2]: above = self.items[2] self.setFontPDF(pdf, above) above.resizePDF(pdf,x,y) above.rect.translate(0, - above.rect.height()) above.rect.alignXCenter( base.rect ) self.rect.unite(above.rect) self.refit()
def resizePDF(self, pdf, x = 0, y = 0): if len(self.items) < 2 or not self.items[0] or not self.items[1]: raise Exception('MathFrac must have two items.') self.rect = Rect(x,y,x,y) dx = pdf.get_string_width(' ') * self.style[1] self.margins.set(dx, 0.0) setFontPDF(pdf, self.style, self.styles) lineHeight = pdf.font_size_pt / pdf.k numerator = self.items[0] if hasattr(numerator,'style'): setFontPDF(pdf, numerator.style, self.styles) numerator.resizePDF(pdf,x + dx, y - lineHeight * 0.5) denominator = self.items[1] if hasattr(denominator,'style'): setFontPDF(pdf, denominator.style, self.styles) denominator.resizePDF(pdf, x + dx, numerator.rect.y1()) if numerator.rect.width() > denominator.rect.width(): denominator.rect.alignXCenter(numerator.rect) else: numerator.rect.alignXCenter(denominator.rect) self.rect.unite(numerator.rect) self.rect.unite(denominator.rect) self.rect.adjust(rect.Point(0,0),rect.Point(dx,0))
def polygon(self, surface, color, pointlist, width=0): """ Draw polygon shape, and returns bounding Rect. Argument include surface to draw, color, and pointlist. Optional width argument of outline, which defaults to 0 for filled shape. """ surface.beginPath() surface.moveTo(*pointlist[0]) for point in pointlist[1:]: surface.lineTo(*point) surface.closePath() if width: surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() else: if hasattr(color, 'a'): surface.setFillStyle(color) else: surface.setFillStyle(Color(color)) surface.fill() xpts = [pt[0] for pt in pointlist] ypts = [pt[1] for pt in pointlist] xmin, xmax = min(xpts), max(xpts) ymin, ymax = min(ypts), max(ypts) if surface._display: return surface._display._surface_rect.clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)) else: return surface.get_rect().clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
def run(self, iterations=1): self.done = False for _ in range(iterations): if self.done: break self.handle_events() if self.draw: self.screen.fill(pygame.Color('white')) self.table.draw(self.screen) self.puck.vel = self.camera.puck['pos'] - self.puck.pos self.puck.pos = self.camera.puck['pos'] print(self.puck.vel) self.striker.pos = self.camera.striker['pos'] self.table = Rect(self.camera.table['min_x'], self.camera.table['min_y'], self.camera.table['max_x'], self.camera.table['max_y']) self.puck.update(self) #self.striker.update(self) if self.draw: pygame.display.flip() return self.striker.vel
def line(self, surface, color, point1, point2, width=1): """ Draw line, and returns bounding Rect. Argument include surface to draw, color, point1, point2. Optional width argument of line. """ surface.beginPath() surface.moveTo(*point1) surface.lineTo(*point2) surface.setLineWidth(width) if hasattr(color, 'a'): surface.setStrokeStyle(color) else: surface.setStrokeStyle(Color(color)) surface.stroke() xpts = [pt[0] for pt in (point1, point2)] ypts = [pt[1] for pt in (point1, point2)] xmin, xmax = min(xpts), max(xpts) ymin, ymax = min(ypts), max(ypts) if surface._display: return surface._display._surface_rect.clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1)) else: return surface.get_rect().clip( Rect(xmin, ymin, xmax - xmin + 1, ymax - ymin + 1))
def test_collision_box(): for a, b, c in intersection_pairs: assert a.collision_box(b) == c, f'{a}.collision_box({b} != {c}' assert b.collision_box(a) == c, f'{a}.collision_box({b} != {c}' r = Rect(0, 0, 2, 2) assert r.collision_box(r) == r
def set_crop_area(self): r = Rect(self.croprect_start, self.croprect_end) # adjust dimensions r.clip_to(self.image_thumb_rect) # ignore rects smaller than this size if min(r.h, r.w) < 10: return ra = r ra = ra.scale_rect(self.scale) ra = ra.move_rect(self.x0, self.y0) ra = ra.valid_rect(self.w, self.h) if self.zoommode: self.canvas.delete(tk.ALL) self.x0 = ra.left self.y0 = ra.top self.region_rect = ra self.displayimage() self.zoommode = False self.zoomButton.deselect() self.zooming = True else: self.drawrect(r) self.crop_rects.append(ra) self.n = self.n + 1 self.set_button_state()
def getOuterRect(self): r = Rect() r.size = ( self.marginLeft + self.image.size[0] + self.marginRight, self.marginTop + self.image.size[1] + self.marginBottom, ) return r
def blit(self, surface, position, area=None): """ Draw given surface on this surface at position. Optional area delimitates the region of given surface to draw. """ try: x, y = position.x, position.y except AttributeError: x, y = position[0], position[1] try: if not area: rect = self.get_rect().createIntersection( Rect(x, y, surface.width, surface.height)) surface_rect = Rect(rect.x, rect.y, rect.width, rect.height) else: surface, surface_rect = surface.subarea(area) except AttributeError: return Rect(0, 0, 0, 0) try: g2d = self._g2d surface_graphics = True except AttributeError: g2d = self.createGraphics() surface_graphics = False try: g2d.drawImage(surface, x, y, None) except TypeError: g2d.drawImage(surface, int(x), int(y), None) if not surface_graphics: g2d.dispose() return surface_rect
def main(): # First thing is to read the source image and grayscale it pickleFile = sys.argv[1] with open(pickleFile, 'rb') as file: rawImg, scaleFactor, rangedNotes = pickle.load(file) if scaleFactor < 1.0: img = cv2.resize(rawImg, None, fx=scaleFactor, fy=scaleFactor, interpolation=cv2.INTER_CUBIC) else: img = rawImg lniName = "Labeled notes" noteImg = img.copy() drawParams = DrawParams() for note in rangedNotes: rect = Rect(note.rect.x, note.rect.y, note.rect.w, note.rect.h, str(note.noteLine) + " " + str(note.duration)) rect.draw(noteImg, drawParams, lniName, allInfo=False) cv2.namedWindow(lniName) cv2.setMouseCallback(lniName, Rect.onClick, lniName) cv2.imshow(lniName, noteImg) print("\t\tPress space to continue...") while True: if cv2.waitKey(30) == 32: break cv2.destroyAllWindows()
def __init__(self, screen, rows=0, columns=0): super().__init__() self.cards = [] self.screen = screen self.cards_offset = 10 self.card_size = vector2(70, 100) self.selected_cards = [] self.on_exit = None self.score = 0 self.wrong_attempts = 0 # SCORE TEXT self.score_text = Text(Rect(vector2(20, 20), vector2(150, 50)), Game.defaultScoreText + str(self.score)) self.score_text.justify = Text.justify_up self.score_text.align = Text.align_left self.childs.append(self.score_text) # EXIT BUTTON x, y = screen.get_size() exit_button = TextButton(vector2(20, y - 70), vector2(150, 50), "Exit") exit_button.on_click = lambda game=self: game.on_exit_game() self.childs.append(exit_button) # WIN TEXT self.win_text = Text(Rect(vector2(0, 0), vector2(x, y)), "Congratulations!") self.childs.append(self.win_text) if rows != 0 and columns != 0: self.new_game(rows, columns) else: self.is_visible = False
class TextItem(DocItem): """Prints some form of text""" def __init__(self, text = '', style = 'body'): DocItem.__init__(self) self.text = text self.style = style def writePDF(self, pdf = None): """Write itself to a FPDF object. Args: pdf (FPDF): the FPDF object to write to. """ return self.getText() def resizePDF(self, pdf, x = 0, y = 0): """Resize internal Rect according to current settings of pdf""" width = pdf.get_string_width( self.getText() ) height = pdf.font_size_pt / pdf.k self.rect = Rect( x, y, x + width, y + height ) def cellPDF(self, pdf, r = None): if r: x_shift = r.x0() y_shift = r.y0() else: x_shift = 0.0 y_shift = 0.0 pdf.set_y( self.rect.y0() - y_shift ) pdf.set_x( self.rect.x0() - x_shift ) pdf.cell( self.rect.width(), self.rect.height(), self.getText() ) def refit(self): """Doesn't need to do anything as cellPDF uses self.rect to output the content""" pass
def test_08(): # Problem: get_rect gibt immer 0, 0 t1 = TextBox("0123456789") t2 = TextBox("0123456789") p1 = Paragraph([Row([t1, t2, NewlineBox(defaultstyle)])]) assert p1.get_rect(0, 0, 0) == Rect(0, 0.0, 1, 1.0) assert p1.get_rect(10, 0, 0) == Rect(10, 0.0, 11, 1.0)
def aggro_check(self, size): aggro_range = self.map.tile_width * size offset = (self.map.tile_width * (size / 2)) collided = [] for player in self.player_characters: rect = Rect(player.x - offset, player.y - offset, aggro_range, aggro_range) collided += [e for e in self.entities if rect.intersect(Rect(*e.pos + e.size)) and e.data.type == 'enemy'] return collided
def generate_map(self, height, width): """Initialize the map""" self.height = height self.width = width #Set map to all empty tiles self.floor = [[0 for y1 in range(height)] for x1 in range(width)] for x in range(self.width): for y in range(self.height): self.floor[x][y] = Tile.get_new_tile() # Create some rooms rooms = [] num_rooms = 0 for r in range(settings.MAX_ROOMS): # random width and height w = random.randint(settings.ROOM_MIN_SIZE, settings.ROOM_MAX_SIZE) h = random.randint(settings.ROOM_MIN_SIZE, settings.ROOM_MAX_SIZE) # random position without going out of the boundaries of the map x = random.randint(0, self.width - w - 1) y = random.randint(0, self.height - h - 1) new_room = Rect(x, y, w, h) # run through the other rooms and see if they intersect with this one failed = False for other_room in rooms: if new_room.intersect(other_room): failed = True break if not failed: # this means there are no intersections, so this room is valid # "paint" it to the map's tiles self.create_room(new_room) # center coordinates of new room, will be useful later (new_x, new_y) = new_room.center() if not num_rooms == 0: # all rooms after the first: # connect it to the previous room with a tunnel # center coordinates of previous room (prev_x, prev_y) = rooms[num_rooms - 1].center() # draw a coin (random number that is either 0 or 1) if random.randint(0, 1) == 1: # first move horizontally, then vertically self.create_h_tunnel(prev_x, new_x, prev_y) self.create_v_tunnel(prev_y, new_y, new_x) else: # first move vertically, then horizontally self.create_v_tunnel(prev_y, new_y, prev_x) self.create_h_tunnel(prev_x, new_x, new_y) # finally, append the new room to the list rooms.append(new_room) num_rooms += 1
def map_all_and_work(zone, duty): workers = [] pool = Pool() nw = Rect(Point(0, 0), Point(CITY_SIZE_X / 2, CITY_SIZE_Y / 2)) ne = Rect(Point(CITY_SIZE_X / 2, 0), Point(CITY_SIZE_X, CITY_SIZE_Y / 2)) sw = Rect(Point(0, CITY_SIZE_Y / 2), Point(CITY_SIZE_X / 2, CITY_SIZE_Y)) se = Rect(Point(CITY_SIZE_X / 2, CITY_SIZE_Y / 2), Point(CITY_SIZE_X, CITY_SIZE_Y)) workers.append( pool.apply_async(conflictSolver, [(0, 0), zone[0][0], nw, duty])) workers.append( pool.apply_async(conflictSolver, [(0, 1), zone[0][1], ne, duty])) workers.append( pool.apply_async(conflictSolver, [(1, 0), zone[1][0], sw, duty])) workers.append( pool.apply_async(conflictSolver, [(1, 1), zone[1][1], se, duty])) pool.close() pool.join() zone = [[[], []], [[], []]] scambi = False bimbi_perduti = 0 for w in workers: res = w.get() #print(res) #print("index x:" +str(res[0][0])) #print("index y:" +str(res[0][1])) zone[res[0][0]][res[0][1]].extend(res[1]) YY = res[0][0] XX = res[0][1] if ((YY - 1) >= 0): #top if (len(res[2]) > 0): scambi = True zone[YY - 1][XX].extend(res[2]) else: bimbi_perduti = bimbi_perduti + len(res[2]) if ((XX - 1) >= 0): #left if (len(res[3]) > 0): scambi = True zone[YY][XX - 1].extend(res[3]) else: bimbi_perduti = bimbi_perduti + len(res[3]) if ((XX + 1) <= 1): #right if (len(res[4]) > 0): scambi = True zone[YY][XX + 1].extend(res[4]) else: bimbi_perduti = bimbi_perduti + len(res[4]) if ((YY + 1) <= 1): #bottom if (len(res[5]) > 0): scambi = True zone[YY + 1][XX].extend(res[5]) else: bimbi_perduti = bimbi_perduti + len(res[5]) #print('abbiamo perso n '+str(bimbi_perduti)) return (zone, scambi)
def resizePDF(self, pdf, x = 0, y = 0): self.rect = Rect(x,y,x,y) for item in self.items: self.setFontPDF(pdf, item) item.resizePDF(pdf,x,y) item.rect.translate(0,self.rect.height()) self.rect.unite(item.rect) self.refit()
def test_intersect_of_non_overlapping_rects(self): r1 = Rect(10, 20, 20, 30) r2 = Rect(10, 30, 20, 40) # abuts the bottom of r1 without intersecting r3 = Rect(20, 20, 30, 40) # abuts the right of r1 without intersecting self.assertIsNone(r1.intersect(r2)) self.assertIsNone(r2.intersect(r1)) self.assertIsNone(r1.intersect(r3)) self.assertIsNone(r3.intersect(r1))
def loadimage(self): self.image_rect = Rect(self.image.size) self.w = self.image_rect.w self.h = self.image_rect.h self.region_rect = Rect((0, 0), (self.w, self.h)) self.edited_img = self.image.copy().convert('RGB') self.displayimage()
def get_rect(self, **attr): """ Return rect of the surface. An optional keyword argument of the rect position. """ rect = Rect(0, 0, self.width, self.height) for key in attr: rect.__setattr__(key, attr[key]) return rect
def get_rect(self, **attr): """ Return rect of the surface. An optional keyword argument of the rect position. """ rect = Rect(0, 0, self.width, self.height) for key in attr: rect.__setattr__(key,attr[key]) return rect
def make_map(self): #fill map with "blocked" tiles self.map = [[ Tile(True) for y in range(self.height) ] for x in range(self.width) ] #create two rooms rooms = [] num_rooms = 0 for r in range(self.max_rooms): #random width and height w = libtcod.random_get_int(0, self.room_min_size, self.room_max_size) h = libtcod.random_get_int(0, self.room_min_size, self.room_max_size) #random position without going out of the boundaries of the map x = libtcod.random_get_int(0, 0, self.width - w - 1) y = libtcod.random_get_int(0, 0, self.height - h - 1) #"Rect" class makes rectangles easier to work with new_room = Rect(x, y, w, h) #run through the other rooms and see if they intersect with this one #if we find an intersection we need to generate a new room # if len(list(filter(new_room.intersect, rooms))) > 0: # continue #"paint" it to the map's tiles self.create_room(new_room) #center coordinates of new room, will be useful later (new_x, new_y) = new_room.center() if num_rooms == 0: #this is the first room, where the player starts at self.starting_pos = (new_x, new_y) else: #all rooms after the first: #connect it to the previous room with a tunnel #center coordinates of previous room (prev_x, prev_y) = rooms[num_rooms-1].center() #draw a coin (random number that is either 0 or 1) if libtcod.random_get_int(0, 0, 1) == 1: #first move horizontally, then vertically self.create_h_tunnel(prev_x, new_x, prev_y) self.create_v_tunnel(prev_y, new_y, new_x) else: #first move vertically, then horizontally self.create_v_tunnel(prev_y, new_y, prev_x) self.create_h_tunnel(prev_x, new_x, new_y) #finally, append the new room to the list rooms.append(new_room) num_rooms += 1
def create_leaf(cls, rooto, leaf_obj, leaf_rect): rect = Rect(leaf_rect.x, leaf_rect.y, leaf_rect.xx, leaf_rect.yy) rect.swapped_x = True # Mark as leaf by setting the xswap flag. res = _NodeCursor.create(rooto, rect) idx = res.index res.first_child = rooto.leaf_count rooto.leaf_count += 1 res.next_sibling = 0 rooto.leaf_pool.append(leaf_obj) res._save_back() res._become(idx) assert (res.is_leaf()) return res
def generate_background(pict, bbxes, min_height, min_width): for i in xrange(N_TRIALS): rand_bbx = Rect(pict.shape[0], pict.shape[1]) intersects = True if rand_bbx.height < min_height or rand_bbx.width < min_width: continue intersects = False for bbx in bbxes: intersects = intersects or rand_bbx.intersects(bbx) if not intersects: break if not intersects: return pict[rand_bbx.ymin:rand_bbx.ymax,rand_bbx.xmin:rand_bbx.xmax] else: return None
def rectOverlaps(self, rect): minX,minY,maxX,maxY = self.getTileBoundsInclusive(rect) tw = self.tileWidth th = self.tileHeight for layer in self.collideLayers: for y in range(minY,maxY+1): for x in range(minX,maxX+1): idx = x + y*layer.width if layer.tileGIDs[idx] != 0: r = Rect(x*tw, y*th, tw,th) if r.intersects(rect): return True return False
class PackNode(object): """ Creates an area which can recursively pack smaller areas into itself. """ def __init__(self, xywh): self.rect = Rect(xywh) def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.rect) def insert(self, xywh): """ Insert an rect into the current rect. Returns a new Node representing the new rect. Returns None if no space is available for the new rect. """ if hasattr(self, 'children'): for child in self.children: r = child.insert(xywh) if r is not None: return r return None rect = Rect(xywh) if self.rect.fits(rect): a = PackNode((self.rect.left+rect.width, self.rect.bottom, self.rect.width-rect.width, rect.height)) b = PackNode((self.rect.left, self.rect.bottom+rect.height, self.rect.width, self.rect.height-rect.height)) self.children = [a,b] return PackNode((self.rect.left, self.rect.bottom, rect.width, rect.height))
def test_border_tiles(self): rect = Rect(0, 0, 3, 3) border_tiles = rect.get_border_tiles() self.assertTrue((0, 0) in border_tiles) self.assertTrue((1, 0) in border_tiles) self.assertTrue((2, 0) in border_tiles) self.assertTrue((1, 0) in border_tiles) self.assertTrue((1, 2) in border_tiles) self.assertTrue((2, 0) in border_tiles) self.assertTrue((2, 1) in border_tiles) self.assertTrue((2, 2) in border_tiles) self.assertFalse((1, 1) in border_tiles) # middle self.assertFalse((3, 1) in border_tiles) # out of bounds rect = Rect(1, 7, 1, 2) border_tiles = rect.get_border_tiles() self.assertEqual(len(border_tiles), 2)
class MathColumn(MultiItem): """Container for inline maths""" def __init__(self, *items): MultiItem.__init__(self) self.style = ('math-var',1) for item in items: self.appendItem(item) def resizePDF(self, pdf, x = 0, y = 0): self.rect = Rect(x,y,x,y) for item in self.items: self.setFontPDF(pdf, item) item.resizePDF(pdf,x,y) item.rect.translate(0,self.rect.height()) self.rect.unite(item.rect) self.refit()
def __init__(self, horizontal, x, y, length): if horizontal: w = length h = self.thickness() self.outer_rect = Rect.from_dimensions( x + self.thickness() / 2, y - WALL_WIDTH, w - int(1.08 * self.thickness()), h + WALL_WIDTH) else: w = self.thickness() h = length self.outer_rect = Rect.from_dimensions( x - WALL_WIDTH, y + self.thickness() / 2, w + WALL_WIDTH, h - int(1.45 * self.thickness())) self.inner_rect = Rect.from_dimensions(x, y, w, h)
class MathFrac(MultiItem): """Container for inline maths""" def __init__(self, num = None, denom = None): MultiItem.__init__(self) self.style = 'math-var', 1 if num: if not denom: denom = MathNumber('1') self.appendItem(num) self.appendItem(denom) def resizePDF(self, pdf, x = 0, y = 0): if len(self.items) < 2 or not self.items[0] or not self.items[1]: raise Exception('MathFrac must have two items.') self.rect = Rect(x,y,x,y) dx = pdf.get_string_width(' ') * self.style[1] self.margins.set(dx, 0.0) setFontPDF(pdf, self.style, self.styles) lineHeight = pdf.font_size_pt / pdf.k numerator = self.items[0] if hasattr(numerator,'style'): setFontPDF(pdf, numerator.style, self.styles) numerator.resizePDF(pdf,x + dx, y - lineHeight * 0.5) denominator = self.items[1] if hasattr(denominator,'style'): setFontPDF(pdf, denominator.style, self.styles) denominator.resizePDF(pdf, x + dx, numerator.rect.y1()) if numerator.rect.width() > denominator.rect.width(): denominator.rect.alignXCenter(numerator.rect) else: numerator.rect.alignXCenter(denominator.rect) self.rect.unite(numerator.rect) self.rect.unite(denominator.rect) self.rect.adjust(rect.Point(0,0),rect.Point(dx,0)) def cellPDF(self, pdf, r = None): MultiItem.cellPDF(self, pdf, r) y = self.items[0].rect.y1() pdf.set_line_width(0.2) if r: x_shift = r.x0() y_shift = r.y0() else: x_shift = 0.0 y_shift = 0.0 pdf.line(self.rect.x0() - x_shift, y - y_shift, self.rect.x1() - x_shift, y - y_shift)
class TreeNode: def __init__(self, label=""): self.rect = Rect(0, 0, *SIZE) self.label = label def is_suitable(self): """ Testing if this instance is suitable. Wraps is_suitable() from Rect """ return self.rect.is_suitable() def __str__(self): return u"<{}> {}".format(self.label, self.rect)
def main(): dungeon_map = [['_' for x in xrange(MAP_HEIGHT)] for x in xrange(MAP_WIDTH)] rooms = [] num_rooms = 0 for r in xrange(MAX_ROOMS): width = random.randrange(ROOM_MIN_SIZE, ROOM_MAX_SIZE) height = random.randrange(ROOM_MIN_SIZE, ROOM_MAX_SIZE) xcorner = random.randrange(0, MAP_WIDTH - width - 1) ycorner = random.randrange(0, MAP_HEIGHT - height - 1) new_room = Rect(xcorner, ycorner, width, height) # new_room.print_rect() if num_rooms > 0: for other_room in rooms: if new_room.intersect(other_room): break dungeon_map = create_room(new_room, dungeon_map) (new_x, new_y) = new_room.center() (prev_x, prev_y) = rooms[num_rooms-1].center() if random.randrange(0, 1) == 1: #first move horizontally, then vertically dungeon_map = create_h_tunnel(prev_x, new_x, prev_y, dungeon_map) dungeon_map = create_v_tunnel(prev_y, new_y, new_x, dungeon_map) else: #first move vertically, then horizontally dungeon_map = create_v_tunnel(prev_y, new_y, prev_x, dungeon_map) dungeon_map = create_h_tunnel(prev_x, new_x, new_y, dungeon_map) rooms.append(new_room) num_rooms = num_rooms + 1 else: dungeon_map = create_room(new_room, dungeon_map) rooms.append(new_room) num_rooms = num_rooms + 1 print_dungeon_map(dungeon_map)
def digCave(nature): caves = RESOURCES.count('CAVE') print('Digging %d cave%s' % ( caves, 's' if caves > 1 else '')) for p in range(0,RESOURCES.count('CAVE')): CX = config['CITY_SIZE_X'] CY = config['CITY_SIZE_Y'] CX2 = config['CITY_SIZE_X']//2 CY2 = config['CITY_SIZE_Y']//2 CX3 = config['CITY_SIZE_X']//3 CY3 = config['CITY_SIZE_Y']//3 p=Point(CX2,CY2) MPS=200 mps=30 if(random.randint(0,1)==0): p1=Point(random.randint(0,CX3),random.randint(0,CY)) else: p1=Point(random.randint(0,CX),random.randint(0,CY3)) p2=Point(random.randint(p1.x+mps,p1.x+MPS), random.randint(p1.y+mps,p1.y+MPS)) place=Rect(p1,p2) place.set_name('CAVE') nature.append(place)
def __init__(self, items=None, depth=8, bounding_rect=None): """Creates a quad-tree. @param items: A sequence of items to store in the quad-tree. Note that these items must be of SimObject. @param depth: The maximum recursion depth. @param bounding_rect: The bounding rectangle of all of the items in the quad-tree. Type of Rect or (x,y,w,h) of the rectangle For internal use only. """ # The sub-quadrants are empty to start with. self.nw = self.ne = self.se = self.sw = None self.depth = depth # Find this quadrant's centre. if bounding_rect: bounding_rect = Rect(bounding_rect) else: # If there isn't a bounding rect, then calculate it from the items. if items: bounding_rect = Rect(items[0].get_bounding_rect()) for item in items[1:]: bounding_rect.add(Rect(item.get_bounding_rect())) else: # in case there are no items, assume a big rect (100x100 # meters) bounding_rect = Rect((0.0, 0.0, 100.0, 100.0)) self.rect = bounding_rect self.items = [] # Insert items self.insert_items(items)
def test_temp(yy,xx,place): nw=Rect(Point(0,0),Point(CITY_SIZE_X/2,CITY_SIZE_Y/2)) ne=Rect(Point(CITY_SIZE_X/2,0),Point(CITY_SIZE_X,CITY_SIZE_Y/2)) sw=Rect(Point(0,CITY_SIZE_Y/2),Point(CITY_SIZE_X/2,CITY_SIZE_Y)) se=Rect(Point(CITY_SIZE_X/2,CITY_SIZE_Y/2),Point(CITY_SIZE_X,CITY_SIZE_Y)) if(xx==0)and(yy==0): if(not nw.overlaps(place)): print('errore micidiale 1'); if(xx==0)and(yy==1): if(not ne.overlaps(place)): print('errore micidiale 2'); if(xx==1)and(yy==0): if(not sw.overlaps(place)): print('errore micidiale 3'); if(xx==1)and(yy==1): if(not se.overlaps(place)): print('errore micidiale 4');
def resizePDF(self, pdf, x = 0, y = 0): self.resizeItemsPDF(pdf, x, y) dx = pdf.get_string_width(' ') * self.style[1] self.rect = Rect(x,y,x,y) h = self.base.rect.height() w = self.base.rect.width() + dx if self.subscript: self.subscript.rect.translate(w, h*0.5) self.rect.unite(self.subscript.rect) if self.superscript: self.superscript.rect.translate(w, - h*0.5) self.rect.unite(self.superscript.rect) self.refit()
def update_layout(self): SingleContainer.update_layout(self) if self.theme: patch = self.theme['folding_box'][('image_closed' if self._collapsed else 'image')] if self.content: self._w = self.content.w + patch.padding_left + patch.padding_right if not self._collapsed: self._h = self.content.h + patch.padding_bottom + patch.padding_top self.elements['topbar'].update(patch.padding_left, self.h - patch.padding_top, self.w - patch.padding_left - patch.padding_right, 1) self.elements['title'].x = patch.padding_left self.elements['title'].y = self.h - patch.padding_top/2 + 1 self.topbar = Rect(0, self.h-patch.padding_top, self.w, patch.padding_top)