def __init__(self, surface: pg.Surface): super().__init__(surface) self.field = Field( # "800000503501007000700308210680073000009005000300004805970500680063789000150040007" # "000000000904607000076804100309701080008000300050308702007502610000403208000000000" # "000001030231090000065003100678924300103050006000136700009360570006019843300000000" # "016007803090800000870001260048000300650009082039000650060900020080002936924600510" # "100000569492056108056109240009640801064010000218035604040500016905061402621000005" "100400006046091080005020000000500109090000050402009000000010900080930560500008004" ) self.font = pg.font.SysFont("Vera", 42) self.blocks = [] self.cells = [] self.debugs = [] self._idx = 0 total_size = surface.get_rect() board_size = min(total_size.width * 2 // 3, total_size.height) board_top_space = total_size.height - board_size self._board = pg.Rect(0, board_top_space, board_size, board_size) print(total_size) self.board_surface = surface.subsurface(self._board.inflate(-20, -20)) block_size = (board_size - 20) // 3 cell_size = (block_size - 6) // 3 for x in range(3): for y in range(3): if y == 0: for i in range(3): cellsurface = surface.subsurface( pg.Rect( block_size * x + cell_size * i + 13, block_size * y + board_top_space - cell_size // 2 + 10, cell_size, cell_size // 2, )) self.cells.append( Text(text=f"x: {3*x+i+1}", surface=cellsurface)) for i in range(3): rect = pg.Rect( board_size - 10, board_top_space + 13 + cell_size * i + block_size * x, cell_size // 2, cell_size, ) print(rect) cellsurface = surface.subsurface(rect) self.cells.append( Text(text=f"{3*x+i+1}", surface=cellsurface)) blockrect = pg.Rect(block_size * x, block_size * y, block_size, block_size) blocksurface = self.board_surface.subsurface(blockrect) self.blocks.append(Block(blocksurface, x, y, self.field)) self.debugs.append( Text( text=f"x: , y: ", surface=surface.subsurface(pg.Rect(0, 0, 200, 50)), ))
def draw_Player(surface: pygame.Surface, state: GameState, player_idx: int): CARD_SPACING = 5 CARD_W = int((surface.get_width() + CARD_SPACING) / 11) CARD_H = int(surface.get_height() / 3) FORE_C = Color('RED') BACK_C = Color('BLUE') LABEL_SIZE = 24 y = 10 App.draw_centered_text(surface, surface.get_width() / 2, y, f'Player {player_idx + 1}', FORE_C, LABEL_SIZE) y += 20 App.draw_centered_text(surface, surface.get_width() / 2, y, 'Hand', FORE_C, LABEL_SIZE) counts = count_card_types(state.hands[player_idx]) counts = {card: count for card, count in counts.items() if count > 0} y += 10 for k, card in enumerate(counts): count = counts[card] x = k * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, count) y += CARD_H + 10 App.draw_centered_text(surface, surface.get_width() / 2, y, 'Played', FORE_C, LABEL_SIZE) played_cards = list(state.played_cards[player_idx]) wasabi_combos = pair_wasabi(played_cards) for card in wasabi_combos: played_cards.remove(card) played_cards.remove(SushiCardType.WASABI) counts = count_card_types(played_cards) counts = {card: count for card, count in counts.items() if count > 0} y += 10 for k, card in enumerate(counts): count = counts[card] x = k * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, count) for k, card in enumerate(wasabi_combos): x = (k + len(counts)) * (CARD_W + CARD_SPACING) App.draw_card(surface.subsurface(Rect(x, y, CARD_W, CARD_H)), card, FORE_C, BACK_C, 1, True) y += CARD_H + 10 pudding = state.puddings[player_idx] score = state.scores[player_idx] App.draw_centered_text(surface, surface.get_width() / 2, y, f'Pudding: {pudding} Score: {score}', FORE_C, LABEL_SIZE)
class Block(sprite.Sprite): """ Данный класс описывает блоки """ def __init__(self, id, x, y, type, DEMAGE): sprite.Sprite.__init__(self) self.image = Surface((PLATFORM_WIDTH, PLATFORM_HEIGHT)) # изображение self.id = id # идентификатор self.type = type # тип платформы self.demage = DEMAGE if type == "-": # разрушаемая self.image = image.load("blocks/platform.png") elif type == "*": # НЕразрушаемая self.image = image.load("blocks/beton.png") else: # все остальные self.image.fill(Color(PLATFORM_COLOR)) self.rect = Rect(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT) # размеры блока def die(self, shutdirection): # попадание в блок if self.type == "-": # если он разрушаемый x = self.rect.left y = self.rect.top w = self.rect.width h = self.rect.height # уменьшаем размер блока с соответсвующего направления if shutdirection == "left": self.image = self.image.subsurface((0, 0, w-self.demage, h)) self.rect = Rect(x, y, w-self.demage, h) elif shutdirection == "right": self.image = self.image.subsurface((self.demage, 0, w-self.demage, h)) self.rect = Rect(x+self.demage, y, w-self.demage, h) if shutdirection == "up": self.image = self.image.subsurface((0, 0, w, h-self.demage)) self.rect = Rect(x, y, w, h-self.demage) if shutdirection == "down": self.image = self.image.subsurface((0, self.demage, w, h-self.demage)) self.rect = Rect(x, y+self.demage, w, h-self.demage) # если блок уничтожен совсем, удаляем его из всех групп if (self.rect.width == 0) or (self.rect.height == 0): self.rect.width = self.rect.height = 0 self.kill()
def draw_plot(surf: pygame.Surface, rect: pygame.Rect, xs: list, ys: list, title: str): """ Draw a plot with data xs and ys on surface surf in rectangle rect :param surf: Surface where the plot will be drawn :param rect: rect of the surface corresponding to position and dimension of the plot :param xs: x coordinate of ever point of dataset :param ys: y coordinate of ever point of dataset :param title: String to be shown on top of plot """ plot_surf = surf.subsurface(rect) w, h = rect.size x0, y0 = int(w * margin_ratio), int(h * (1 - margin_ratio)) x1, y1 = int(w * (1 - margin_ratio)), int(h * margin_ratio) minx, maxx, miny, maxy = min(xs), max(xs), min(ys), max(ys) lx, ly = maxx - minx, maxy - miny _draw_axis(plot_surf, (x0, y0), (x1, y1)) _draw_title(plot_surf, rect, title) if lx == 0. or ly == 0.: return _draw_x_ticks(plot_surf, (x0, y0), (x1, y0), (minx, maxx)) _draw_y_ticks(plot_surf, (x0, y0), (x0, y1), (miny, maxy)) _draw_points(plot_surf, xs, ys, (x0, y0), (x1, y1), minx, miny, lx, ly)
def draw(self, surface: pg.Surface): if self.page_index >= len(self.pages): return width, _ = surface.get_size() rect = pg.Rect(0, 450, width, 150) sub = surface.subsurface(rect) self.pages[self.page_index].draw(sub)
def render(self, surface: pg.Surface): sensorEdges = [(self.x + self.size * cos(self.rotation), self.y - self.size * sin(self.rotation)), (self.x + self.size * cos(self.rotation) + self.proximitySensorLen * sin(self.rotation), self.y - self.size * sin(self.rotation) + self.proximitySensorLen * cos(self.rotation)), (self.x - self.size * cos(self.rotation) + self.proximitySensorLen * sin(self.rotation), self.y + self.size * sin(self.rotation) + self.proximitySensorLen * cos(self.rotation)), (self.x - self.size * cos(self.rotation), self.y + self.size * sin(self.rotation))] self.sensorRect = pg.draw.lines(surface, PINK, True, sensorEdges) self.proximitySensor = pg.mask.from_threshold(surface, PINK, ONE) self.surface = surface.subsurface( pg.Rect(self.x - self.size, self.y - self.size, 2 * self.size, 2 * self.size)) pg.draw.circle(self.surface, GREEN, (self.size, self.size), self.size) # print(sensorEdges, self.sensorRect.topleft) self.mask = pg.mask.from_threshold(self.surface, GREEN, (1, 1, 1, 255))
def draw_field(self, players): canvas = Surface((self.raw_w, self.raw_h)) for row in range(len(FIELD)): for col in range(len(FIELD[0])): scr_x = col * TILE_scale scr_y = row * TILE_scale subsurf = canvas.subsurface( (scr_x, scr_y, TILE_scale, TILE_scale)) subsurf.fill(TILE_CLRs[FIELD[row][col]]) for i in range(4): player = players[i] # type: Player player_color = PLAYER_CLRs[i] if player: pos_x = (player.position.x + 0.0) * TILE_scale pos_y = (player.position.y - 1.0) * TILE_scale draw.rect(canvas, player_color, (pos_x, pos_y, TILE_scale, TILE_scale * 2), 0) aim_origin = player.get_shoot_origin() * TILE_scale draw.line(canvas, CLR_red, aim_origin, aim_origin + player.look_direction * TILE_scale * 30) for e in player.events: if e is "jump": self.add_effect( (pos_x + 0.5 * TILE_scale, pos_y + 2 * TILE_scale), player_color) player.events.remove(e) else: pass # because those events are triggered by input.poll() # they get reset instantly afterwards # when the commands are passed as events to player update this reset will be moved to player update player.events = [] return canvas
def render_display(screen: pygame.Surface, tree: Optional[TMTree], selected_node: Optional[TMTree], hover_node: Optional[TMTree]) -> None: """Render a treemap and text display to the given screen. Use the constants TREEMAP_HEIGHT and FONT_HEIGHT to divide the screen vertically into the treemap and text comments. """ # First, clear the screen pygame.draw.rect(screen, pygame.color.THECOLORS['black'], (0, 0, WIDTH, HEIGHT)) subscreen = screen.subsurface((0, 0, WIDTH, TREEMAP_HEIGHT)) # TODO: Uncomment this afer you have completed Task 2 for rect, colour in tree.get_rectangles(): # Note that the arguments are in the opposite order pygame.draw.rect(subscreen, colour, rect) # add the hover rectangle if selected_node is not None: pygame.draw.rect(subscreen, (255, 255, 255), selected_node.rect, 5) if hover_node is not None: pygame.draw.rect(subscreen, (255, 255, 255), hover_node.rect, 2) # TODO: Uncomment this after you have completed Task 2 _render_text(screen, _get_display_text(selected_node)) # This must be called *after* all other pygame functions have run. pygame.display.flip()
def draw_plot(surf: pygame.Surface, rect: pygame.Rect, xs: list, ys: list, title: str): """ Draw a plot with data xs and ys on surface surf in rectangle rect :param surf: :param rect: :param xs: :param ys: :param title: :return: """ plot_surf = surf.subsurface(rect) w, h = rect.size x0, y0 = int(w * margin_ratio), int(h * (1 - margin_ratio)) x1, y1 = int(w * (1 - margin_ratio)), int(h * margin_ratio) minx, maxx, miny, maxy = min(xs), max(xs), min(ys), max(ys) lx, ly = maxx - minx, maxy - miny _draw_axis(plot_surf, (x0, y0), (x1, y1)) _draw_title(plot_surf, rect, title) if lx == 0. or ly == 0.: return _draw_x_ticks(plot_surf, (x0, y0), (x1, y0), (minx, maxx)) _draw_y_ticks(plot_surf, (x0, y0), (x0, y1), (miny, maxy)) _draw_points(plot_surf, xs, ys, (x0, y0), (x1, y1), minx, miny, lx, ly)
def draw(self, surface: pygame.Surface) -> List[MouseRegion]: surface.fill(self.BG_COLOR) if len(self.frames) == 0: return [] if (len(self.frames) != self.__number_of_elements or time.time() - self.__last_layout_evaluation > self.REEVALUATION_INTERVAL_SECONDS or surface.get_size() != self.__surface_size): self._calculate_layout(surface) target_size = surface.get_size() element_size = (int(target_size[0] / self.__layout[0]), int(target_size[1] / self.__layout[1])) regions = [] for i, frame in enumerate(self.frames): i_x = i % self.__layout[0] i_y = int(i / self.__layout[0]) frame_surface = _opencv_to_pygame(frame) target_rect = frame_surface.get_rect().fit(pygame.Rect(i_x * element_size[0], i_y * element_size[1], *element_size)) target_surface = surface.subsurface(target_rect) pygame.transform.scale(frame_surface, target_rect.size, target_surface) self.after_draw_frame(i, frame, surface, target_surface) regions.append(MouseRegion(frame.source, target_rect, (frame.width, frame.height))) self.after_draw(surface) return regions
def __init__( self, screen: "in_game.screen.screen.InGameScreen", surface: Surface, fonts: Dict[str, Font], sounds: Dict[str, Sound], images: Dict[str, Surface], player: "in_game.play_area.sprites.player.Player") -> None: self.__screen = screen self.__surface = surface self.__fonts = fonts self.__sounds = sounds self.__images = images self.__keyboard = Keyboard( screen, surface, player, self.__fonts, WHITE) for event_handler in self.__keyboard.get_event_handlers(): screen.add_event_handler(event_handler) block_rect = surface.get_rect( topleft=(PlayArea.LEFT_MARGIN, PlayArea.TOP_MARGIN), width=surface.get_width() - PlayArea.LEFT_MARGIN, height=surface.get_height() - PlayArea.TOP_MARGIN) block_surface = surface.subsurface(block_rect) self.__block_area = BlockArea(self, block_surface, fonts, images, sounds, player) player_string = "PLAYER {0:d}: ".format(player.get_number()) size = self.__fonts["big"].size(player_string) initial_pos = (self.__surface.get_width() // 2 - size[0], 5) self.__player_text = pygame.sprite.GroupSingle( TextSprite(initial_pos, player_string, self.__fonts["big"], GREEN) ) initial_pos = (self.__surface.get_width() // 2, 5) score = Score(initial_pos, fonts["big"], sounds["score"]) self.__score = pygame.sprite.GroupSingle(score) self.__debug_info = pygame.sprite.GroupSingle(DebugInfo(self, fonts)) self.__scroll_velocity = 8 self.__line_numbers = pygame.sprite.OrderedUpdates() self.__active_power_up_jump = GroupSingleAnyRect() self.__active_power_up_shield = GroupSingleAnyRect() self.__game_over_score = pygame.sprite.GroupSingle() # (735 - 35) / 32 = 22 self.__max_line_numbers = round((surface.get_height() - PlayArea.TOP_MARGIN) / Block.BLOCK_HEIGHT) if player.get_joystick() is not None: screen.add_event_handler(PlayerJoystickEventHandler(screen, player.get_joystick(), player)) event_handler = PlayerKeyboardEventHandler( screen, PlayArea.key_mappings[player.get_number() - 1], player) screen.add_event_handler(event_handler) self.__game_over_bg = None
def cut_sheet(sheet: pygame.Surface, columns: int, rows: int) -> List[pygame.Surface]: """Разделяет переданное изображение на кадры.""" frames = [] w, h = sheet.get_width() // columns, sheet.get_height() // rows for j in range(rows): for i in range(columns): frames.append(sheet.subsurface(pygame.Rect(w * i, h * j, w, h))) return frames
def load(self, texture: pygame.Surface, row_id=0, frame_size=vec2(16, 16)): self.frame_size = frame_size self.anim_surfs = list() for i in range(0, self.frame_count): tex = texture.subsurface( (int(self.frame_size.x) * i, int(self.frame_size.y) * row_id, int(self.frame_size.x), int(self.frame_size.y))) self.anim_surfs.append(tex) return self
def _slice(surface: pygame.Surface, r): assert surface is not None sliced = surface.subsurface(r) if surface.get_colorkey() is not None: sliced.set_colorkey(surface.get_colorkey()) return sliced
def draw(self, surface: pygame.Surface) -> List[MouseRegion]: surface.fill(self.BG_COLOR) if not self.input.value: return [] frame_surface = _opencv_to_pygame(self.input.value) target_rect = frame_surface.get_rect().fit(surface.get_rect()) target_surface = surface.subsurface(target_rect) pygame.transform.scale(frame_surface, target_rect.size, target_surface) return [MouseRegion(self.input.value.source, target_rect, (self.input.value.width, self.input.value.height))]
def load_parts(self, texture: pygame.Surface, count: int): assert (count > 0) self.partCount = count self.partSurfs = list() tex_dim: vec2 = vec2(texture.get_size()[0] // self.partCount, texture.get_size()[1]) for i in range(0, self.partCount): tex = texture.subsurface( (int(tex_dim.x) * i, 0, int(tex_dim.x), int(tex_dim.y))) self.partSurfs.append(pygame.transform.scale(tex, self.dim.data()))
def _render(surface: pygame.Surface, tree: Optional[FileSystemTree], selected_item: Optional[FileSystemTree]) -> None: """ Updates the visual when any changes are made """ _clear_screen(surface) _add_legend(surface) sub_surface = surface.subsurface( (0, 0, DIMENSIONS[0] - 180, DIMENSIONS[1] - 25)) _draw_rectangles(sub_surface, tree, selected_item) _render_text(surface, _get_display_text(selected_item)) pygame.display.flip()
def __init__(self, parentSurface:Surface, rect:pygame.Rect, filmstrip:Surface, borderColor:tuple): Widget.__init__(self, parentSurface, rect, borderColor, None) self.images = [] self.numImages = int(filmstrip.get_rect().height / filmstrip.get_rect().width) self.currentImage = 0 clipRect = pygame.Rect(0, 0, rect.width, rect.height) for x in range(0, self.numImages): self.images.append(filmstrip.subsurface(clipRect)) clipRect.move_ip(0, rect.height) self.draw()
def draw(self, surface: pg.Surface, neighbors: Neighborhood, cell_type: Type[Cell], pointed: Cell): square = surface.subsurface(self.get_rect()) if self.mode in (CursorMode.NONE, CursorMode.CREATE): cell_type().draw(square, neighbors, opacity=.2) self.texture.draw(square) if self.mode == CursorMode.INFO: info = self.font.render(pointed.info(), True, (255, 255, 255), (0, 0, 0)) surface.blit(info, (CELL_SIZE * (self.x + 1) + round(CELL_SIZE / 8), CELL_SIZE * self.y + round(CELL_SIZE / 2 - info.get_height() / 2)))
def draw(self, mousePos, mouseButtons): drawSurf = Surface(self.availableSpace) self.layerData.draw( drawSurf.subsurface( Rect(0, 26, self.availableSpace[0], self.availableSpace[1] - 26))) draw.rect(drawSurf, (240, 240, 240), (0, 0, self.availableSpace[0], 26)) for i in self.dropdowns: i.draw(drawSurf, mousePos, mouseButtons) return drawSurf
def draw(self, surface: pg.Surface): visible_layout = self.layout[self.offset:self.offset+self.height] for i, cell_type in enumerate(visible_layout): rect = pg.Rect((0, CELL_SIZE * i), (CELL_SIZE, CELL_SIZE)) cell_type.draw_icon(surface.subsurface(rect)) if self.offset + i == self.selected: Cursor.texture.draw(surface.subsurface(rect)) if self.selected_name_timer > 0: cell_name = self.font.render(self.cell_type.name(), True, (255, 255, 255), None) # def blit_alpha(target, source, location, opacity): timer = self.selected_name_cooldown - self.selected_name_timer blit_alpha( surface, cell_name, (CELL_SIZE + 8, (self.selected - self.offset) * CELL_SIZE + round(CELL_SIZE / 2 - cell_name.get_height() / 2)), 1 - (timer/self.selected_name_cooldown)**(1/self.selected_name_fadeout) )
def subsurfaces(surface: pygame.Surface, start: tuple, size: tuple, columns: int, rows: int = 1): surfaces: List[pygame.Surface] = [] for row in range(rows): for col in range(columns): location = (start[0] + size[0] * col, start[1] + size[1] * row) surfaces.append(surface.subsurface(pygame.Rect(location, size))) return surfaces
def add_spritesheet(self, name: str, img: pygame.Surface, rect_list: List[pygame.Rect], set_sprite_list=False, **kwargs) -> None: if not isinstance(img, pygame.Surface) or not rect_list: return self.add_sprite_list(name, [img.subsurface(rect) for rect in rect_list], set_sprite_list=set_sprite_list, **kwargs)
def split_screen(surface: pygame.Surface) -> List[pygame.Surface]: half_width = surface.get_width() // 2 height = surface.get_height() split = [] for i in range(0, 2): player_rect = pygame.Rect(i * half_width, 0, half_width, height) # TODO: Vorsicht bei fullscreen split.append(surface.subsurface(player_rect)) return split
def paint(self, canvas: pygame.Surface): """Paint the panel surface and it's children. This method should be extended in the subclasses and provide drawing capability of the panel. In order to repaint the child panels ``super().paint(canvas)`` should be called. :param canvas: pygame surface for drawing. """ for panel in self.components: if panel.visible: panel.paint(canvas.subsurface(panel.rect))
def cut_sheet(sheet: pg.Surface, columns: int, rows: int) -> Tuple[pg.Rect, List[pg.Surface]]: rect = pg.Rect(0, 0, sheet.get_width() // columns, sheet.get_height() // rows) frames = [] for j in range(rows): for i in range(columns): frame_location = (rect.w * i, rect.h * j) # self.rect.size - это кортеж (w, h) frames.append(sheet.subsurface(pg.Rect(frame_location, rect.size))) return rect, frames
def split_sprites( sheet: pygame.Surface) -> Tuple[pygame.Surface, pygame.Surface]: """Return apple and snake sprites already resized. Parameter sheet should contain 4x3 sprites, with the apple in the bottom rigth corner.""" apple = sheet.subsurface((SPRITE_BLOCK[0] * 3, SPRITE_BLOCK[1] * 2, SPRITE_BLOCK[0], SPRITE_BLOCK[1])) apple = pygame.transform.scale(apple, (BLOCK[0], BLOCK[1])) snake = sheet snake = pygame.transform.scale(snake, (BLOCK[0] * 4, BLOCK[1] * 3)) return apple, snake
def _add_legend(title_text: pygame.Surface) -> None: """ Adds the file type - color legend """ sub_surface = title_text.subsurface( (DIMENSIONS[0] - 178, 0, 178, DIMENSIONS[1] - 25)) pygame.draw.rect(sub_surface, pygame.color.THECOLORS["aliceblue"], (0, 0, 178, DIMENSIONS[1] - 25)) sub_surface.blit( pygame.font.SysFont("Segoe UI", 30, True).render("Legend", 1, pygame.color.THECOLORS["black"]), (35, 15)) _add_legend_items(sub_surface) _add_author(sub_surface)
def clear_line(self, screen: Surface, index: int) -> None: """ Collect all frozen sprites, draw them, remove line, create new frozen sprite. """ above_line = screen.subsurface( (0, 0, Config().width, index * Config.scale)).copy() screen.blit(above_line, (0, Config.scale)) self.frozen_tetrominos_layer.empty() self.frozen_tetrominos_layer.add(FrozenTetrominos(screen.copy())) return
def draw_frame(self, surface: pg.Surface, elapsed_time: float): surface.fill((60, 60, 60, 255)) if self.picture is None: return self.draw_text_frame(surface, elapsed_time) self.picture.please_draw(surface) crop = pg.Rect( self.picture.get_width(), 0, surface.get_width() - self.picture.get_width(), surface.get_height(), ) subsurface = surface.subsurface(crop) return self.draw_text_frame(subsurface, elapsed_time)
def draw_spectrum(self, f, x): draw_area = Surface((1, len(f)), depth=24) d = surfarray.pixels3d(draw_area) self.peak = np.maximum(np.amax(f, axis=0), self.peak) a = (255 * f / self.peak[np.newaxis, :]).astype(np.uint8) d[0, :, 1:] = a[::-1] d[0, :, 0] = a[::-1, 1] / 2 + a[::-1, 0] / 2 for m in self.markers: im = int((2 * m / self.sample_rate) * len(f)) d[0, -im, 0] = 255 del d it = int((2 * self.top_freq / self.sample_rate) * len(f)) self.surface.blit(smoothscale(draw_area.subsurface((0, len(f) - it - 1, 1, it)), (1, self.size[1])), (x, 0)) self.peak *= 2.0 ** (-1.0 / 100)
def render(self, ui_screen): super().render(ui_screen) # Generate a screen of the size of the map map = self.get_manager(Manager.MAP) map_screen = Surface((map.width * GRID_WIDTH, map.height * GRID_HEIGHT), SRCALPHA, 32) SESSION.render(map_screen, ui_screen) # Trim the screen to just the camera area camera_x, camera_y = self.get_manager(Manager.PLAYER).get_camera_coords() return map_screen.subsurface((camera_x, camera_y, min(CAMERA_WIDTH, map_screen.get_size()[0]), min(CAMERA_HEIGHT, map_screen.get_size()[1])))
def __init__(self, surface: Surface, definition: TileMapDefinition, *, no_init: bool = False): self.surface = surface self.definition = definition self.sub_surfaces: Dict[str, Surface] = {} if not no_init: for name, (x, y) in definition.tiles.items(): px, py = definition.get_tile_pos(x, y) self.sub_surfaces[name] = surface.subsurface( px, py, definition.tile_width, definition.tile_height)
def __init__(self, parentSurface:pygame.Surface, rect:pygame.Rect, skin:Skin, sequence:Sequence): Container.__init__(self, parentSurface, rect, skin) backgroundColor = skin.guiColor("Background") parentSurface.fill(backgroundColor, rect) self.sequence = sequence gridRect = pygame.Rect(0, rect.top + Padding.GRID, rect.width, rect.height - (Padding.GRID * 2)) self.parentSurface = parentSurface.subsurface(gridRect) self.rect = self.parentSurface.get_rect() self.background = pygame.Surface((self.rect.width, self.rect.height)) self.background.fill(skin.guiColor("Grid")) self.parentSurface.blit(self.background, self.rect) self.gridSprites = GridSpriteGroup(sequence, (gridRect.left, gridRect.top), self.rect, skin) self.activePopup = None
from pygame.sprite import * from factions import * pygame.init() screen = display.set_mode((800,600),HWSURFACE) display.set_caption('Regime Change') background = Surface(screen.get_size()) background.fill((128,128,128)) text = font.SysFont('Courier', 10) plot = background.subsurface(Rect(0, 0, background.get_width(), background.get_height()/2)) chart = background.subsurface(Rect(0, plot.get_height(), background.get_width(), background.get_height()-plot.get_height())) values = 'militarism', 'moralism' society = Society([Faction('aristocracy', (0,0,255), random(), values), Faction('merchant class', (0,255,0), random(), values), Faction('populace', (255,0,0), random(), values)]) for f in society.factions: for v in f.values.keys(): f.values[v] = random() charts = [chart.subsurface(Rect(i * chart.get_width()/len(society.factions),
class Screen(object): def __init__(self, size, caption, icon_caption): pygame.init() display.set_caption(caption, icon_caption) self._make_screen(size) self._controls = [] self._sprites = Group() self._drag_start = None self.dragged = lambda start, end: None self.size_changed = lambda size: None def _make_screen(self, size): self._screen = display.set_mode(size, HWSURFACE | RESIZABLE) @property def size(self): return self._screen.get_size() def step(self, dots, shapes): for e in event.get(): if e.type == QUIT: return True elif e.type == KEYDOWN: if e.key == K_ESCAPE: return True elif e.type == VIDEORESIZE: self._make_screen(e.size) self.size_changed(self.size) elif e.type == MOUSEBUTTONDOWN and e.button == 1: self._drag_start = mouse.get_pos() elif e.type == MOUSEMOTION and 1 in e.buttons: if self._drag_start is not None: p = mouse.get_pos() if p != self._drag_start: self.dragged(self._drag_start, p) self._drag_start = p elif e.type == MOUSEBUTTONUP and e.button == 1: self._drag_start = None p = mouse.get_pos() w, h = self.size dw = 0 for c in self._controls: dw += c.width if w - dw <= p[0] < w - dw + c.width: c.click((p[0] - (w - dw), p[1])) break self._sprites.empty() for dot in dots: sprite = Sprite() sprite.image = pygame.Surface((2 * dot.radius, 2 * dot.radius), flags=SRCALPHA) draw.circle(sprite.image, dot.color, (dot.radius,dot.radius), dot.radius) sprite.rect = Rect(tuple([int(c) - dot.radius for c in dot.location]), sprite.image.get_size()) self._sprites.add(sprite) for shape in shapes: sprite = Sprite() sprite.image = pygame.Surface((int(shape.width), int(shape.height)), flags=SRCALPHA) points = [tuple([int(c) for c in p]) for p in shape.points] if len(points) > 2: draw.polygon(sprite.image, shape.color, points) else: draw.lines(sprite.image, shape.color, False, points) sprite.rect = Rect(tuple([int(c) for c in shape.location]), sprite.image.get_size()) self._sprites.add(sprite) self._sprites.clear(self._screen, self._background) self._sprites.draw(self._screen) display.flip() return False def fill_background_rows(self, color, rows): self._background = Surface(self._screen.get_size()) self._background.fill((128,128,128)) for i in range(len(rows)): for start, length in rows[i]: self._background.fill(color, Rect(start, i, length, 1)) def draw_controls(self): w, h = self.size dw = 0 for c in self._controls: dw += c.width c.draw(self._background.subsurface(Rect(w - dw, 0, c.width, h))) def paint_background(self): self._screen.blit(self._background, (0,0)) def add(self, control): self._controls.append(control)