我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.SRCALPHA。
def style(srf, bg=None, border=(0,0,0), weight=0, padding=0): "Create a new surface with padding, background color, and/or border" w, h = srf.get_size() # Add padding padding += weight w += 2 * padding h += 2 * padding img = pygame.Surface((w, h), pygame.SRCALPHA) # Add background color and border if bg: img.fill(rgba(bg)) img.blit(srf, (padding, padding)) if weight: drawBorder(img, border, weight) return img
def test_render(self): csv = textwrap.dedent(self.TILEMAP_CSV).strip() tilemap = (sappho.tiles.TileMap. from_csv_string_and_tilesheet(csv, self.tilesheet)) # Create a surface that has 1x2 strips of red, green, and # blue to against the rendered tilemap. This surface has # to have the SRCALPHA flag and a depth of 32 to match # the surface returned by the render function. test_surface = pygame.surface.Surface((3, 2), pygame.SRCALPHA, 32) test_surface.fill((255, 0, 0), pygame.Rect(0, 0, 1, 2)) test_surface.fill((0, 255, 0), pygame.Rect(1, 0, 1, 2)) test_surface.fill((0, 0, 255), pygame.Rect(2, 0, 1, 2)) # Render the tilemap output_surface = tilemap.to_surface() # Compare the two surfaces assert(compare_surfaces(test_surface, output_surface))
def create_surface_layers(target_surface, number_of_layers): """Create a list of pygame surfaces the size of the target surface. Arguments: target_surface (pygame.Surface): The surface whose dimensions will be used for each layer. number_of_layers (int): The number of surfaces to create/return. Returns: list[pygame.Surface]: List of surfaces """ surface_layers = [] for i in range(number_of_layers): surface = pygame.surface.Surface(target_surface.get_size(), pygame.SRCALPHA, 32) surface_layers.append(surface) return surface_layers
def __init__(self, source_resolution, output_resolution, view_resolution, behavior=None): """Create a Camera! Arguments: view_resolution (tuple[int, int]): used to create view_rect attribute. """ super(Camera, self).__init__(output_resolution) self.source_surface = pygame.surface.Surface(source_resolution, pygame.SRCALPHA) self.source_resolution = source_resolution self.output_resolution = output_resolution self.view_rect = pygame.Rect((0, 0), view_resolution) self.behavior = behavior or CameraBehavior()
def snapshot(self): "Capture the canvas as an Image instance" srf = pygame.Surface(self.size, pygame.SRCALPHA) # Draw background if isinstance(self._bg, Image): self._bg.config(size=self._size) srf.blit(self._bg.image, (0,0)) elif self._bg: srf.fill(self._bg) # Draw objects for g in self: if g.snapshot is not None: xy = g.blitPosition((0,0), g.size) srf.blit(g.snapshot().image, xy) else: g.draw(srf, snapshot=True) # Draw border if self.weight: drawBorder(srf, self.border, self.weight) return Image(srf)
def main(): pygame.init() screen = pygame.display.set_mode((500,500)) screen.fill((255, 0, 0)) s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32) pygame.draw.line(s, (0,0,0), (250, 250), (250+200,250)) width = 1 for a_radius in range(width): radius = 200 pygame.gfxdraw.aacircle(s, 250, 250, radius-a_radius, (0, 0, 0)) screen.blit(s, (0, 0)) pygame.display.flip() try: while 1: event = pygame.event.wait() if event.type == pygame.QUIT: break if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.unicode == 'q': break pygame.display.flip() finally: pygame.quit()
def test_save_colorkey(self): """ make sure the color key is not changed when saving. """ s = pygame.Surface((10,10), pygame.SRCALPHA, 32) s.fill((23,23,23)) s.set_colorkey((0,0,0)) colorkey1 = s.get_colorkey() p1 = s.get_at((0,0)) temp_filename = "tmpimg.png" try: pygame.image.save(s, temp_filename) s2 = pygame.image.load(temp_filename) finally: os.remove(temp_filename) colorkey2 = s.get_colorkey() # check that the pixel and the colorkey is correct. self.assertEqual(colorkey1, colorkey2) self.assertEqual(p1, s2.get_at((0,0)))
def test_copy(self): # __doc__ (as of 2008-06-25) for pygame.surface.Surface.copy: # Surface.copy(): return Surface # create a new copy of a Surface color = (25, 25, 25, 25) s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) s1.fill(color) s2 = s1.copy() s1rect = s1.get_rect() s2rect = s2.get_rect() self.assert_(s1rect.size == s2rect.size) self.assert_(s2.get_at((10,10)) == color)
def test_fill(self): # __doc__ (as of 2008-06-25) for pygame.surface.Surface.fill: # Surface.fill(color, rect=None, special_flags=0): return Rect # fill Surface with a solid color color = (25, 25, 25, 25) fill_rect = pygame.Rect(0, 0, 16, 16) s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) s1.fill(color, fill_rect) for pt in test_utils.rect_area_pts(fill_rect): self.assert_(s1.get_at(pt) == color ) for pt in test_utils.rect_outer_bounds(fill_rect): self.assert_(s1.get_at(pt) != color )
def test_fill_negative_coordinates(self): # negative coordinates should be clipped by fill, and not draw outside the surface. color = (25, 25, 25, 25) color2 = (20, 20, 20, 25) fill_rect = pygame.Rect(-10, -10, 16, 16) s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) r1 = s1.fill(color, fill_rect) c = s1.get_at((0,0)) self.assertEqual(c, color) # make subsurface in the middle to test it doesn't over write. s2 = s1.subsurface((5, 5, 5, 5)) r2 = s2.fill(color2, (-3, -3, 5, 5)) c2 = s1.get_at((4,4)) self.assertEqual(c, color) # rect returns the area we actually fill. r3 = s2.fill(color2, (-30, -30, 5, 5)) # since we are using negative coords, it should be an zero sized rect. self.assertEqual(tuple(r3), (0, 0, 0, 0))
def test_get_alpha(self): # __doc__ (as of 2008-06-25) for pygame.surface.Surface.get_alpha: # Surface.get_alpha(): return int_value or None # get the current Surface transparency value s1 = pygame.Surface((32,32), pygame.SRCALPHA, 32) self.assert_(s1.get_alpha() == 255) for alpha in (0, 32, 127, 255): s1.set_alpha(alpha) for t in range(4): s1.set_alpha(s1.get_alpha()) self.assert_(s1.get_alpha() == alpha) ########################################################################
def test_set_colorkey(self): # __doc__ (as of 2008-06-25) for pygame.surface.Surface.set_colorkey: # Surface.set_colorkey(Color, flags=0): return None # Surface.set_colorkey(None): return None # Set the transparent colorkey s = pygame.Surface((16,16), pygame.SRCALPHA, 32) colorkeys = ((20,189,20, 255),(128,50,50,255), (23, 21, 255,255)) for colorkey in colorkeys: s.set_colorkey(colorkey) for t in range(4): s.set_colorkey(s.get_colorkey()) self.assertEquals(s.get_colorkey(), colorkey)
def __init__(self, x, y, sceneData, max_health=10): super().__init__() self.name = "ChargePad" self.frameAnimationSpeed = 15 imageBase = pygame.image.load(os.path.join('img', 'unbranded-cola.png')) imageRot = pygame.transform.rotate(imageBase, 10) imageRot2 = pygame.transform.rotate(imageBase, 20) imageRot3 = pygame.transform.rotate(imageBase, -10) frames = [imageRot3,imageBase, imageRot,imageRot2,imageRot,imageBase] self.animation = Animation(frames, self.frameAnimationSpeed, True) self.image = frames[0] self.imageTransparent = pygame.Surface((1, 1),pygame.SRCALPHA) self.rect = self.image.get_rect() # Position centrée du player self.x = x self.y = y self.rect.x = x self.rect.y = y self.sceneData = sceneData
def __init__(self, x, y, sceneData, max_health=10): super().__init__() self.name = "ChargePad" self.frameAnimationSpeed = 20 imageBase = pygame.image.load(os.path.join('img', 'charge-pad.png')) imageFlash = pygame.image.load(os.path.join('img', 'charge-pad-flash.png')) frames = [imageBase, imageFlash] self.animation = Animation(frames, self.frameAnimationSpeed, True) self.image = frames[0] self.imageTransparent = pygame.Surface((1, 1),pygame.SRCALPHA) self.rect = self.image.get_rect() # Position centrée du player self.x = x self.y = y self.rect.x = x self.rect.y = y self.sceneData = sceneData
def draw_car(self, player_data): """ ??? """ carImagePath = self.theme + ('/mycar.png' if player_data.name is self.current_player.name else "/car.png") carImage = pygame.image.load(carImagePath).convert(32, pygame.SRCALPHA) rotatedCar = pygame.transform.rotate(carImage, -player_data.rotation * 180 / math.pi) carRect = rotatedCar.get_rect() carRect.center = self.calculate_offset(player_data.pos_x, player_data.pos_y) self.surf.blit(rotatedCar, carRect) font = pygame.font.Font('font/wqy-microhei.ttc', 18) nameSurf = font.render(player_data.name, True, Constants.NAME_COLOR) nameRect = nameSurf.get_rect() nameRect.center = self.calculate_offset(player_data.pos_x, player_data.pos_y - 48) # FIXME: ??????????? ?????? surf.fill(NAMEBG, nameRect) self.surf.blit(nameSurf, nameRect)
def __init__(self, x, y, color, direction, speed, container, brain = None): pygame.sprite.Sprite.__init__(self, container) self.image = pygame.Surface((16,16), flags=pygame.SRCALPHA) self.rect = self.image.get_rect() basex = 423 if color==RED: basex += 96 ## Generate the sprite image from spritesheet ssrect = pygame.Rect((basex,710,16,16)) global spritesheet self.image.blit(spritesheet,(0,0),ssrect) self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction self.speed = speed self.brain = brain
def draw(self,surface): rad2 = Vector(self.radius,self.radius) if self.idle: # Range-circle surf = pg.Surface((self.shot_range*2,)*2, pg.SRCALPHA) pg.draw.circle(surf, (0,0,255,50), (self.shot_range,)*2, self.shot_range) surface.blit(surf, self.pos-(self.shot_range,)*2) pg.draw.circle(surface, (0,0,255), self.pos, self.shot_range,3) # Tower itself render_image = pg.transform.rotozoom(self.image,-self.angle,1) # rotozoom for a bit AA draw_center = self.pos - Vector( *render_image.get_size() )/2 surface.blit(render_image, draw_center) if not self.placeable: # Red circle, if not allowed to place aSurf = pg.Surface((self.radius*2,)*2, pg.SRCALPHA) aSurf.convert_alpha() radius = int(self.radius) pg.draw.circle(aSurf,(255,0,0,50), rad2, radius) pg.draw.circle(aSurf,(255,0,0,250), rad2, radius, 3) surface.blit(aSurf,draw_center)
def __init__(self, ls, w, h, l, t, value): pygame.sprite.Sprite.__init__(self) self.ls = ls self.w = w self.h = h self.left = l self.top = t self.focus_order = -1 if self.ls.lang.ltr_text: self.right_align = False else: self.right_align = True self.font_color = self.ls.colors.font_color self.value = value self.select_item = False self.update_me = True self.image = pygame.Surface([w, h], flags=pygame.SRCALPHA) self.rect = self.image.get_rect() self.rect.topleft = [l, t] self.font_v = self.ls.font_2
def layout_update(self): self.color = (255, 255, 255, 150) self.scheme = "white" if self.game_board.mainloop.scheme is not None: if self.game_board.mainloop.scheme.dark: self.scheme = "black" self.color = (0, 0, 0, 150) self.width = self.layout.game_w self.height = self.layout.game_h self.image = pygame.Surface([self.width, self.height], flags=pygame.SRCALPHA) self.image.fill(self.color) self.rect = self.image.get_rect() self.rect.topleft = [0, 0] self.img = pygame.image.load(os.path.join('res', 'images', self.img_src)).convert_alpha() self.img2 = pygame.image.load(os.path.join('res', 'images', self.img_src2)).convert_alpha() # img2 has the same size img_pos_x = self.img.get_rect(centerx=self.image.get_width() // 2) img_pos_y = self.img.get_rect(centery=self.image.get_height() // 2) self.img_pos = (img_pos_x[0], img_pos_y[1])
def generate_images(font): # generate a scanline image to create scanline effect scanline = pygame.Surface((glyph_width, glyph_height), pygame.SRCALPHA) for y in range(0, glyph_height, 2): pygame.draw.line(scanline, (0, 0, 0, 128), (0, y), (glyph_width, y)) # render all characters a head of time for char in charset: chars = list() cache.append(chars) for value in computed_values: color = calc_color(value) temp = font.render(char, 1, color) temp = pygame.transform.smoothscale(temp, (glyph_width, glyph_height)) temp.blit(scanline, (0, 0)) image = pygame.Surface(temp.get_size()) image.blit(temp, (0, 0)) chars.append(image)
def get_tile(self, image_name, clip_x, clip_y): if image_name not in self.images: s = pygame.Surface((self.tile_size,self.tile_size)) s.fill((0,0,0)) return s surface = self.images[image_name] rect = pygame.Rect( ( clip_x*self.tile_size, clip_y*self.tile_size, self.tile_size, self.tile_size ) ) image = pygame.Surface(rect.size, pygame.SRCALPHA) image.fill((0,0,0,0)) image.blit(surface, (0, 0), rect) return image
def render(self): surface = pygame.Surface(self.parent.resolution) for y in range(self.fireworks.get_height()): for x in range(self.fireworks.get_width()): node = self.fireworks.get_cell(x,y) if node > 0: pygame.draw.rect(surface, colours.COLOUR_YELLOW, (x*self.firework_size, y*self.firework_size, self.firework_size, self.firework_size)) surface.blit(self.congratulations_text, ((surface.get_width()-self.congratulations_text.get_width())/2, surface.get_height()/2 - 150) ) surface.blit( self.team1_text, ((surface.get_width()-self.team1_text.get_width())/2, (surface.get_height()-self.team1_text.get_height())/2) ) mask = pygame.Surface(self.parent.resolution, pygame.SRCALPHA) mask.fill((0,0,0, 255-self.alpha)) surface.blit(mask, (0,0)) return surface
def render(self): surface = pygame.Surface(self.root.resolution) if self.cur_animation < 3: banner = self.versus_banner.render() surface.blit(banner, ( (surface.get_width()-banner.get_width())//2, (surface.get_height()-banner.get_height())//2 ) ) else: window = self.battle_window.render() status = self.mage_status.render() window.blit(status, (0, window.get_height()-200)) round_count = self.round_counter.render() window.blit(round_count, self.round_counter.get_pos()) surface.blit(window, (0,0)) mask = pygame.Surface(self.root.resolution, pygame.SRCALPHA) mask.fill((0,0,0, 255-self.alpha)) surface.blit(mask, (0,0)) return surface
def main(): pygame.init() screen = pygame.display.set_mode((500,500)) screen.fill((255, 0, 0)) s = pygame.Surface(screen.get_size(), pygame.SRCALPHA, 32) pygame.gfxdraw.aacircle(s, 250, 250, 200, (0, 0, 0)) screen.blit(s, (0, 0)) pygame.display.flip() try: while 1: event = pygame.event.wait() if event.type == pygame.QUIT: break if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE or event.unicode == 'q': break pygame.display.flip() finally: pygame.quit()
def todo_test_blit__SRCALPHA_to_SRCALPHA_non_zero(self): #TODO # " There is no unit test for blitting a SRCALPHA source with non-zero # alpha to a SRCALPHA destination with non-zero alpha " LL w,h = size = 32,32 s = pygame.Surface(size, pygame.SRCALPHA, 32) s2 = s.copy() s.fill((32,32,32,111)) s2.fill((32,32,32,31)) s.blit(s2, (0,0)) # TODO: # what is the correct behaviour ?? should it blend? what algorithm? self.assertEquals(s.get_at((0,0)), (32,32,32,31))
def setSize(self, size): self.geometry = size self.geometry2 = [self.geometry[0]+13,self.geometry[1]+29] self.pos2 = (self.pos[0]+self.geometry2[0], self.pos[1]+self.geometry2[1]) self.pos3 = (self.pos[0]+self.geometry2[0]/2, self.pos[1]+self.geometry2[1]/2) self.surface = pygame.Surface((self.geometry[0], self.geometry[1])) self.surfaceTemp = pygame.Surface((self.geometry[0], self.geometry[1])) self.widgetSurface = pygame.Surface((self.geometry[0], self.geometry[1]), pygame.SRCALPHA, 32) self.animStage = [self.geometry[0],self.geometry[1]] self.animDone = True self.widgets = [] if (not self.oldWidgets == None) or (not self.oldWidgets == []): for widget in self.oldWidgets: if type(widget) is str: self.widgets += [eval(widget)] self.widgets[len(self.widgets)-1].setScreen(self.widgetSurface, self.sysRes, self.sysVar)
def __init__(self, workQueue, queueLock, dataDir): super(Extension, self).__init__() # super() will call Thread.__init__ for you self.workQueue = workQueue self.queueLock = queueLock self.tData = ['', [], 'Extension'] self.hasQueue = False print (pygame.display.Info().current_w, pygame.display.Info().current_h) self.screenTemp = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h), pygame.SRCALPHA, 32) '''Used by the WM to prevent flickering''' self.screen = pygame.Surface((pygame.display.Info().current_w, pygame.display.Info().current_h), pygame.SRCALPHA, 32) '''Screen buffer that extensions draw on''' self._stop = threading.Event() self.dataDir = dataDir self.errorData = None self.args = None self.extName = "Unnamed Extension" #self.screen.fill((255,255,255,255))
def draw_progressbar(surface, rect, color, bgcolor, progress, text="", radius=0.7): draw_roundrect(surface, rect, bgcolor, radius) foreground = pygame.surface.Surface(rect.size, pygame.SRCALPHA) draw_roundrect(foreground, foreground.get_rect(), color, radius) revealed = (0, 0, rect.width * progress, rect.height) foreground.set_colorkey((0, 0, 0)) surface.blit(foreground, rect.topleft, area=revealed) if text == "": return font = pygame.font.Font("texgyreadventor-regular.otf", 15) text = font.render(text, True, (20, 20, 20)) t_rect = text.get_rect(center=rect.center) surface.blit(text, t_rect)
def _getAppearance(self, *args): """ Return the underlying Widget's appearance; Renders the Listbox's list and selection private function parameters: tuple arguments for the update (first argument should be an instance pygame.event.Event) return values: pygame.Surface the underlying Widget's appearance """ surface = super(Listbox, self)._getAppearance(*args) linesize = self._font.get_linesize() for n in range(len(self._list)): surface.blit(self._font.render(str(self._list[n]), pygame.SRCALPHA, self._foreground), (0, linesize * n)) if self.isFocused(): s, e = self._sort(CURSOR, SELECTION) for n in range(s, e + 1): selection = pygame.Surface((self._bounds.width, linesize), pygame.SRCALPHA, 32) selection.fill(self._selectioncolor) surface.blit(selection, (0, linesize * n)) return surface
def __init__(self, x, y, width, height): """ Initialisation of a Widget parameters: int x-coordinate of the Widget (left) int y-coordinate of the Widget (top) int width of the Widget int height of the Widget return values: - """ super(Widget, self).__init__() self.image = pygame.Surface((width, height), pygame.SRCALPHA, 32) self._bounds = self.image.get_rect().move(x, y) self.rect = self._bounds.copy() self._border = defaultBorder self._focus = False self._active = True self._foreground = defaultForeground self._background = defaultBackground
def _getAppearance(self, *args): """ Blits the text to the Button's Surface and returns the result. private function parameters: tuple arguments for the update (first argument should be an instance pygame.event.Event) return values: pygame.Surface the underlying Widget's appearance """ surface = super(Button, self)._getAppearance(*args) center = surface.get_rect().center size = self._font.size(self._text) coords = (center[0] - size[0] / 2, center[1] - size[1] / 2) surface.blit(self._font.render(str(self._text), pygame.SRCALPHA, self._foreground), coords) if self._state: overlay = surface.copy() if self._state == 2: overlay.fill(self._pressedcolor) else: overlay.fill(self._hoveredcolor) surface.blit(overlay, (0, 0)) return surface
def _getRoundRect(self, rect, color): """ Draw a rectangle with rounded corners and return the bordered result parameters: pygame.Rect the bounds of the rectangle to be drawn tuple of format pygame.Color for the color to draw with return values: pygame.Surface the rectangle """ rect.topleft = 0, 0 surface = pygame.Surface(rect.size, pygame.SRCALPHA) surface.fill(color, rect.inflate(-2 * self.radius, 0)) surface.fill(color, rect.inflate(0, -2 * self.radius)) corners = rect.inflate(-2 * self.radius, -2 * self.radius) pygame.draw.circle(surface, color, corners.topleft, self.radius) pygame.draw.circle(surface, color, corners.topright, self.radius) pygame.draw.circle(surface, color, corners.bottomleft, self.radius) pygame.draw.circle(surface, color, corners.bottomright, self.radius) return surface
def _getAppearance(self, *args): """ Return the underlying Widget's appearance; Renders the Entry's text, cursor and selection private function parameters: tuple arguments for the update (first argument should be an instance pygame.event.Event) return values: pygame.Surface the underlying Widget's appearance """ surface = super(Entry, self)._getAppearance(*args) linesize = self._font.get_linesize() surface.blit(self._font.render(str(self._text), pygame.SRCALPHA, self._foreground), (0, (self._bounds.height - linesize) / 2)) if self.isFocused(): cursor = pygame.Surface((2, linesize)) cursor.fill(self._foreground) surface.blit(cursor, (self._indexToPos(CURSOR), (self._bounds.height - linesize) / 2)) selection = pygame.Surface((abs(self._indexToPos(CURSOR) - self._indexToPos(SELECTION)), linesize), pygame.SRCALPHA, 32) selection.fill(self._selectioncolor) surface.blit(selection, (self._sort(self._indexToPos(CURSOR), self._indexToPos(SELECTION))[0] , (self._bounds.height - linesize) / 2)) return surface
def cria_nave(posicao): nave = {} nave['contador'] = 0 nave['corpo'] = fisica.cria_corpo(posicao[0], posicao[1]) nave['corpo']['massa'] = 5 nave['corpo']['direcao'] = 90 nave['surface'] = pygame.surface.Surface( (24, 38), pygame.SRCALPHA, 32).convert_alpha() pygame.draw.line(nave['surface'], WHITE, ( 1, 34), (12, 1), 2) pygame.draw.line(nave['surface'], WHITE, (24, 34), (12, 1), 2) pygame.draw.line(nave['surface'], WHITE, ( 3, 24), (21, 24), 2) nave['surface'] = pygame.transform.rotozoom(nave['surface'], -90, 1) return nave
def cria_arteroide(tela, posicao): arteroide = pygame.surface.Surface((90, 84), pygame.SRCALPHA, 32).convert_alpha() pontos_asteroide_1 = ( (19, 0), (40, 18), (60, 0), (80, 18), (64, 38), (78, 59), (50, 80), (15, 80), (0, 63), (0, 20)) pontos_asteroide_2 = ( (3, 21), (33, 21), (22, 3), (52, 3), (82, 21), (82, 31), (46, 42), (82, 62), (63, 82), (47, 71), (19, 82), (3, 51)) pontos_asteroide_3 = ( (32, 5), (63, 5), (82, 33), (82, 47), (53, 82), (32, 82), (38, 47), (18, 82), (3, 53), (21, 43), (3, 35)) asteroides = [pontos_asteroide_1, pontos_asteroide_2, pontos_asteroide_3] pygame.draw.polygon(arteroide, WHITE, asteroides[random.randint(0, 2)], 1) tela.blit(arteroide, posicao) # função que cria o personagem patrulha
def __init__( self, x, y, color, direction=1, ): pygame.sprite.Sprite.__init__(self, self.containers) """self.image = pygame.Surface((2, 18), pygame.SRCALPHA, 32) self.image = self.image.convert_alpha() pygame.draw.rect(self.image, color, (0, 0, 2, 18)) # (12,225,15) self.rect = self.image.get_rect() """ self.image,self.rect = load_image('lazer.png',5,25,-1) self.rect.center = (x, y - direction * 20) self.direction = direction
def __init__( self, x, y, color, direction, speed, ): pygame.sprite.Sprite.__init__(self, self.containers) self.image = pygame.Surface((10, 10), pygame.SRCALPHA, 32) self.image = self.image.convert_alpha() self.col = list(color) for i in range(5, 0, -1): self.col[0] = color[0] * float(i) / 5 self.col[1] = color[1] * float(i) / 5 self.col[2] = color[2] * float(i) / 5 pygame.draw.circle(self.image, tuple(self.col), (5, 5), i, 0) self.rect = self.image.get_rect() self.rect.center = (x, y) # + direction[1]*20) self.direction = direction self.speed = speed
def __init__(self, size, walls): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface(size, pygame.SRCALPHA) self.rect = self.image.get_rect() self.visible_area = self.image.copy() self.image.fill((20,20,20,255)) self.footprint = self.rect self.footprint.midbottom = self.rect.midbottom self.mask = pygame.mask.from_surface(self.visible_area) self.visible_position = [-1, -1] # Sprite details to conform to sprite group self.velocity = [0, 0] self._position = [0, 0] self._old_position = self.position self.feet = pygame.Rect(0, 0, self.rect.width * .5, 8)
def renderTile(self, address, getColor): if address in self.tiles: return self.tiles[address] tile = pygame.Surface((8, 8), pygame.SRCALPHA) for y in range(8): address_y = address + y * 2 low_byte = self.mem.read(address_y) high_byte = self.mem.read(address_y + 1) for x in range(8): mask = 1 << x low_bit = int(bool(low_byte & mask)) high_bit = int(bool(high_byte & mask)) color = (high_bit << 1) | low_bit tile.set_at((7 - x, y), getColor(color)) self.tiles[address] = tile return tile
def loadTiles(self, image, columns, rows, name, alpha = True): image = image.convert_alpha() tile_width = math.floor(image.get_width()/columns) tile_height = math.floor(image.get_height()/rows) need_to_scale = True if self.tilemap == None or (tile_width == self.tilemap.tile_width and tile_height == self.tilemap.tile_height): need_to_scale = False images = [None] * (columns*rows) for y in range(rows): id_offset = y*columns for x in range(columns): img = pygame.Surface((tile_width, tile_height), flags=pygame.SRCALPHA) if not alpha: img = pygame.Surface((tile_width, tile_height)) img.blit(image, [0,0], [x*tile_width, y*tile_height, tile_width, tile_height]) if need_to_scale: img = pygame.transform.scale(img, (self.tilemap.tile_width, self.tilemap.tile_height)).convert_alpha() #if alpha: # img = img.convert_alpha() images[id_offset+x] = img self.images[name] = images self.createIcon(name) #loads a resource file detailing the location, name and dimensions of images to load.
def loadTiles(self, image, columns, rows, name): image = image.convert_alpha() tile_width = math.floor(image.get_width()/columns) tile_height = math.floor(image.get_height()/rows) need_to_scale = True if tile_width == self.tilemap.tile_width and tile_height == self.tilemap.tile_height: need_to_scale = False images = [None] * (columns*rows) og_images = [None] * (columns*rows) for y in range(rows): id_offset = y*columns for x in range(columns): img = pygame.Surface((tile_width, tile_height), flags=pygame.SRCALPHA).convert_alpha() img.blit(image, [0,0], [x*tile_width, y*tile_height, tile_width, tile_height]) og_images[id_offset+x] = img if need_to_scale: img = pygame.transform.scale(img, (self.tilemap.tile_width, self.tilemap.tile_height)).convert_alpha() images[id_offset+x] = img self.og_images[name] = og_images self.images[name] = images self.createIcon(name)
def render_cities(city_sites,font): for i in city_sites: city = i.city x,y = i.get_cords() screen = pygame.display.get_surface() pygame.draw.rect(screen,(0,0,0),(x-8,y-8,16,16)) toWrite = font.render(city.name, True, (30,30,30)) w,h = toWrite.get_size() s = pygame.Surface((w,h ), pygame.SRCALPHA) # per-pixel alpha s.fill((255,255,255,128)) screen.blit(s,(x-28,y+12)) screen.blit(toWrite,(x-28,y+12))
def to_surface(self): """Blit the TileMap to a surface Returns: pygame.Surface: Surface containing the tilemap """ tile_size_x, tile_size_y = self.tilesheet.tile_size width_in_tiles = len(self.tiles[0]) height_in_tiles = len(self.tiles) layer_size = (width_in_tiles * tile_size_x, height_in_tiles * tile_size_y) new_surface = pygame.Surface(layer_size, pygame.SRCALPHA, 32) new_surface.fill([0, 0, 0, 0]) for y, row_of_tiles in enumerate(self.tiles): for x, tile in enumerate(row_of_tiles): # blit tile subsurface onto respective layer tile_position = (x * tile_size_x, y * tile_size_y) new_surface.blit(tile.image, tile_position) return new_surface
def image(self): if self._srf: return self._srf srf = pygame.Surface(self.size, pygame.SRCALPHA) r = round(self.radius) w = self.weight if w: pygame.draw.circle(srf, self._stroke, (r,r), r) f = self._fill if f or w: if not f: f = 0, 0, 0, 0 pygame.draw.circle(srf, f, (r,r), r-w) self._srf = srf return srf
def render(self): "Render the polygon onto a new Surface" w, f, s = round(self.weight), self._fill, self._stroke dx, dy = self._rect.topleft dx = w - dx dy = w - dy size = self.size size = 2 * w + size[0], 2 * w + size[1] srf = pygame.Surface(size, pygame.SRCALPHA) pts = list((x+dx,y+dy) for (x,y) in self.vertices) if f: pygame.draw.polygon(srf, f, pts) if w and s: pygame.draw.polygon(srf, s, pts, w) return srf
def _apply(srf, pos, size, origSize): "Blit the visible subsurface onto a transparent background" img = pygame.Surface(origSize, pygame.SRCALPHA) img.blit(srf.subsurface(pos, size), pos) return img
def _apply(srf, pos, size, origSize): "Blit the scaled image onto a transparent background" srf = pygame.transform.smoothscale(srf, size) img = pygame.Surface(origSize, pygame.SRCALPHA) img.blit(srf, pos) return img