def draw_round_border(surface, width=4, color=None, bounds=None): """draw_round_border(Surface, line_width, Color, Rect) => None only Surface is required""" h = surface.get_height() w = surface.get_width() img = dialog.circle_border_image if color == None: color = pygame.color.Color("white") if bounds == None: bounds = surface.get_rect() r = Rect(0,0,8,8) border = bounds.inflate(-8,-8) border.topleft = bounds.topleft surface.blit(img, border.topleft, r) r.top = 8 surface.blit(img, border.bottomleft, r) r.left = 8 surface.blit(img, border.bottomright, r) r.top = 0 surface.blit(img, border.topright, r) i = bounds.inflate(-17,-17) o = bounds.inflate(-3,-3) o.topleft = bounds.topleft draw.line(surface, color, (i.left,o.top),(i.right,o.top), 4 ) draw.line(surface, color, (o.left,i.top),(o.left,i.bottom), 4 ) draw.line(surface, color, (i.left,o.bottom),(i.right,o.bottom), 4 ) draw.line(surface, color, (o.right,i.top),(o.right,i.bottom), 4 )
def create_platforms_rect(self, tiles, layer): """ Create a collision rect for each non-empty tile segment, that is, one or more tiles together """ if len(tiles) < 1: return False x, y = tiles.pop(0) width = self.map.content['tilewidth'] height = self.map.content['tileheight'] rect = Rect((0, 0, 0, 0)) rect.left = x * width rect.top = y * height rect.width = width rect.height = height # self.platforms.append(Platform(rect, layer)) n_tiles_x, n_tiles_y = 0, 0 # exclude the tiles we're about to create a platform for excluded_tiles = [] for (n_x, n_y) in tiles: if abs(n_x - x) == n_tiles_x and n_y == y: rect.width += width n_tiles_x += 1 excluded_tiles.append((n_x, n_y)) if abs(n_y - y) == n_tiles_y and n_x == x: rect.height += height n_tiles_y += 1 excluded_tiles.append((n_x, n_y)) self.platforms.append(Platform(rect, layer)) self.create_platforms_rect([t for t in tiles if not t in excluded_tiles], layer)
def bounce_in_box(bounce_obj_rect: Rect, bounce_object_speed, \ box_rect: Rect) -> bool: """ Bounce the object if it hits the border of the box. The speed and the position of the `bounce_obj` will be updated. @param bounce_obj_rect The Rect of the bouncing object @param bounce_obj_speed The 2D speed vector of the bouncing object. @return Whether the `bounce_obj` hits the box or not. """ hit = False if bounce_obj_rect.left <= box_rect.left: bounce_obj_rect.left = box_rect.left bounce_object_speed[0] *= -1 hit = True elif bounce_obj_rect.right >= box_rect.right: bounce_obj_rect.right = box_rect.right bounce_object_speed[0] *= -1 hit = True if bounce_obj_rect.top <= box_rect.top: bounce_obj_rect.top = box_rect.top bounce_object_speed[1] *= -1 hit = True elif bounce_obj_rect.bottom >= box_rect.bottom: bounce_obj_rect.bottom = box_rect.bottom bounce_object_speed[1] *= -1 hit = True return hit
def drawDebugRects(sgroup, color_cb): for s in (sgroup): color = color_cb(s) srect = Rect(s.rect) srect.left += self.scenebuf_delta_x srect.top = self.GAME_HEIGHT - 50 self.backbuf.fill(color, srect)
def scroll_up_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.top = m r.right = self.width - m r.inflate_ip(-4, -4) return r
def get_bullet_image(index, w=16, h=16): global bullet_image if not bullet_image: bullet_image = image.load(resource_path(config.nbtTreeSettings.bulletFileName.get())) r = Rect(0, 0, w, h) line_length = int(bullet_image.get_width() / w) line = int(index / line_length) r.top = line * h r.left = (index - (line * line_length)) * w return bullet_image.subsurface(r)
def test_top( self ): """Changing the top attribute moves the rect and does not change the rect's width """ r = Rect( 1, 2, 3, 4 ) new_top = 10 r.top = new_top self.assertEqual( Rect(1,new_top,3,4), r ) self.assertEqual( new_top, r.top )
def test_top(self): """Changing the top attribute moves the rect and does not change the rect's width """ r = Rect(1, 2, 3, 4) new_top = 10 r.top = new_top self.assertEqual(Rect(1, new_top, 3, 4), r) self.assertEqual(new_top, r.top)
def draw(self): #First draw container rect,then draw text rect inside it self.text_surface= self.font.render(self.text, True,self.font_color,self.bgcolor) self.text_size=self.text_surface.get_size() container_rect=Rect(self.x_y[0]-self.border_width,self.x_y[1] - self.border_width,self.text_size[0] + self.border_width,self.text_size[1]+self.border_width) container_rect.top=self.x_y[1] container_rect.left=self.x_y[0] self.text_dest=self.x_y+(self.border_width,self.border_width) pygame.draw.rect(self.surface,self.border_color,container_rect) self.surface.blit(self.text_surface,self.text_dest)
def get_paddle_rect(self, controller): if controller == self.cl: return self.pl.rect # Mirror paddle rect size = (PADDLE_WIDTH, PADDLE_HEIGHT) topleft = (PADDLE_MARGIN_X, PADDLE_MARGIN_Y) rect = Rect(topleft, size) rect.top = self.pr.rect.top return rect
def add_button(self, rect: pygame.Rect, title: str): if len(self.buttons) > 0: i = len(self.buttons) - 1 rect.top += self.buttons[i].size[1] + self.buttons[i].top + 50 elif len(self.subtitles) > 0: i = len(self.subtitles) - 1 rect.top = self.subtitles[i][0].get_size( )[0] + self.subtitles[i][1][1] + 50 else: rect.top += self.menu_title.get_size( )[1] + self.menu_title_dest[1] + 50 self.buttons.append(Button(rect, title))
def __contains__(self, event: Event): r = Rect(self._rect) r.left = 0 r.top = 0 answer: bool = False try: p = self.global_to_local(event.pos) pList = list(p) answer = r.collidepoint(pList[0], pList[1]) except AttributeError as ae: self.logger.error(f"{ae.__repr__()}") return answer
def push_ip(larger_rect: Rect, smaller_rect: Rect): '''Larger rect pushes out smaller rect via the smallest possible vector.''' clip = larger_rect.clip(smaller_rect) if not clip: return if clip.height <= clip.width: if smaller_rect.centery <= clip.centery: smaller_rect.bottom = larger_rect.top else: smaller_rect.top = larger_rect.bottom else: if smaller_rect.centerx <= clip.centerx: smaller_rect.right = larger_rect.left else: smaller_rect.left = larger_rect.right
def setSlider(self, ratio): ''' Create a Rectangle corresponding to the slider position position will be relative to the surface so modify the top acc. to ratio ''' rect = Rect( (0, 0), self.rect.size ) # set position to origin as fill rect is relative to surface rect.top = rect.height - int(rect.height * ratio) # change position rect.height = int(rect.height * ratio) # change size self.surf.fill(TEAL, rect=rect) # now fill in what's remaining with background brect = Rect((0, 0), self.rect.size) brect.height = rect.top self.surf.fill(BLACK, rect=brect)
def render_discard_pile(board_render, player_id, seat): group = Group() match = board_render.match player = match.players[player_id] if player.discard_pile is None: return group rect = Rect(board_render.surface.get_rect()) rect.center = (0, 0) side_calculation = (SMALL_TILE_SIZE[1] + 10) * 3 if seat == 0: rect.bottom = side_calculation + TILE_SIZE[1] + 20 if seat == 2: rect.top = -side_calculation tile_offset = 10 tiles_per_row = 12 i = 0 row = 0 row_offset = SMALL_TILE_SIZE[1] + tile_offset full_width = tiles_per_row * (SMALL_TILE_SIZE[0] + tile_offset) - tile_offset beginning_of_across_line = (rect.width - full_width) / 2 beginning_of_across_line += full_width if seat == 2 else 0 across = beginning_of_across_line for tile in player.discard_pile: tile_pos = (across, -rect.y + (row * row_offset)) tile_sprite = TileRender( board_render.small_dictionary, tile, tile_pos, small_tile=True, rotation=seat, ) group.add(tile_sprite) across += (SMALL_TILE_SIZE[0] + tile_offset if seat == 0 else -(SMALL_TILE_SIZE[0] + tile_offset)) i += 1 if i >= tiles_per_row: i = 0 row += 1 if seat == 0 else -1 across = beginning_of_across_line return group
def split_surface(sprite_sheet, subsurface_tuple): """ Return a list of Surface objects pulled from the sprite sheet. The list is in order from top to bottom, left to right. The subsurface_tuple is expected to be (width, height). """ subsurfaces = [] surface_rect = sprite_sheet.get_rect() subsurface_size = (surface_rect.width // subsurface_tuple[0], surface_rect.height // subsurface_tuple[1]) rect = Rect((0, 0), subsurface_size) for i in range(subsurface_tuple[0]): rect.left = i * rect.width for j in range(subsurface_tuple[1]): rect.top = j * rect.width subsurfaces.append(sprite_sheet.subsurface(rect)) return subsurfaces
def draw_text(text='sample text', color=(255, 255, 255), pos=(0, 0), surface=None, align_x='left', align_y='top'): if (surface == None): surface = api.screen text_rect = Rect(0, 0, *font.size(text)) if (align_x == 'left'): text_rect.left = pos[0] elif (align_x == 'center'): text_rect.centerx = pos[0] elif (align_x == 'right'): text_rect.right = pos[0] if (align_y == 'top'): text_rect.top = pos[1] elif (align_y == 'center'): text_rect.centery = pos[1] elif (align_y == 'bottom'): text_rect.bottom = pos[1] surface.blit(font.render(text, 1, color), text_rect)
def bounce_in_box_ip(bounce_obj_rect: Rect, bounce_obj_speed, box_rect: Rect): """ Bounce the object if it hits the border of the box. The speed and the position of the `bounce_obj` will be updated. @param bounce_obj_rect The Rect of the bouncing object @param bounce_obj_speed The 2D speed vector of the bouncing object. """ if bounce_obj_rect.left <= box_rect.left: bounce_obj_rect.left = box_rect.left bounce_obj_speed[0] *= -1 elif bounce_obj_rect.right >= box_rect.right: bounce_obj_rect.right = box_rect.right bounce_obj_speed[0] *= -1 if bounce_obj_rect.top <= box_rect.top: bounce_obj_rect.top = box_rect.top bounce_obj_speed[1] *= -1 elif bounce_obj_rect.bottom >= box_rect.bottom: bounce_obj_rect.bottom = box_rect.bottom bounce_obj_speed[1] *= -1
def align_rect(outer: pygame.Rect, inner: pygame.Rect, coords, *, halign: Literal["left", "center", "right"] = "left", valign: Literal["top", "center", "bottom"] = "top", outer_halign: Literal["left", "center", "right"] = "left", outer_valign: Literal["top", "center", "bottom"] = "top"): """Calculate coordinates for an inner rectangle aligned to an outer rectangle""" x, y = coords if outer_halign == "left": pass elif outer_halign == "center": x = outer.centerx + x elif outer_halign == "right": x = outer.right + x if outer_valign == "top": pass elif outer_valign == "center": y = outer.centery + y elif outer_valign == "bottom": y = outer.bottom + y if halign == "left": inner.left = x elif halign == "center": inner.centerx = x elif halign == "right": inner.right = x if valign == "top": inner.top = y elif valign == "center": inner.centery = y elif valign == "bottom": inner.bottom = y return inner.topleft
def bounce_off_ip(bounce_obj_rect: Rect, bounce_obj_speed, \ hit_obj_rect: Rect, hit_obj_speed): """ Update the speed and position of the `bounce_obj` after it bounces off the `hit_obj`. This function is called only when two objects are colliding. @param bounce_obj_rect The Rect of the bouncing object @param bounce_obj_speed The 2D speed vector of the bouncing object. @param hit_obj_rect The Rect of the hit object @param hit_obj_speed The 2D speed vector of the hit object """ # Treat the hit object as an unmoveable object speed_diff_x = bounce_obj_speed[0] - hit_obj_speed[0] speed_diff_y = bounce_obj_speed[1] - hit_obj_speed[1] # The relative position between top and bottom, and left and right # of two objects at the last frame rect_diff_T_B = bounce_obj_rect.top - hit_obj_rect.bottom - speed_diff_y rect_diff_B_T = bounce_obj_rect.bottom - hit_obj_rect.top - speed_diff_y rect_diff_L_R = bounce_obj_rect.left - hit_obj_rect.right - speed_diff_x rect_diff_R_L = bounce_obj_rect.right - hit_obj_rect.left - speed_diff_x # Set the position and speed of the bouncing object # acccroding to the relative position of two objects if rect_diff_T_B > 0 and rect_diff_B_T > 0: bounce_obj_rect.top = hit_obj_rect.bottom bounce_obj_speed[1] *= -1 elif rect_diff_T_B < 0 and rect_diff_B_T < 0: bounce_obj_rect.bottom = hit_obj_rect.top bounce_obj_speed[1] *= -1 if rect_diff_L_R > 0 and rect_diff_R_L > 0: bounce_obj_rect.left = hit_obj_rect.right bounce_obj_speed[0] *= -1 elif rect_diff_L_R < 0 and rect_diff_R_L < 0: bounce_obj_rect.right = hit_obj_rect.left bounce_obj_speed[0] *= -1
def __draw_hitpoints(self, camera): """ Draw the entity's hitpoints, or a marker showing where it is if it's off screen. """ entities = self.__entity_manager.query(Body, Hitpoints) for entity in entities: body = entity.get_component(Body) hitpoints = entity.get_component(Hitpoints) # Draw health bar if it's on screen. Otherwise draw marker. rect = Rect(0, 0, body.size * 2, 6) rect.center = rect.center = camera.world_to_screen(body.position) rect.top = rect.top - (body.size * 1.2) self.__draw_bar(camera, rect, hitpoints.hp / float(hitpoints.max_hp), (255, 255, 255), (255, 0, 0), (0, 255, 0)) # Sneakily draw a power bar as well if the entity has it. power = entity.get_component(Power) if power is not None: rect.top += rect.height + 4 self.__draw_bar(camera, rect, power.power / float(power.capacity), (255, 255, 255), (100, 50, 0), (255, 255, 0))
def limit_paddles(self, paddle: pygame.Rect): if paddle.top < 0: paddle.top = 0 elif paddle.bottom > GAME_HEIGHT: paddle.bottom = GAME_HEIGHT return paddle
def reverse_clamp_ip(larger_rect: Rect, smaller_rect: Rect): if not larger_rect.contains(smaller_rect): larger_rect.left = min(larger_rect.left, smaller_rect.left) larger_rect.right = max(larger_rect.right, smaller_rect.right) larger_rect.top = min(larger_rect.top, smaller_rect.top) larger_rect.bottom = max(larger_rect.bottom, smaller_rect.bottom)
def main(): pygame.init() pantalla=pygame.display.set_mode((800,600)) pygame.FULLSCREEN pygame.display.set_caption("ProyectoPygame") reloj1=pygame.time.Clock() salir=False p1 = Personaje() p1._x = 430 p1._y = 180 p1.x_antes = 50 p1.y_antes = 50 p1.tam_rectangulos((70, 70)) p1.actualizacionRec() p2 = Personaje() p2._x = 100 p2._y = 200 p2.tam_rectangulos((100, 100)) p2.actualizacionRec() plataforma2 = Plataforma() plataforma2.setXY(250, 200) plataforma2.setTamRect(300, 100) p1_antes = Rect(p1.x_antes, p1.y_antes, 70, 70) motor = MotorVideojuego() motor.conjuntoPersonajes = [p1, p2] #motor.start() start = pygame.time.get_ticks()/1000 iter=0 limit=1000 l = reposicion(p1, plataforma2) while salir == False: lista=pygame.event.get()#((pygame.KEYDOWN, pygame.KEYUP, pygame.QUIT, pygame.MOUSEBUTTONDOWN)) for event in lista: #----------Escuchando Eventos del Usuario-# if event.type == pygame.QUIT: salir = True if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: p1.setSalto(True) print "SAlta" if event.type == pygame.MOUSEMOTION: xy=pygame.mouse.get_pos() p1.x_antes = xy[0] p1.y_antes = xy[1] p1_antes.left = xy[0] p1_antes.top = xy[1] l = reposicion(p1, plataforma2) pantalla.fill((0,0,240)) if pygame.time.get_ticks()>limit: #print iter limit+=1000 iter=0 iter+=1 pygame.draw.rect(pantalla, green, plataforma2.rectangulo) pygame.draw.rect(pantalla, red, p1.rectangulo) pygame.draw.rect(pantalla, red, p1_antes) for rec in l: pygame.draw.rect(pantalla, darkBlue, rec) reloj1.tick(120) pygame.display.update() motor.salirJuego = True pygame.quit()
print "*** MCEDIT DEBUG:", e print "*** MCEDIT DEBUG: bullets image file:", resource_path( config.nbtTreeSettings.bulletFileName.get()) print "*** MCEDIT DEBUG: current directory:", os.getcwd() from pygame import Surface, draw, SRCALPHA bullet_image = Surface((64, 64), SRCALPHA) bullet_image.fill((0, 0, 0, 0)) for i in range(4): for j in range(4): bullet_image.fill( (255 / (i or 1), 255 / (j or 1), 255, 255), [16 * i, 16 * j, 16 * i + 16, 16 * j + 16]) r = Rect(0, 0, w, h) line_length = int(bullet_image.get_width() / w) line = int(index / line_length) r.top = line * h r.left = (index - (line * line_length)) * w return bullet_image.subsurface(r) default_bullet_styles = { TAG_Byte: ((20, 20, 200), None, 'circle', 'b'), TAG_Double: ((20, 200, 20), None, 'circle', 'd'), TAG_Float: ((200, 20, 20), None, 'circle', 'f'), TAG_Int: ((16, 160, 160), None, 'circle', 'i'), TAG_Long: ((200, 20, 200), None, 'circle', 'l'), TAG_Short: ((200, 200, 20), (0, 0, 0), 'circle', 's'), TAG_String: ((60, 60, 60), None, 'circle', 's'), TAG_Compound: (bullet_color_active, None, '', ''), TAG_Byte_Array: ((20, 20, 200), None, 'square', 'B'), TAG_Int_Array: ((16, 160, 160), None, 'square', 'I'),
bullet_image = image.load(resource_path(config.nbtTreeSettings.bulletFileName.get())) except Exception, e: print "*** MCEDIT DEBUG: bullets image could not be loaded." print "*** MCEDIT DEBUG:", e print "*** MCEDIT DEBUG: bullets image file:", resource_path(config.nbtTreeSettings.bulletFileName.get()) print "*** MCEDIT DEBUG: current directory:", os.getcwd() from pygame import Surface, draw, SRCALPHA bullet_image = Surface((64, 64), SRCALPHA) bullet_image.fill((0, 0, 0, 0)) for i in range(4): for j in range(4): bullet_image.fill((255/(i or 1), 255/(j or 1), 255, 255), [16*i, 16*j, 16*i+16, 16*j+16]) r = Rect(0, 0, w, h) line_length = int(bullet_image.get_width() / w) line = int(index / line_length) r.top = line * h r.left = (index - (line * line_length)) * w return bullet_image.subsurface(r) default_bullet_styles = {TAG_Byte: ((20, 20, 200), None, 'circle', 'b'), TAG_Double: ((20, 200, 20), None, 'circle', 'd'), TAG_Float: ((200, 20, 20), None, 'circle', 'f'), TAG_Int: ((16, 160, 160), None, 'circle', 'i'), TAG_Long: ((200, 20, 200), None, 'circle', 'l'), TAG_Short: ((200, 200, 20), (0, 0, 0), 'circle', 's'), TAG_String: ((60, 60, 60), None, 'circle', 's'), TAG_Compound: (bullet_color_active, None, '', ''), TAG_Byte_Array: ((20, 20, 200), None, 'square', 'B'), TAG_Int_Array: ((16, 160, 160), None, 'square', 'I'), TAG_List: ((200, 200, 200), (0, 0, 0), 'square', 'L'),
def __contains__(self, event): r = Rect(self._rect) r.left = 0 r.top = 0 p = self.global_to_local(event.pos) return r.collidepoint(p)
ang, distance = self.angle, self.speed return sin(ang) * distance, cos(ang) * distance def collide(self): angle = self.angle x, y = self.center radius = self.get_radius() rect = Rect(x - radius, y - radius, radius * 2, radius * 2) bandit = self.parent.bandit.rect if rect.colliderect(bandit): if bandit.left - rect.right > rect.top - bandit.bottom: angle = -angle rect.right = bandit.left else: angle = pi - angle rect.top = bandit.bottom field = self.parent.rect if rect.right > field.w or rect.left < 0: angle = -angle if rect.right > field.w: rect.right = field.w else: rect.left = 0 if rect.top < 0 or rect.bottom > field.h: angle = pi - angle if rect.top < 0: rect.top = 0 else: rect.bottom = field.h self.angle = angle self.center = rect.center