def __init__(self, evManager, numlines=3, rect=(0, 0, 100, 20), txtcolor=(255, 0, 0), bgcolor=None): Widget.__init__(self, evManager) self._em.reg_cb(ChatlogUpdatedEvent, self.on_remotechat) self._em.reg_cb(MGameAdminEvt, self.on_gameadmin) self._em.reg_cb(MNameChangeFailEvt, self.on_namechangefail) self._em.reg_cb(MMyNameChangedEvent, self.on_namechangesuccess) self._em.reg_cb(MNameChangedEvt, self.on_namechangesuccess) self._em.reg_cb(MdHpsChangeEvt, self.on_updatehps) self.font = Font(None, config_get_fontsize()) self.rect = rect size = rect.size self.txtcolor = txtcolor self.bgcolor = bgcolor if bgcolor: # completely opaque bg img = Surface(size) img.fill(self.bgcolor) img = img.convert() else: # more or less transparent img = Surface(self.rect.size, SRCALPHA) # handles transparency transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) # black img = img.convert_alpha() self.image = img self.maxnumlines = numlines self.linewidgets = deque(maxlen=numlines) # deque of TextLabelWidgets
class Bullet(pygame.sprite.Sprite, Drawable, EventHandler): height = 5 width = 5 def __init__(self, x, y, direction: Directon = Directon.UP, velocity=5): super().__init__() self.velocity = velocity self.direction = direction self.rect = Rect(int(x - self.width / 2), y - self.height, self.width, self.height) self.image = Surface((self.width, self.height)) self.image.fill(WHITE) def handle(self, event: pygame.event.Event): pass def draw(self, surface: pygame.Surface): pygame.draw.rect(surface, WHITE, self.rect) def update(self, *args, **kwargs): # noinspection PyTypeChecker self.rect.move_ip(0, self.velocity * self.direction.value) if self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: self.kill()
def prepare_paragraph(text, width, size="normal", colour=(0,0,0)): font = FONTS[size] lines = [] words = text.split() if words: lastline = None line = words[0] for i in range(1,len(words)): lastline = line line = line+" "+words[i] w,h = font.size(line) if w > width: lines.append(lastline) line = words[i] else: line = "" lines.append(line) parawidth = max(font.size(each)[0] for each in lines) lineheight = font.get_height() paraheight = lineheight*len(lines) paragraph = Surface((parawidth,paraheight),pygame.SRCALPHA) paragraph.fill((255,255,255,0)) for y,line in enumerate(lines): text = prepare(line,size,colour) paragraph.blit(text,(0,y*lineheight)) return paragraph
def __init__(self, fruit, interp_step): """ Prepare the fruit's spr: a square diamond with a number in the center. interp_step determines where to position the sprite, based on the view's current sprite step. """ DirtySprite.__init__(self) self.fruit = fruit # make the square sq_surf = Surface((cell_size / 1.414, cell_size / 1.414)) sq_surf.set_colorkey((255, 0, 255)) # magenta = color key sq_surf.fill(FRUIT_COLORS[fruit.fruit_type]) # rotate for a diamond dm_surf = rotate(sq_surf, 45) blit_rect = Rect(0, 0, cell_size * 1.414, cell_size * 1.414) # blit the diamond as the fruit's image img = Surface((cell_size, cell_size)) img.set_colorkey((255, 0, 255)) # magenta = color key img.fill((255, 0, 255)) img.blit(dm_surf, blit_rect) # add text at the center self.font = Font(None, font_size) txtsurf = self.font.render(str(fruit.fruit_num), True, (0, 0, 0)) textpos = txtsurf.get_rect(center=(cell_size / 2, cell_size / 2)) img.blit(txtsurf, textpos) # prepare rect to blit on screen self.resync(interp_step) self.image = img
def update(self, duration): if self.dirty == 0: return # TODO: is bliting on existing surf faster than creating a new surface? size = self.rect.size txtcolor = self.txtcolor bgcolor = self.bgcolor if bgcolor: # opaque bg txtimg = self.font.render(self.text, True, txtcolor, bgcolor) txtimg = txtimg.convert() img = Surface(size) img.fill(bgcolor) else: # transparent bg txtimg = self.font.render(self.text, True, txtcolor) txtimg = txtimg.convert_alpha() img = Surface(size, SRCALPHA) # handle transparency img.fill((0, 0, 0, 0)) # 0 = transparent, 255 = opaque # center the txt inside its box ctr_y = size[1] / 2 textpos = txtimg.get_rect(left=2, centery=ctr_y) img.blit(txtimg, textpos) self.image = img
def prepare_table(rows, alignment="lr", size="normal", colour=(0,0,0), padding=0): f = FONTS[size] numcolumns = len(rows[0]) numrows = len(rows) def u(n): return n if isinstance(n, unicode) else unicode(n) shapes = [[f.size(u(col)) for col in row] for row in rows] maxheight = max(max(shape[1] for shape in shaperow) for shaperow in shapes) widths = [max(shaperow[i][0] for shaperow in shapes) for i in range(numcolumns)] table = Surface((sum(widths) + padding * (numcolumns - 1), maxheight * numrows + padding * (numrows - 1)), pygame.SRCALPHA) table.fill((255,255,255,0)) y = 0 for r, row in enumerate(rows): x = 0 for c, col in enumerate(row): w, h = shapes[r][c] text = prepare(u(col), size=size, colour=colour) align = alignment[c] if align == "r": adjustx = widths[c] - w elif align == "c": adjustx = (widths[c] - w) // 2 else: adjustx = 0 table.blit(text, (x + adjustx, y)) x += widths[c] + padding y += maxheight + padding return table
def activate(self): xsize = 300 ysize = 70 bkg = Surface((xsize, ysize)) bkg.lock() bkg.fill((128,128,128)) for i in range(1, 4): draw.rect(bkg,(i*32,i*32,i*32),(4-i,4-i,xsize+(i-4)*2,ysize+(i-4)*2),3) corner = (64,64,64) bkg.set_at((0,0), corner) bkg.set_at((xsize,0), corner) bkg.set_at((xsize,ysize), corner) bkg.set_at((0,ysize), corner) bkg.unlock() bkg.set_alpha(64) self.bkg = bkg if self.title != None: banner = OutlineTextBanner(self.title, (200,200,200), 20) self.title_image = banner.render() self.title_image.set_alpha(96) self.arrow = res.loadImage("wait_arrow.png", colorkey=1)
def create_turn_marker(board, parent_rect, group): MARKER_OFFSET = 20 MARKER_WIDTH = 5 current_turn = board.current_board.current_turn if current_turn % 2 == 0: marker_size = (parent_rect.width - MARKER_OFFSET, MARKER_WIDTH) else: marker_size = (MARKER_WIDTH, parent_rect.width - MARKER_OFFSET) marker_size_half = (marker_size[0] / 2, marker_size[1] / 2) parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - marker_size_half[1]), (parent_half_width - marker_size_half[0], 0), (0, -parent_half_height + marker_size_half[1]), (-parent_half_width + marker_size_half[0], 0), ] turn_marker_surface = Surface(marker_size) turn_marker_surface.fill((255, 255, 255)) sprite = Sprite() sprite.rect = turn_marker_surface.get_rect() sprite.image = turn_marker_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[current_turn][0] sprite.rect.y += SEAT_OFFSETS[current_turn][1] sprite.layer = 2 group.add(sprite)
def display_dialog(surface: Surface, name: str, dialog: str): WIDTH = 455 HEIGHT = 205 BORDER = 5 IN_WIDTH = WIDTH - BORDER IN_HEIGHT = HEIGHT - BORDER canevas = Surface((WIDTH, HEIGHT)) canevas.fill(color.TEXT_BACKGROUND_COLOR) pos = Vector(dimensions.WINDOW_WIDTH - (30 + IN_WIDTH), dimensions.WINDOW_HEIGHT - (30 + IN_HEIGHT)) sizes = Vector(IN_WIDTH, IN_HEIGHT) rect = pygame.Rect(Vector().to_pos(), sizes.to_pos()) draw.rect(canevas, color.WHITE, rect, 5) font_name = ImagesCache().fonts["dialog"].render("{}: ".format(name), True, color.TEXT_NAME_COLOR) canevas.blit(font_name, (5, 4)) height = 30 for line in break_dialog_lines(dialog): font_text = ImagesCache().fonts["dialog"].render( line, True, color.TEXT_FOREGROUND_COLOR) canevas.blit(font_text, (10, height)) height += 20 return functools.partial(surface.blit, canevas, pos.to_pos())
class Label(): def __init__(self, width, height, color): self.surface = Surface((width, height)) self.color = color self.surface.fill(color) def caption(self, text, fontStyle): myfont = font.SysFont(fontStyle.font, fontStyle.size) self.size = myfont.size(text) offsetX = (self.surface.get_width() - self.size[0]) / 2 offsetY = (self.surface.get_height() - self.size[1]) / 2 self.surface.fill(self.color) label = myfont.render(text, True, fontStyle.color) self.surface.blit(label, (offsetX, offsetY)) return self.surface def width(self): return self.size[0] def height(self): return self.size[1]
class WelcomeScreen(object): def __init__(self, mouse): self.mouse = mouse self.surface_size = (CONFIG['screen']['width']/2, CONFIG['screen']['height']/2) self.surface = Surface(self.surface_size) def draw(self, screen): text_box = TextBox(self.surface, align="center") self.surface.fill((0,175,75)) text_box.text_color = (32, 32, 32) text_box.background_color = ((0, 175, 75)) text_box.font_size = 35 text_box.draw_new_line("Welcome to the", margin_top=-20) text_box.draw_new_line("City Manager Game!") text_box.font_size = 25 text_box.draw_new_line("Here you can create new buildings, roads", margin_top=20) text_box.draw_new_line("and earn money from the things you have built.") text_box.draw_new_line(f"Every {CONFIG['income_period']/1000} seconds you will earn money", margin_top=5) text_box.draw_new_line("from your belongings.") text_box.draw_new_line("You can build new things using the ") text_box.draw_new_line("money you have as well.") text_box.draw_new_line("Have fun!") text_box.draw_new_line("Press enter to continue", margin_top=10) screen.blit(self.surface, (self.surface_size[0]/2, self.surface_size[1]/2))
class Grid: surface = None def __init__(self, width, height, spacing=20): self.width = width self.height = height self.spacing = spacing self.initializeSurface() def initializeSurface(self): self.surface = Surface((self.width, self.height), flags=HWSURFACE | SRCALPHA) self.surface.fill(Color(0, 0, 0, 0)) for i in range(0, self.width, self.spacing): pygame.draw.line(self.surface, Color(0, 0, 0, 255), (i, 0), (i, self.height)) for i in range(0, self.height, self.spacing): pygame.draw.line(self.surface, Color(0, 0, 0, 255), (0, i), (self.width, i)) pygame.draw.line(self.surface, Color(0, 0, 0, 255), (self.width - 1, 0), (self.width - 1, self.height)) pygame.draw.line(self.surface, Color(0, 0, 0, 255), (0, self.height - 1), (self.width, self.height - 1)) def render(self, screen): screen.blit(self.surface, (0, 0)) pass
class Star(pygame.sprite.Sprite, Drawable): height = 1 width = 1 move_step = 2 def __init__(self, direction: Directon = Directon.DOWN): super().__init__() self.direction = direction self.rect = Rect(random.randint(0, SCREEN_WITH), random.randint(0, SCREEN_HEIGHT), self.width, self.height) self.image = Surface((self.width, self.height)) self.image.fill(WHITE) def handle(self, event: pygame.event.Event): pass def draw(self, surface: pygame.Surface): pygame.draw.rect(surface, WHITE, self.rect) def update(self, *args, **kwargs): self.rect.move_ip(0, self.move_step) if self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: self.rect.y = 0 self.rect.x = random.randint(0, SCREEN_WITH)
def pygame_loop(surface_: surface.Surface, clock: time.Clock, update: bool = True) -> None: global num_of_iterations clock.tick(FPS) if update: num_of_iterations += 1 display.set_caption( f"Diffusion Limited Aggregation - {BETA} - {num_of_iterations}") for event in events.get(): if event.type == pygame.QUIT: at_end() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: at_end() if update: p.update() surface_.fill(BLACK) render(surface_) display.flip()
class Panel(Clickable): def __init__(self, x, y, w, h, color=0x000000): self.items = [] self.clickables = [] self.surface = Surface((w, h)) self.visible = True self.x = x self.y = y self.color = color def draw(self, screen): if self.visible: self.surface.fill(self.color) for item in self.items: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def add(self, item): self.items.append(item) if isinstance(item, Clickable): self.clickables.append(item) def is_pressed(self, wx, wy, button): if not self.visible: return False x = wx - self.x y = wy - self.y res = False for item in self.clickables: res = res or item.is_pressed(x, y, button) return res
class ResizeAlert(RootObject): def __init__(self, width, height, root_object_manager: RootObjectManager, timeout=1): self.width = width self.height = height self.root_object_manager = root_object_manager self.timeout = timeout self.start_time = time() self.background = Surface((300, 200)) self.background.fill(BACKGROUND_COLOR) self.background.set_alpha(127) self.background_x = center(self.width, self.background.get_width()) self.background_y = center(self.height, self.background.get_height()) self.surface = Font(NANUMSQUARE_BOLD_FONT, 36, TEXT_COLOR).render(f'{width}x{height}') self.x = center(self.width, self.surface.get_width()) self.y = center(self.height, self.surface.get_height()) self.root_object_manager.remove_by_class(ResizeAlert) def tick(self): if time() - self.timeout > self.start_time: self.destroy() def render(self, surface: Surface): surface.blit(self.background, (self.background_x, self.background_y)) surface.blit(self.surface, (self.x, self.y)) def destroy(self): self.root_object_manager.remove(self)
def activate(self): xsize = 300 ysize = 70 bkg = Surface((xsize, ysize)) bkg.lock() bkg.fill((128, 128, 128)) for i in range(1, 4): draw.rect(bkg, (i * 32, i * 32, i * 32), (4 - i, 4 - i, xsize + (i - 4) * 2, ysize + (i - 4) * 2), 3) corner = (64, 64, 64) bkg.set_at((0, 0), corner) bkg.set_at((xsize, 0), corner) bkg.set_at((xsize, ysize), corner) bkg.set_at((0, ysize), corner) bkg.unlock() bkg.set_alpha(64) self.bkg = bkg if self.title != None: banner = OutlineTextBanner(self.title, (200, 200, 200), 20) self.title_image = banner.render() self.title_image.set_alpha(96) self.arrow = res.loadImage("wait_arrow.png", colorkey=1)
def __init__(self, evManager, numlines=3, rect=(0, 0, 100, 20), txtcolor=(255, 0, 0), bgcolor=None): Widget.__init__(self, evManager) # When receiving an event containing text, # add or remove that text to the widget's set of text lines to display. # addevents_attrs maps event classes to the text attr of events # that add text to display. self.addevents_attrs = {MdAddPlayerEvt: "pname", MNameChangedEvt: "newname", MMyNameChangedEvent: "newname"} for evtClass in self.addevents_attrs: self._em.reg_cb(evtClass, self.on_addtextevent) # rmevents_attrs maps event classes to the text attributes of events # that remove text to display. self.rmevents_attrs = {MPlayerLeftEvt: "pname", MNameChangedEvt: "oldname", MMyNameChangedEvent: "oldname"} for evtClass in self.rmevents_attrs: self._em.reg_cb(evtClass, self.on_rmtextevent) self.texts = [] # Each text is a player name. # gfx self.font = Font(None, config_get_fontsize()) self.rect = rect self.txtcolor = txtcolor self.bgcolor = bgcolor img = Surface(rect.size) if bgcolor: img.fill(bgcolor) else: img.set_alpha(0, RLEACCEL) # fully transparent self.image = img self.maxnumlines = numlines self.linewidgets = deque(maxlen=numlines) # deque of TextLabelWidgets
class menu(object): def __init__(self, rect, width): self.surface = Surface((width, rect.height)) self.surface.fill((100,100,250)) self.buttonDict = dict() self.addButton(10, 10, 40, 40, "House") self.updateAll() def addButton(self, x, y, width, height, text): self.buttonDict[(x, y, width, height)] = (button.button(width, height, text)) def getButton(self, x, y): for myRect in self.buttonDict.keys(): if Rect(myRect[0], myRect[1], myRect[2], myRect[3]).collidepoint(x, y): return self.buttonDict[(myRect[0], myRect[1], myRect[2], myRect[3])].text return None def updateAll(self): for myRect, button in self.buttonDict.items(): self.surface.blit(button.surface, (myRect[0], myRect[1])) def getSurface(self): return self.surface
def update(self, duration): """ update all the contained linewidgets. Return right away if no text has changed. """ if self.dirty == 0: # no new text has been added return # make the box size = self.rect.size bgcolor = self.bgcolor if bgcolor: # completely opaque bg img = Surface(size) img.fill(self.bgcolor) img = img.convert() else: # more or less transparent img = Surface(size, SRCALPHA) # handles transparency transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) # black img = img.convert_alpha() # blit each line for wid in self.linewidgets: wid.update(duration) img.blit(wid.image, wid.rect) self.image = img self.dirty = 0
def update(self, duration): """ update all the contained linewidgets TODO: check that it works with transparent bg """ if self.dirty == 0: return # make the box size = self.rect.size bgcol = self.bgcolor if bgcol: # only display a bg img if bgcolor specified img = Surface(size) img.fill(bgcol) img = img.convert() else: # more or less transparent img = Surface(size, SRCALPHA) # handles transparency transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) img = img.convert_alpha() # blit each line numelemts = min(len(self.texts), self.maxnumlines) for i in range(numelemts): wid = self.linewidgets[i] wid.set_text(self.texts[-i - 1]) wid.update(duration) img.blit(wid.image, wid.rect) self.image = img
def run(self, surface): surface.set_at((31, 0), (255, 0, 0)) surface.set_at((31, 31), (255, 0, 0)) if len(self.items) > 0: bar_height = round(30 / len(self.items)) else: bar_height = 30 gfxdraw.line(surface, 31, 1, 31, 30, (0, 0, 0)) bar_height_end = (1 + bar_height) * (1 + self.selected_index) if bar_height_end > 30: bar_height_end = 30 gfxdraw.line(surface, 31, 1 + bar_height * self.selected_index, 31, bar_height_end, (0, 255, 0)) pos = 0 for item in self.items: test = Surface((31, 6)) if pos == self.selected_index and not self.buttonPressed: test.fill(Color((100, 0, 0))) elif pos == self.selected_index and self.buttonPressed: test.fill(Color((150, 0, 0))) item.run(test) surface.blit(test, (0, pos * 7)) pos += 1
def convert_to_colorkey_alpha(surf, colorkey=Color('magenta')): """Give the surface a colorkeyed background that will be transparent when drawing. Colorkey alpha, unlike per-pixel alpha, will keep the image's transparent background while using methods such as Surface.set_alpha(). Keyword arguments: surf (Surface): Will be converted to alpha using colorkey. colorkey (Color): The color value for the colorkey. The default is magenta or RGB(255, 0, 255). This should be set to a color that isn't present in the image, otherwise those areas with a matching colour will be drawn transparent as well. """ colorkeyed_surf = Surface(surf.get_size()) colorkeyed_surf.fill(colorkey) colorkeyed_surf.blit(surf, (0, 0)) colorkeyed_surf.set_colorkey(colorkey) colorkeyed_surf.convert() colorkeyed_surf.set_alpha(255) return colorkeyed_surf
def make_counter_btn(x: int, y: int, font: pygame.font.Font, align: str="center", vertical_align: str="middle", min_: int=1, max_: int=5, color: Color=(0, 0, 0)): group = pygame.sprite.Group() counter_sprite = CounterSprite(x, y, font, align, vertical_align, min_, max_, color) group.add(counter_sprite) rect = counter_sprite.base_rect w = h = rect.h w = w // 3 points = [ (0, h//2), (w-1, h*0.8-1), (w-1, h*0.2) ] x, y = rect.topleft left_image = Surface((w, h)).convert_alpha() left_image.fill((255, 255, 255)) left_image.set_colorkey(left_image.get_at((0, 0))) pygame.gfxdraw.filled_polygon(left_image, points, color) # left_image = font.render("<", True, color) btn = RichSprite(x-5, y, align="right", vertical_align="top", image=left_image, press_fnc=counter_sprite._count_down) group.add(btn) x, y = rect.topright right_image = pygame.transform.flip(left_image, True, False) right_image.set_colorkey(right_image.get_at((0, 0))) btn = RichSprite(x+5, y, align="left", vertical_align="top", image=right_image, press_fnc=counter_sprite._count_up) group.add(btn) return group, counter_sprite.get_count
def __init__(self, left: int, top: int, game_player, image_height: int=50): super().__init__() self.game_player = game_player surface = game_player.character.face_image name = game_player.player.name stock = game_player.stock # キャラ画像 image_width = image_height rect = Rect(left, top, image_width, image_height) image = surface_fit_to_rect(surface, rect) self.character_sprite = SimpleSprite(rect, image) self.add(self.character_sprite) # ストックの丸 self.stock = stock self.stock_sprites = [Group() for i in range(stock)] x, y = self.character_sprite.rect.bottomright stock_radius = int(0.05 * image_height) left, top = x, y - stock_radius * 2 for i in range(stock): surface = Surface((stock_radius * 2, stock_radius * 2)).convert_alpha() surface.fill((125, 125, 125)) surface.set_colorkey(surface.get_at((0, 0))) pygame.gfxdraw.filled_circle(surface, stock_radius, stock_radius, stock_radius-1, (255, 255, 255)) stock_sprite = SimpleSprite(Rect(left, top, stock_radius * 2, stock_radius * 2), surface) self.stock_sprites[i].add(stock_sprite) print(self.stock_sprites[i]) left += stock_radius * 2 # プレイヤーネーム font_size = int(0.2 * image_height) font = pygame.font.Font(None, font_size) left, bottom = self.character_sprite.rect.bottomright bottom -= stock_radius * 2 self.player_name_sprite = TextSprite( x=left, y=bottom, align="left", vertical_align="bottom", text=name, font=font, color=(255, 255, 255) ) self.add(self.player_name_sprite) # プレイヤーネームのbg width = self.character_sprite.rect.w + max(stock_radius * 2 * stock, self.player_name_sprite.rect.w) + 10 height = self.character_sprite.rect.h self.base_rect = Rect(*self.character_sprite.rect.topleft, width, height) rect = self.base_rect bg_image = Surface(rect.size).convert_alpha() bg_image.fill((0, 0, 0)) bg_image.set_alpha(225) bg_sprite = SimpleSprite(rect, bg_image) self.bg_group = Group() self.bg_group.add(bg_sprite)
def render(self, text, antialias, color, background=None): """Font.render(text, antialias, color, background=None): return Surface draw text on a new Surface""" color = Color(color) fg = ffi.new("SDL_Color [1]") bg = ffi.new("SDL_Color [1]") fg[0].r = color.r fg[0].g = color.g fg[0].b = color.b if background: try: background = Color(background) bg[0].r = background.r bg[0].g = background.g bg[0].b = background.b except (TypeError, ValueError): # Same error behaviour as pygame bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 else: bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 if text is None or text == "": # Just return a surface of width 1 x font height height = sdl.TTF_FontHeight(self._sdl_font) surf = Surface((1, height)) if background and isinstance(background, Color): surf.fill(background) else: # clear the colorkey surf.set_colorkey(flags=sdl.SDL_SRCCOLORKEY) return surf if not isinstance(text, basestring): raise TypeError("text must be a string or unicode") if "\x00" in text: raise ValueError("A null character was found in the text") if isinstance(text, unicode): text = text.encode("utf-8", "replace") if utf_8_needs_UCS_4(text): raise UnicodeError("A Unicode character above '\\uFFFF' was found;" " not supported") if antialias: if background is None: sdl_surf = sdl.TTF_RenderUTF8_Blended(self._sdl_font, text, fg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Shaded(self._sdl_font, text, fg[0], bg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Solid(self._sdl_font, text, fg[0]) if not sdl_surf: raise SDLError(ffi.string(sdl.TTF_GetError())) surf = Surface._from_sdl_surface(sdl_surf) if not antialias and background is not None: surf.set_colorkey() surf.set_palette([(bg[0].r, bg[0].g, bg[0].b)]) return surf
class Block: # (Sprite): """ A generic patch/agent. Has a Pixel_xy but not necessarily a RowCol. Has a Color. """ agent_text_offset = int(1.5 * gui.PATCH_SIZE) patch_text_offset = -int(1.0 * gui.PATCH_SIZE) def __init__(self, center_pixel: Pixel_xy, color=Color('black')): super().__init__() self.center_pixel: Pixel_xy = center_pixel self.rect = Rect((0, 0), (gui.PATCH_SIZE, gui.PATCH_SIZE)) # noinspection PyTypeChecker sum_pixel: Pixel_xy = center_pixel + Pixel_xy((1, 1)) self.rect.center = sum_pixel self.image = Surface((self.rect.w, self.rect.h)) self.color = self.base_color = color self._label = None self.highlight = None def distance_to_xy(self, xy: Pixel_xy): x_dist = self.center_pixel.x - xy.x y_dist = self.center_pixel.y - xy.y dist = sqrt(x_dist * x_dist + y_dist * y_dist) return dist # Note that the actual drawing (blit and draw_line) takes place in core.gui. def draw(self, shape_name=None): if self.label: self.draw_label() if isinstance(self, Patch) or shape_name in SHAPES: self.rect.center = self.center_pixel # self.rect = Rect(center=self.rect.center) gui.blit(self.image, self.rect) else: gui.draw(self, shape_name=shape_name) def draw_label(self): offset = Block.patch_text_offset if isinstance( self, Patch) else Block.agent_text_offset text_center = Pixel_xy((self.rect.x + offset, self.rect.y + offset)) line_color = Color('white') if isinstance( self, Patch) and self.color == Color('black') else self.color obj_center = self.rect.center label = self.label gui.draw_label(label, text_center, obj_center, line_color) @property def label(self): return self._label if self._label else None @label.setter def label(self, value): self._label = value def set_color(self, color): self.color = color self.image.fill(color)
class FilteredSpList(Clickable): def __init__(self, data, x, y, filters): self.data = data self.filter = filters self.surface = Surface((200, 170)) self.x = x self.y = y self.up_button = Button(86, 0, 28, 21, callback=self.decrease_offset, sprite=SpriteManager().sprites['up_button']) self.down_button = Button(86, 142, 28, 21, callback=self.increase_offset, sprite=SpriteManager().sprites['down_button']) self.offset = 0 self.items = [self.up_button, self.down_button] self.clickables = [self.up_button, self.down_button] self.reset() def update_specialists(self): self.shown_sp_panels = self.sp_panels[self.offset:self.offset + 2] for i in range(len(self.shown_sp_panels)): self.shown_sp_panels[i].y = i * 60 + 21 def increase_offset(self): if self.offset < len(self.data.specialists) - 2: self.offset += 1 self.update_specialists() def decrease_offset(self): if self.offset > 0: self.offset -= 1 self.update_specialists() def draw(self, screen): self.surface.fill(0x000000) for item in self.items: item.draw(self.surface) for item in self.shown_sp_panels: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def is_pressed(self, wx, wy, button): x = wx - self.x y = wy - self.y res = False for item in self.clickables: res = res or item.is_pressed(x, y, button) for item in self.shown_sp_panels: if item.is_pressed(x, y, button): if item.selected: self.chosen.add(item.specialist) else: self.chosen.remove(item.specialist) res = True return res def reset(self): free_specialists = [sp for sp in self.data.specialists if not sp.occupied and sp.s_type in self.filter] self.sp_panels = [SpecialistPanel(0, 0, specialist, True) for specialist in free_specialists] self.update_specialists() self.chosen = set()
def __init__(self, rect, image, player=None, **kwargs): image = Surface((rect.width, rect.height)) image.fill((255, 100, 0)) if Bomb.bombimage == None: Bomb.bombimage = pygame.image.load("./assets/bomb.png").convert_alpha() self.exploding = False super(Bomb, self).__init__(rect, Bomb.bombimage, **kwargs)
def text(self, value): #set the new text self._label.text = value #reconstruction of the frame surface, maybe resized frame = Surface((self._padding_left * 2 + self._label.width, self._padding_top * 2 + self._label.height)) frame.fill(Color("grey")) self._sprite.image = frame #self._sprite = SpriteFactory().fromSurface("widget.button", frame, self._sprite.rect.topleft, layer=self._sprite.layer) self._sprite.dirty = 1
class Lantern(Sprite): def __init__(self, win, player, coords): super().__init__() self.player = player self.sub = 'lantern' self.playerGrappling = False # You can not set it equal to coord or else it will be equal to playerCoords self.coords = [coords[0], coords[1]] self.lightLevel = 2 self.light = Light(win, self, self.lightLevel * 25) #depletion self.maxDeplete = 100 self.deplete = 0 # Mode 0: Tracking Mode | Mode 1: Stay Mode self.mode = 0 self.sprite = Surface((20, 20)) self.sprite.fill((255, 255, 0)) self.surf = win self.trackingCoords = player.coords def checkGrapplingHook(self, playPos): # 20 is the lightbox width and height xCase = playPos[0] > self.coords[0] and playPos[0] < self.coords[0] + 20 yCase = playPos[1] > self.coords[1] and playPos[1] < self.coords[1] + 20 self.playerGrappling = xCase and yCase def moveCoords(self, x, y): self.coords[0] += x self.coords[1] += y def move(self): laternSpeed = 5 # 40 is the distance between the lantern and the player x = self.trackingCoords[0] y = self.trackingCoords[1] - 40 if x - 5 > self.coords[0]: # Lantern moves right self.coords[0] += laternSpeed elif x + 5 < self.coords[0]: # Lantern moves left self.coords[0] -= laternSpeed if y - 5 > self.coords[1]: # Lantern moves Down self.coords[1] += laternSpeed elif y + 5 < self.coords[1]: # Lantern moves Up self.coords[1] -= laternSpeed if self.mode == 1: if self.deplete // 10 < self.maxDeplete: self.deplete += 1 def set_mode(self, mode): self.mode = mode def render(self): self.surf.blit(self.sprite, self.coords) self.light.update() def renderToLight(self, light): light.blit(self.sprite, (90, 90))
class World(object): def __init__(self, width, height): self.width = 300 self.height = 300 self.grid_size = 20 self.pixel_size = Rect(0, 0, width, height) self.full_grid = Rect(0, 0, self.width, self.height) self.view_grid = Rect(10, 10, 0, 0) self.prev_view_grid = None self.zoom(0) self.ground = [[0 for col in range(self.width)] for row in range(self.height)] for y in range(self.height): for x in range(self.width): self.ground[y][x] = Assets.colors_db.any('dirt') self.surface = Surface((width, height), HWSURFACE, 32) def draw(self, screen): rect = self.view_grid if self.prev_view_grid != rect: self.prev_view_grid = Rect(rect) x1 = rect.left y1 = rect.top x2 = min(self.width, rect.left + rect.width) y2 = min(self.height, rect.top + rect.height) r = Rect(0, 0, self.grid_size, self.grid_size) for row in self.ground[y1:y2 - 1]: for col in row[x1:x2 - 1]: self.surface.fill(col, r) r.left += self.grid_size r.left = 0 r.top += self.grid_size screen.blit(self.surface, self.pixel_size) def view_move(self, move): self.view_grid.left += move.x self.view_grid.top += move.y self.view_grid.clamp_ip(self.full_grid) def zoom_in(self): self.zoom(+1) def zoom_out(self): self.zoom(-1) def zoom(self, dz): if 50 >= self.grid_size + dz >= 5: self.grid_size = self.grid_size + dz self.view_grid.width = int(math.ceil(self.pixel_size.width / float(self.grid_size))) + 1 self.view_grid.height = int(math.ceil(self.pixel_size.height / float(self.grid_size))) + 1 self.view_grid.clamp_ip(self.full_grid) self.prev_view_grid = None
def make_color_image(size, color): # PYGaME CHOKE POINT s = Surface(size).convert() if color: s.fill(color) else: s.set_colorkey(s.get_at((0, 0))) return s
class Obstacle(pygame.sprite.Sprite): def __init__(self, rect): super().__init__() self.image = Surface((rect[2], rect[3])) self.image.fill((100, 100, 100)) self.rect = Rect(*rect) draw.rect(self.image, (0, 0, 0), (0, 0, rect[2], rect[3]), 1) def update(self): pass
def finalise(self, target_surface: Surface, target_area: pygame.Rect, row_chunk_origin: int, row_chunk_height: int, row_bg_height: int, x_scroll_offset: int = 0, letter_end: Optional[int] = None): surface = Surface(self.size, depth=32, flags=pygame.SRCALPHA) surface.fill(self.colour) target_surface.blit(surface, self, area=target_area)
class EmitterHandler(object): TIME_TILL_EMITTER_REMOVAL = 10.0 # Seconds def __init__(self, zombie_handler: ZombieHandler): self.active_emitters = PriorityQueue() self.new_emitters = PriorityQueue() self.running = True self.current_emitters = set() self.zombie_handler = zombie_handler self.lock = Lock() self.emitter_surface = Surface( (Constant.SCREEN_WIDTH, Constant.SCREEN_HEIGHT), pygame.SRCALPHA) self.thread = Thread(target=self.handler_thread) self.thread.start() def add_emitter(self, emitter: SoundEmitter): self.lock.acquire() self.current_emitters.add(emitter) self.lock.release() def handler_thread(self): while self.running: zombies = self.zombie_handler.get_zombies() self.lock.acquire() for emitter in self.current_emitters: for zombie in zombies: zombie.hear(emitter) self.lock.release() time.sleep(0.1) def step(self): self.lock.acquire() to_delete = set() for emitter in self.current_emitters: delete_emitter = emitter.step() if delete_emitter: to_delete.add(emitter) self.current_emitters -= to_delete self.lock.release() def draw(self, screen, camera): self.lock.acquire() for emitter in self.current_emitters: self.emitter_surface.fill((0, 0, 0, 0)) emitter.draw(self.emitter_surface, camera) screen.blit(self.emitter_surface, (0, 0)) self.lock.release() def quit_thread(self): # Stop thread on delete self.running = False self.thread.join()
def loadImage(self, colour): result = Surface(self.baseImg.get_size(), pygame.SRCALPHA) result.fill((0, 0, 0, 0)) result.blit(self.baseImg, (0, 0)) temp = Surface(self.baseImg.get_size(), pygame.SRCALPHA) temp.fill(colour + (255, )) temp.blit(self.teamImg, (0, 0), special_flags=pygame.BLEND_RGBA_MULT) result.blit(temp, (0, 0)) self.cached[colour] = result
def draw_hud(self) -> None: """ Draws all hud elements """ # clear clear = Surface((self.window_width, self.window_height - self.window_playable_height)) clear.fill((0, 0, 0)) self.window.blit(clear, (0, self.window_playable_height)) self.draw_names() self.draw_lifes() self.draw_effects()
def render(self): self.check() if self.disabled: return pos = self.rect.center t = self.mod["eyeType"] color0 = (255,255,255) color1 = (0,0,0) radius = (self.mod["eyeSkill"] + 2) * 3 color = skinColor(self.mod) # we have to determine how big the eye will be before drawing size = (radius * 2, radius * 2) rect = Rect((0,0), size) image = Surface(size) image.fill(self.colorkey) image.set_colorkey(self.colorkey) # locking the surface makes multiple drawing operations quicker image.lock() # draw the border of the eye if radius < 10: steps = 16 else: steps = 8 for t in range(0,360,steps): t = radians(t) new_color = Color(color.r, color.g, color.b) h, s, v, a = new_color.hsva v = int(sin(t) * 50) + 50 if v < 0: v = 0 - v new_color.hsva = (h, s, v, a) x = int(rect.centerx + cos(t) * (radius - 4)) y = int(rect.centery + sin(t) * (radius - 4)) draw.circle(image, new_color, (x, y), 3) # draw the white and pupil draw.circle(image, color0, rect.center, radius - 3) draw.circle(image, color1, rect.center, (radius - 3) / 3) image.unlock() rect.center = pos self.rect = rect self.image = image
def __init__(self, x, y, padding_left, padding_top, text="button", text_size=16, layer=900): super(Button, self).__init__() self._label = Label(0, 0, text_size, text, layer=layer + 1) self._label.topleft = (x + padding_left, y + padding_top) self._padding_left = padding_left self._padding_top = padding_top frame = Surface((padding_left * 2 + self._label.width, padding_top * 2 + self._label.height)) frame.fill(Color("grey")) self._sprite = SpriteFactory().fromSurface("widget.button", frame, (x, y), layer=layer)
def _renderh1(self): self.text = self.h1Font.render('RUNNY CHRISTMAS', True, scoreColor) self.rect = self.text.get_rect() self.rect.center = CENTER_POSITION alpha_surf = Surface(self.text.get_size(), SRCALPHA) # Don't modify the original text surf. self.textWithAlpha = self.text.copy() # Fill alpha_surf with this color to set its alpha value. alpha_surf.fill((255, 255, 255, self.fadeInValue)) # To make the text surface transparent, blit the transparent # alpha_surf onto it with the BLEND_RGBA_MULT flag. self.textWithAlpha.blit(alpha_surf, (0, 0), special_flags=BLEND_RGBA_MULT)
def create_blank_surface(width, height): """Return a completely transparent Surface of the given dimensions. Args: width (int): The width of the Surface in pixels. height (int): The height of the Surface in pixels. """ blank_surf = Surface((width, height)) blank_surf.fill(Color('magenta')) blank_surf.set_colorkey(Color('magenta')) blank_surf.convert() blank_surf.set_alpha(255) return blank_surf
def prepare_passage(text, width, size="normal", colour=(0,0,0)): sections = text.split("\n") paras = [prepare_paragraph(t,width,size=size,colour=colour) for t in sections] fullwidth = max(p.get_width() for p in paras) fullheight = sum(p.get_height() for p in paras) passage = Surface((fullwidth,fullheight),pygame.SRCALPHA) passage.fill((255,255,255,0)) y = 0 for p in paras: passage.blit(p,(0,y)) y += p.get_height() return passage
def padimage(self, image): """ Do a little processing of the input image to make it purdyer. Pad the image with transparent pixels so the edges get antialised when rotated and scaled. Looks real nice. """ new = Surface(image.get_rect().inflate(2, 2).size, pygame.SRCALPHA) color = image.get_at((0,0)) color[3] = 0 new.fill(color) new.blit(image, (1,1)) return new
class Rocket(Sprite): def __init__(self, dna=None): super(Rocket, self).__init__() self.pos = [300, 550] self.vel = [0, 0] self.acc = [0, 0] self.dna = dna if dna is not None else DNA() self.fitness = 0 self.image = Surface((8, 8)) self.image.fill(THECOLORS['white']) self.rect = self.image.get_rect() def get_force(self, force, timefactor): factor = 0.1 * timefactor self.acc[0] += force[0] * factor self.acc[1] += force[1] * factor def is_alive(self, target_pos, blocks): return self.rect.left > 0 and self.rect.right < 600 \ and self.rect.top > 0 and self.rect.bottom < 600 \ and dist(self.pos, target_pos) > 16 \ and self.rect.collidelist(blocks) == -1 def calc_fitness(self, target_pos, blocks): self.fitness = my_map(dist(self.rect.center, target_pos), 0, 600, 600, 0) if dist(self.pos, target_pos) < 16: self.fitness *= 10 if self.rect.collidelist(blocks) != -1: self.fitness /= 10 # if self.rect.left > 0 and self.rect.right < 600 \ # and self.rect.top > 0 and self.rect.bottom < 600: # self.fitness /= 5 return self.fitness def update(self, counter, target_pos, blocks, timefactor): self.vel[0] += self.acc[0] * timefactor self.vel[1] += self.acc[1] * timefactor if self.is_alive(target_pos, blocks): self.pos[0] += self.vel[0] * timefactor self.pos[1] += self.vel[1] * timefactor self.vel[0] *= 1 self.vel[1] *= 1 self.get_force(self.dna.genes[counter], timefactor) self.rect.center = self.pos
def create_wind_markers(match, parent_rect, group): current_path = os.path.dirname(os.path.realpath(__file__)) font_path = os.path.join( current_path, "..", "..", "resources", "fonts", "SourceSans3-Semibold.ttf" ) font = Font(font_path, 40) MARKER_SIZE = (40, 40) MARKER_SIZE_HALF = (MARKER_SIZE[0] / 2, MARKER_SIZE[1] / 2) MARKER_OFFSET = 40 parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - MARKER_SIZE_HALF[1] - MARKER_OFFSET), (parent_half_width - MARKER_SIZE_HALF[0] - MARKER_OFFSET, 0), (0, -parent_half_height + MARKER_SIZE_HALF[1] + MARKER_OFFSET), (-parent_half_width + MARKER_SIZE_HALF[0] + MARKER_OFFSET, 0), ] WIND_ORDERS = [ ["E", "S", "W", "N"], ["N", "E", "S", "W"], ["W", "N", "E", "S"], ["S", "W", "N", "E"], ] current_east_seat = match.current_board.current_dealer wind_order = WIND_ORDERS[current_east_seat] for i in range(4): wind = wind_order[i] background_surface = Surface(MARKER_SIZE) if i == current_east_seat: background_color = (255, 0, 0) else: background_color = (100, 100, 100) background_surface.fill(background_color) font_surface = font.render(wind, True, (255, 255, 255)) font_width, font_height = font.size(wind) background_surface.blit( font_surface, ((MARKER_SIZE[0] - font_width) / 2, (MARKER_SIZE[1] - font_height) / 2), ) sprite = Sprite() sprite.rect = background_surface.get_rect() sprite.image = background_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[i][0] sprite.rect.y += SEAT_OFFSETS[i][1] sprite.layer = 2 group.add(sprite)
class ControlButton: button_id = 0 def __init__(self, title, name, x, y, width, height, button_color, font_color, func, background_image=None): self.title = title self.name = name self.id = ControlButton.button_id ControlButton.button_id += 1 self.x = x self.y = y self.abs_x = x self.abs_y = y self.width = width self.height = height self.func = func self.button_color = button_color self.font_color = font_color self.__selected_color = color.white self.background_image = background_image if background_image: img_surf = pygame.image.load(background_image) self.surface = pygame.transform.scale(img_surf, (width, height)) else: self.surface = Surface((self.width, self.height)) self.draw() def selected(self): self.__selected_color, self.font_color = self.font_color, self.__selected_color def draw(self): if not self.background_image: text = TextObject(self.title, Constants.font, Constants.control_button_text_size, self.font_color) self.surface.fill(self.button_color) self.surface.blit(text.Text, (10, 10)) def pushed(self): return self.func()
class Block(Sprite): """ A generic patch/agent. Has a Pixel_xy but not necessarily a RowCol. Has a Color. """ agent_text_offset = int(1.5 * gui.PATCH_SIZE) patch_text_offset = -int(1.0 * gui.PATCH_SIZE) def __init__(self, center_pixel: Pixel_xy, color=Color('black')): super().__init__() self.center_pixel = center_pixel self.rect = Rect((0, 0), (gui.PATCH_SIZE, gui.PATCH_SIZE)) # noinspection PyTypeChecker sum_pixel: Pixel_xy = center_pixel + Pixel_xy((1, 1)) self.rect.center = sum_pixel self.image = Surface((self.rect.w, self.rect.h)) self.color = self.base_color = color self.label = None def distance_to_xy(self, xy: Pixel_xy): x_dist = self.center_pixel.x - xy.x y_dist = self.center_pixel.y - xy.y dist = sqrt(x_dist * x_dist + y_dist * y_dist) return dist # Note that the actual drawing (blit and draw_line) takes place in core.gui. def draw(self): if self.label: self.draw_label() gui.blit(self.image, self.rect) def draw_label(self): text = gui.FONT.render(self.label, True, Color('black'), Color('white')) offset = Block.patch_text_offset if isinstance( self, Patch) else Block.agent_text_offset text_center = Pixel_xy((self.rect.x + offset, self.rect.y + offset)) # gui.SCREEN.blit(text, text_center) gui.blit(text, text_center) line_color = Color('white') if isinstance( self, Patch) and self.color == Color('black') else self.color # self.draw_line(line_color=line_color, start_pixel=self.rect.center, end_pixel=text_center) gui.draw_line(start_pixel=self.rect.center, end_pixel=text_center, line_color=line_color) def set_color(self, color): self.color = color self.image.fill(color)
def handle(self, requested, attrs): locid = attrs['id'] x,y = (attrs['x'], attrs['y']) size = (attrs['size']) locw , loch = (100,100) surface = Surface((size, size)) if x < 0 or x >= locw or y < 0 or y >= loch: surface.fill(THECOLORS['black']) else: surface.fill(THECOLORS['white']) return surface
def draw(self, pressed): from pygame.surface import Surface from pygame.draw import rect from pygame.display import flip self.surface.fill(self.surface_color) if pressed: self.current_position += pressed self.current_position %= self.number_buttons menu_surface = Surface((self.menu_width, self.menu_height)) menu_surface.fill(self.surface_color) rect(menu_surface, self.selection_color, self.info_list[self.current_position].point_rect) for i in range(self.number_buttons): menu_surface.blit(self.info_list[i].text_surface, self.info_list[i].text_rect) self.surface.blit(menu_surface, self.shift) flip()
def getEndGameSplash(winnerName=None, winnerColor=None): """If winningName and winnerColor are both None, display a tie game screen. """ screen = Display.get_surface() splashGroup = SpriteGroup() if winnerName != None and winnerColor != None: # Create winning bomberman image fatalityRect = Rect((0, 0, 500, 500)) fatalityRect.centerx = screen.get_rect().centerx fatalityRect.centery = screen.get_rect().centery fatalityAnimation = WorldlessWidget(Surface((500, 500)), fatalityRect) fatalImage = pygame.image.load("images/fatality.png").convert() fatalImage.set_colorkey(LAVENDER) bmanColor = Surface((fatalImage.get_width(), fatalImage.get_height())) bmanColor.fill(winnerColor) bmanColor.blit(fatalImage, bmanColor.get_rect()) winnerFrames = createFrames(bmanColor) fatalityAnimation.startAnimation(winnerFrames, 0, 12) splashGroup.add(fatalityAnimation) # Create text for winning player winnerText = TextBar(winnerName + " Wins!", (0, 0, 200, 50), 50) imgWidth = winnerText.image.get_width() winnerText.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(winnerText) else: tieText = TextBar("TIE GAME!", (0, 20, 250, 50), 35) imgWidth = tieText.image.get_width() tieText.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(tieText) escMessage = TextBar("Press Escape to exit.", (0, 60, 250, 50), 25) imgWidth = escMessage.image.get_width() escMessage.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(escMessage) pressKeyText = TextBar( "Press a key or button when ready. Next round will start when everyone is ready.", (0, 90, 250, 50), 25 ) imgWidth = pressKeyText.image.get_width() pressKeyText.rect.left = (screen.get_size()[X] - imgWidth) / 2 splashGroup.add(pressKeyText) return splashGroup
class ExpeditionsPanel(Clickable): def __init__(self, data, x, y): self.data = data self.surface = Surface((200, 420)) self.x = x self.y = y self.up_button = Button(86, 0, 28, 21, callback=self.decrease_offset, sprite=SpriteManager().sprites['up_button']) self.down_button = Button(86, 381, 28, 21, callback=self.increase_offset, sprite=SpriteManager().sprites['down_button']) self.offset = 0 self.items = [self.up_button, self.down_button] self.clickables = [self.up_button, self.down_button] self.update_expeditions() self.visible = True def update_expeditions(self): window = self.data.expeditions[self.offset:self.offset + 6] self.items = [self.up_button, self.down_button] for i in range(len(window)): self.items.append(ExpeditionWidget(0, i * 80 + 21, window[i])) def increase_offset(self): if self.offset < len(self.data.specialists) - 6: self.offset += 1 self.update_expeditions() def decrease_offset(self): if self.offset > 0: self.offset -= 1 self.update_expeditions() def draw(self, screen): if not self.visible: return self.surface.fill(0x000000) for item in self.items: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def is_pressed(self, wx, wy, button): if not self.visible: return False x = wx - self.x y = wy - self.y for item in self.clickables: item.is_pressed(x, y)
def __init__(self, color="black"): surface = Surface(Window().size) surface = surface.convert() try: color = Color(color) except: color = Color("black") surface.fill(color) self._sprite = SpriteFactory().fromSurface("main.fx.overlay", surface, layer=10000) self._sprite.pinned = True self._sprite.dirty = 1 self._sprite.visible = False self._sprite.image.set_alpha(0) self._fading = 0 # 0: idle | 1: fade in | -1: fade out
def update(self, duration): """ reblit the entries on my rect """ if self.dirty == 0: return # make the transparent box size = self.rect.size img = Surface(size, SRCALPHA) transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) img = img.convert_alpha() # TODO: alpha or color key? # blit each entry for entry in self.entries: entry.update(duration) img.blit(entry.image, entry.rect) self.image = img
def on_board_built(self, ev): """ Build the board background. """ width, height = ev.width, ev.height board = ev.board # to obtain cells from coords win_height = self.window.get_height() bg = Surface((win_height, win_height)) bg = bg.convert() bg.fill(bg_color) for left in range(width): for top in range(height): cell = board.get_cell(left, top) bg.blit(cell.image, cell.rect) # blit the board bg onto the window's bg self.window_bg.blit(bg, (0, 0)) self._em.subscribe(BoardUpdatedEvent, self.on_board_update)
def __init__(self, board, coords, pathdir, iswalkable, isentr=False, isjunc=False, iswait=False, iskill=False, istrap=False): """ coords are my coordinates. pathdir is the direction of the next cell in the path (e.g. DIR_UP). """ self.coords = left, top = coords self.board = board self.pathdir = pathdir # non-null for traps self.nextcell = None # will remain None for the exit self.prevcell = None # will remain None for the entrance self.loadcell = None # will remain None for non-loading cells self.fruit = None # will be set by the board or cells self.iswalkable = iswalkable # traps are walkable self.istrap = istrap self.load_dir = None #gfx cspr_left = left * cell_size cspr_top = top * cell_size self.rect = Rect(cspr_left, cspr_top, cell_size, cell_size) img = Surface((cell_size, cell_size)) if istrap: img.fill(trap_color) elif self.iswalkable: # but not a trap img.fill(path_color) else: img.fill(bg_color) self.image = img
class Dialog(object): def __init__(self, x, y, w, h): self.items = [] self.clickables = [] self.surface = Surface((w, h)) self.x = x self.y = y self.w = w self.h = h self.enter_btn = None self.esc_btn = None def draw(self, screen): self.surface.fill(0xaaaaaa) for item in self.items: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def add(self, item): self.items.append(item) if isinstance(item, Clickable): self.clickables.append(item) def click(self, wx, wy, button): x = wx - self.x y = wy - self.y if x < 0 or y < 0: return res = False for item in self.clickables: res = res or item.is_pressed(x, y, button) return res def add_ok(self, button): self.enter_btn = button self.add(button) def add_cancel(self, button): self.esc_btn = button self.add(button)
def __init__(self, em, ev): """ em is the mode's event manager, ev is an event containing data from the previous mode. """ self._em = em window = pygame.display.set_mode(resolution) self.window = window pygame.display.set_caption('Smoothie Factory - %s' % self.pagename) # blit the bg screen: all black bg = Surface(window.get_size()) bg.fill((0, 0, 0)) bg = bg.convert() self.window_bg = bg self.window.blit(bg, (0, 0)) # build GUI self.gui = self._build_gui() # return a sprite group em.subscribe(VTickEvent, self.on_tick)