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 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 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 scroll_left_rect(self): d = self.scroll_button_size r = Rect(0, 0, d, d) m = self.margin r.bottom = self.height - m r.left = 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_left( self ): """Changing the left attribute moves the rect and does not change the rect's width """ r = Rect( 1, 2, 3, 4 ) new_left = 10 r.left = new_left self.assertEqual( new_left, r.left ) self.assertEqual( Rect(new_left,2,3,4), r )
def test_left(self): """Changing the left attribute moves the rect and does not change the rect's width """ r = Rect(1, 2, 3, 4) new_left = 10 r.left = new_left self.assertEqual(new_left, r.left) self.assertEqual(Rect(new_left, 2, 3, 4), r)
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_debug_zone(self, controller): w, h = self.size rect = Rect((0, PADDLE_MARGIN_Y), (PADDLE_MARGIN_X, h - 2 * PADDLE_MARGIN_Y)) if controller == self.cl: rect.right = PADDLE_MARGIN_X return rect else: rect.left = w - PADDLE_MARGIN_X return rect
def draw_infinity_bg(screen: Surface, image: Surface, rect1: Rect, rect2: Rect) -> None: """ Draws the infinity backround. It uses two rectangles to swap the images. The two rectangles are moving in one direction. One of them is always with WIDTH ahead of the other rectangle. So if it reaches the end, every rectangle goes back with -WIDTH. """ rect1.left += 1 rect2.left += 1 if rect1.left == WIDTH: rect1.left = -WIDTH if rect2.left == WIDTH: rect2.left = -WIDTH screen.blit(image, rect1) screen.blit(image, rect2)
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 load_image_array(name): fullpath = os.path.join(RESOURCE_PATH, name) image = pygame.image.load(fullpath) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() width, height = image.get_size() if width % height != 0: raise ValueError, 'Image has invalid dimensions' image_list = [] rect = Rect((0, 0), (height, height)) for i in xrange(width / height): rect.left = i * height image_list.append(image.subsurface(rect)) return image_list
def render_vertical_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) * 4 if seat == 1: rect.right = side_calculation + 180 if seat == 3: rect.left = -side_calculation - 180 tile_offset = 10 tiles_per_row = 8 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.height - ((rect.height - full_width) / 2) beginning_of_across_line -= full_width if seat == 3 else 0 across = beginning_of_across_line for tile in player.discard_pile: tile_pos = (-rect.x + (row * row_offset), across) 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 == 1 else -(SMALL_TILE_SIZE[0] + tile_offset)) i += 1 if i >= tiles_per_row: i = 0 row += 1 if seat == 1 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 load_images(): images = {} images['Terrain'] = {} images['Terrain'][False] = load_file('Terrain-Solid.png') images['Terrain'][True] = load_file('Terrain-Spikes.png') images['Terrain']['Goal'] = load_file('Goal.png') images['Player'] = {} images['Player']['Idle'] = load_file('Player-Idle.png') images['Player']['Jump'] = load_file('Player-Jump.png') images['Player']['Fall'] = load_file('Player-Fall.png') images['Player']['Dead'] = load_file('Player-Dead.png') images['Player']['Run'] = [load_file(('Player-Run-'+str(frame)+'.png')) for frame in range(1,3)] images['Player']['Walk'] = [load_file(('Player-Walk-'+str(frame)+'.png')) for frame in range(1,3)] images['Player']['Run'].insert(0,images['Player']['Idle']) images['Player']['Walk'].insert(0,images['Player']['Idle']) images['Digits'] = [] digit_rect = Rect(0,0,5,8) digit_image = load_file('Digits.png') for digit_number in range(10): images['Digits'].append(Surface([5,8],SRCALPHA,32)) images['Digits'][-1].blit(digit_image,[0,0],digit_rect) digit_rect.left = digit_rect.right digit_rect.left += 1 images['Splash'] = {} images['Splash']['Logo'] = load_file('yuriifreire.png') images['Splash']['Title'] = load_file('Title.png') images['Splash']['Presents'] = load_file('Presents.png') images['Splash']['Press-Any-Key'] = load_file('Press-Any-Key.png') return images
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 get_bullet_rect(self, surf, lvl): r = Rect(0, 0, self.bullet_size, self.bullet_size) r.left = self.bullet_size * lvl r.inflate_ip(-4, -4) return r
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)
aiPaddle.y = 0 ai_speed = 0 elif aiPaddle.bottom > height: aiPaddle.bottom = height ai_speed = 0 if playerPaddle.colliderect(ball): playerSound.play() ball_speed_x = -ball_speed_x if player_speed == 0: ball_speed_y = ball_speed_y/abs(ball_speed_y) else: ball_speed_y = player_speed ball.left = playerPaddle.right + 1 elif aiPaddle.colliderect(ball): playerSound.play() ball_speed_x = -ball_speed_x # prevent if ai_speed == 0: ball_speed_y = ball_speed_y/abs(ball_speed_y) else: ball_speed_y = ai_speed ball.right = aiPaddle.x - 1 if ball.y <= 0: sideSound.play()
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()
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 def update_total_elapsed(self): current_ticks = time.get_ticks() self.total_elapsed += current_ticks - self.last_ticks self.last_ticks = current_ticks def draw_circle(self):
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)
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'),
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'), TAG_Short_Array: ((200, 200, 20), None, 'square', 'S'),