def rect_setup(self, button_width, button_height): ''' works out menu button positions and font sizes, iterates down from a large size so that it finds the largest size that fits the text for all the buttons nicely. Preferably the button strings should vary too much in length''' surf_midpoint = (int(0.5 * self.surf_width), int(0.5 * self.surf_height)) text_size = Menu.INITIAL_TEXT_SIZE font = Font(None, text_size) rect_list = [] for i in range(self.num_buttons): button_pos = (surf_midpoint[0] - button_width / 2, surf_midpoint[1] + (button_height * (i - self.num_buttons / 2)) * Menu.BUTTON_SPACING) rect = Rect(button_pos, (button_width, button_height)) rect_list.append(rect) while (font.size(self.button_strings[i])[0] >= (button_width * Menu.FONT_MARGIN) or font.size(self.button_strings[i])[1] >= (button_height * Menu.FONT_MARGIN)): text_size -= 1 font = Font(None, text_size) self.button_rects = rect_list self.button_text = [ font.render(s, 1, BLACK) for s in self.button_strings ] self.button_text_pos = [(self.button_rects[i].center[0] - self.button_text[i].get_size()[0] / 2, self.button_rects[i].center[1] - self.button_text[i].get_size()[1] / 2) for i in range(self.num_buttons)]
def __init__(self, font: Font, color: Color, text: str, **kwargs): super().__init__(font.size(text), **kwargs) self._font = font self._color = color self._text = text self._rendered_text = None self._update_text()
def main(): """ use pygame to convert a TTF to BMP """ if len(sys.argv) < 3: print("Usage: {} <TTF-file> <size>".format(sys.argv[0])) exit(1) fname = sys.argv[1] fsize = int(sys.argv[2]) outname = "{}_{}.BMP".format(os.path.splitext(fname)[0], fsize) print("Loading font {} in height {}...".format(fname, fsize)) init() f = Font(fname, fsize) print("Rendering {} characters '{}'".format(len(RENDER_STRING), RENDER_STRING)) width = None for ch in RENDER_CHARS: w, h = f.size(str(ch)) if width is None: width = w if w != width: print("ERROR: Font is not monospaced!") exit(1) surface = f.render(RENDER_STRING, False, (255, 255, 255), (0, 0, 0)) print("Writing rendered characters to '{}'...".format(outname)) image.save(surface, outname)
def __init__(self, x, y, width, height, msg, size=16, text_colour=base.BLACK, bg_colour=base.WHITE, highlight_text=base.WHITE, highlight_bg=base.BLACK, offset_x=0, offset_y=0, bold=False): self.normal = pygame.Surface((width, height)) self.normal.fill(bg_colour) font = Font(_FONT, size) font.set_bold(bold) font_width, font_height = font.size(msg) font_x = (width - font_width) / 2 font_y = (height - font_height) / 2 self.normal.blit(font.render(msg, False, text_colour), (font_x, font_y)) self.highlighted = pygame.Surface((width, height)) self.highlighted.fill(highlight_bg) self.highlighted.blit(font.render(msg, False, highlight_text), (font_x, font_y)) self.offset_x = offset_x self.offset_y = offset_y self.force_highlight = False self.disabled = False PicassoAsset.__init__(self, self.normal, x, y)
def __init__(self, font: Font, color: Color, format_string: str, format_variable: Any, **kwargs): text = format_string % format_variable text_size = font.size(text) super().__init__(text_size, **kwargs) self._format_string = format_string self._font = font self._color = color self._rendered_text = self._font.render(text, True, color)
def find_font_size(self): size = 100 while size >= 1: f = Font(FONT, size) w, h = f.size('8') if w < self.w and h < self.h: return size size = size -1 return size
def find_font_size(self): size = 100 while size >= 1: f = Font(FONT, size) w, h = f.size('8') if w < self.w and h < self.h: return size size = size - 1 return size
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)
def __init__(self, pos: tuple, width: float, height: float) -> None: """Initialise a new `MessageDisplay` object. pos: a pair of floats that describe this display's position on the screen. The floats must be normalized, e.g. a value of (0.3, 0.6) means 30% of the screen width and 60% of the screen height. (0, 0) is the top left corner. width: the normalized width of the display. height: the normalized height of the display. """ validate(self.__init__, locals()) surface_w, surface_h = pygame.display.get_surface().get_size() pos_x, pos_y = pos self.left_pos = pos_x - width/2 top_pos = pos_y - height/2 self.messages = [] line_height = height*0.03 self.font_height = line_height*0.8 # Because a message may be of an arbitrary length, there must # be a mechanism that wraps the text and displays it on # multiple lines. # A monospace font family must be used because a constant # character width is required. font = Font( pygame.font.match_font('mono'), int(surface_h * self.font_height) ) font_px_width, _ = font.size('a') self.chars_per_line = int(surface_w * width / font_px_width) self.lines = int(surface_h * height / (surface_h * line_height)) # The possible y positions for labels must be saved for use # in the render function. self.y_positions = list( xrange( top_pos + line_height/2, top_pos + line_height*self.lines, line_height ) )
def start_rating(): global process_mode, rating_font, rating_lines, rating_menu_btn, rating_window, rating_sprites process_mode = 'rating' rating_sprites = Group() rating_window = RatingWindow() rating_menu_btn = RatingCloseButton() rating_sprites.add(rating_window) rating_sprites.add(rating_menu_btn) rating_sprites.draw(main_screen) rating_font = Font(font, 60) try: first5 = requests.get(host, json={'operation': 'get5'}).json()['res'] your_place = requests.get(host, json={ 'operation': 'get_user', 'user': data['name'] }).json()['res'] max_name = max(first5, key=lambda x: len(x[1]))[1] for i in range(len(first5)): line = str(i + 1) + '. ' + first5[i][1] line = rating_font.render(line, 0, font_color) main_screen.blit(line, (180, i * 55 + 150)) line2 = rating_font.render(str(first5[i][2]), 0, font_color) main_screen.blit( line2, (190 + rating_font.size('1. ' + max_name)[0], i * 55 + 150)) if your_place: line = str(your_place[0]) + '. ' + data['name'] + ' ' + str( your_place[2]) else: line = 'Вашего имени нет в рейтинге' line = rating_font.render(line, 0, font_color) main_screen.blit(line, (180, 475)) except Exception: line = rating_font.render('Произошла ошибка', 0, font_color) main_screen.blit(line, (180, 150)) line = rating_font.render('Попробуйте позже', 0, font_color) main_screen.blit(line, (180, 205)) pygame.display.flip()
def draw(self): if self.dirty(): self.count = self.territory_asset.territory.armies font = Font(None, self.size) dimension = font.size(str(self.count) * 2) text_diagonal_length = math.sqrt(math.pow(dimension[0] / 2, 2) + math.pow(dimension[1], 2)) circle_radius = int(math.ceil(text_diagonal_length / 2)) #print circle_radius #print dimension [0] self.surface = pygame.Surface([44, 44], pygame.SRCALPHA, 32) self.surface = self.surface.convert_alpha() pygame.draw.circle(self.surface, base.BLACK, (circle_radius, circle_radius), circle_radius) pygame.draw.circle(self.surface, base.LIGHT_BROWN, (circle_radius, circle_radius), circle_radius - 2) font_surface = font.render(str(self.count), False, self.colour).convert() self.surface.blit(font_surface, (circle_radius - dimension[0] / 4, circle_radius - dimension[1] / 2)) return self.surface
def draw(self): if self.dirty(): self.count = self.territory_asset.territory.armies font = Font(None, self.size) dimension = font.size(str(self.count) * 2) text_diagonal_length = math.sqrt( math.pow(dimension[0] / 2, 2) + math.pow(dimension[1], 2)) circle_radius = int(math.ceil(text_diagonal_length / 2)) #print(circle_radius #print(dimension [0] self.surface = pygame.Surface([44, 44], pygame.SRCALPHA, 32) self.surface = self.surface.convert_alpha() pygame.draw.circle(self.surface, base.BLACK, (circle_radius, circle_radius), circle_radius) pygame.draw.circle(self.surface, base.LIGHT_BROWN, (circle_radius, circle_radius), circle_radius - 2) font_surface = font.render(str(self.count), False, self.colour).convert() self.surface.blit(font_surface, (circle_radius - dimension[0] / 4, circle_radius - dimension[1] / 2)) return self.surface
def rect_setup(self, button_width, button_height): ''' works out menu button positions and font sizes, iterates down from a large size so that it finds the largest size that fits the text for all the buttons nicely. Preferably the button strings should vary too much in length''' surf_midpoint = (int(0.5 * self.surf_width), int( 0.5 * self.surf_height )) text_size = Menu.INITIAL_TEXT_SIZE font = Font(None, text_size) rect_list = [] for i in range(self.num_buttons): button_pos = (surf_midpoint[0] - button_width/2, surf_midpoint[1] + (button_height * (i - self.num_buttons/2)) * Menu.BUTTON_SPACING) rect = Rect(button_pos, (button_width, button_height)) rect_list.append(rect) while (font.size(self.button_strings[i])[0] >= (button_width * Menu.FONT_MARGIN) or font.size(self.button_strings[i])[1] >= (button_height * Menu.FONT_MARGIN)): text_size -= 1 font = Font(None, text_size) self.button_rects = rect_list self.button_text = [font.render(s, 1, BLACK) for s in self.button_strings] self.button_text_pos = [(self.button_rects[i].center[0] - self.button_text[i].get_size()[0]/2, self.button_rects[i].center[1] - self.button_text[i].get_size()[1]/2) for i in range(self.num_buttons)]
def render_score_screen(board_render): should_show_screen = board_render.board_manager.round_should_end group = LayeredUpdates() if not should_show_screen: return 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) font_small = Font(font_path, 24) match = board_render.match scores = match.scores delta_scores = match.delta_scores total_scores = list(map(lambda s: s[0] + s[1], zip(scores, delta_scores))) winner_indices = numpy.argwhere(numpy.array(delta_scores) > 0).flatten() winner_names = [] array = numpy.array(total_scores) temp = array.argsort()[::-1] ranks = numpy.empty_like(temp) ranks[temp] = numpy.arange(len(array)) icons = get_object('boticons')['bot'] screen_surface = Surface(board_render.surface.get_size(), pygame.SRCALPHA) screen_surface.fill((0, 0, 0)) ROUND_COMPLETE = "Round Complete" round_complete_surface = font.render(ROUND_COMPLETE, True, (255, 255, 255)) font_width, font_height = font.size(ROUND_COMPLETE) icon_size = (100, 100) player_list = match.ai_list x = screen_surface.get_width() // 5 y = font_height + 5 for seat in range(4): ai_name = player_list[seat] name = None icon = None for entry in icons: if entry['ai'] == ai_name: name = entry['name'] icon = entry['icon'] break if name is None: raise "BOT WAS NOT DEFINED." if seat in winner_indices: winner_names += [name] icon_surface = Surface(icon_size, pygame.SRCALPHA) load_image_resource(icon, icon_surface, size=icon_size) screen_surface.blit( icon_surface, (x, y) ) player_name = font.render(name, True, (255, 255, 255)) _, name_h = font.size(name) screen_surface.blit( player_name, (x + icon_size[0] + 10, y) ) score_string = "{} Points".format(scores[seat]) score_render = font_small.render(score_string, True, (255, 255, 255)) _, score_h = font_small.size(score_string) screen_surface.blit( score_render, (x + icon_size[0] + 10, y + name_h + 5) ) delta_string = "{}{}".format("+" if delta_scores[seat] >= 0 else "", delta_scores[seat]) delta_render = font_small.render(delta_string, True, (255, 255, 255)) _, delta_h = font_small.size(delta_string) screen_surface.blit( delta_render, (x + icon_size[0] + 10, y + name_h + 5 + score_h + 5) ) total_string = "Total: {} Points".format(total_scores[seat]) total_render = font_small.render(total_string, True, (255, 255, 255)) screen_surface.blit( total_render, (x + icon_size[0] + 10, y + name_h + 5 + score_h + 5 + delta_h + 5) ) place_string = "{}".format(ranks[seat] + 1) place_render = font.render(place_string, True, (255, 255, 255)) place_w, place_h = font.size(place_string) screen_surface.blit( place_render, (x - place_w - 5, y + ((icon_size[1] - place_h) // 2)) ) y += icon_size[1] + 70 LOADING_NEXT_ROUND = "Loading next Round..." loading_surface = font.render(LOADING_NEXT_ROUND, True, (255, 255, 255)) loading_width, loading_height = font.size(LOADING_NEXT_ROUND) screen_surface.blit( loading_surface, (screen_surface.get_width() - loading_width - 10, screen_surface.get_height() - loading_height - 10) ) screen_surface.blit( round_complete_surface, ((screen_surface.get_width() // 2) - (font_width // 2), 10), ) result_pos = (screen_surface.get_width() * 0.6, screen_surface.get_height() // 3) if board_render.board_manager.did_exhaustive_draw: EXHAUSTIVE = "Exhaustive Draw" exhaustive_surface = font.render(EXHAUSTIVE, True, (255, 255, 255)) screen_surface.blit( exhaustive_surface, result_pos ) else: WINNERS = "Winners:" winners = ", ".join(winner_names) winner_text = font_small.render(WINNERS, True, (255, 255, 255)) winner_name_text = font_small.render(winners, True, (255, 255, 255)) screen_surface.blit( winner_text, result_pos ) screen_surface.blit( winner_name_text, (result_pos[0], result_pos[1] + winner_text.get_rect().height + 5) ) background_sprite = Sprite() background_sprite.rect = screen_surface.get_rect() background_sprite.image = screen_surface background_sprite.layer = 0 group.add(background_sprite) return group
class Text(object): def __init__(self, text="", x=0, y=0, font_size=10, color=(0, 0, 0), background_color=(255, 255, 255), antialias=True): self._color = color self._background_color = background_color self._font_size = font_size self._font = Font(pygame.font.get_default_font(), self._font_size) self._antialias = antialias self._text = None self._surface = None self._text_size = None self._rect = None self._x = x self._y = y self.text = text def _render(self): return self._font.render(self._text, self._antialias, self._color, self._background_color) def _create_rect(self): return Rect(self.x, self.y, self._text_size[0], self._text_size[1]) def draw(self, surface): surface.blit(self._surface, (self.x, self.y)) def erase(self, surface, rect=None): if rect is None: rect = self.rect pygame.draw.rect(surface, self._background_color, rect, 0) @property def text(self): return self._text @text.setter def text(self, value): self._text = value self._surface = self._render() self._text_size = self._font.size(self._text) self._rect = self._create_rect() @property def rect(self): return self._rect @property def x(self): return self._x @x.setter def x(self, value): self._x = value self._rect = self._create_rect() @property def y(self): return self._y @y.setter def y(self, value): self._y = value self._rect = self._create_rect()
class Screen(BlittableObject) : #list of backgrounds for different levels BACKGROUND = ("images/background_1.png", "images/background_2.png", "images/background_3.png", "images/background_4.png", "images/background_5.png") DEATH_SCENE = "images/death_scene.png" NUM_ENEMIES_PER_LEVEL = 2 GAME_MUSIC = 'sounds/bubliki.ogg' PLATFORM_LOCATIONS = ( ((0.1, 0.5), (0.7, 0.5), (0.4, 0.25)), ((0.1, 0.3), (0.4, 0.55), (0.7, 0.3)), ((0.1, 0.25), (0.4, 0.45), (0.7, 0.65)), ((0.1, 0.5), (0.4, 0.25), (0.7, 0.5)), ((0.1, 0.65), (0.4, 0.45), (0.7, 0.25)) ) def __init__(self, canvas, quit_program): BlittableObject.__init__(self, canvas) self.reset() #stores the method to completely quit the game, so Menu can call it when needed self.quit_program = quit_program self.menu_toggle() #set up a store for the state of important keys, this is managed by the update handler in main.py self.key_register={"Left":False,"Up":False,"Right":False,"Shoot":False} """"This code would allow us to set the game in multiple ways dependings on the variables passed default resets the game to basically empty and to level 1.""" def reset(self, running = False, player = None, ship = None, platforms = None, platform_rects = None, enemies = None, collectables = None, game_level = 1): """This allows the backgrounds to loop no matter how many levels are completed (5 should be enough though).""" image_ref = (game_level-1) % 5 self.set_image(Screen.BACKGROUND[image_ref], self.surface.get_size()) self.running = running self.menu = False self.player = player self.ship = ship self.platforms = platforms self.platform_rects = platform_rects self.enemies = enemies self.collectables = collectables self.game_over = False self.game_won = False self.game_level = game_level self.font = Font(None, self.surf_height/20) #This method controls what happens when a new game or level is started def new_game(self, game_level = 1): running = True platforms = [] for i in Screen.PLATFORM_LOCATIONS[(game_level-1) % 5]: platforms.append(Platforms(self.surface, *i)) platform_rects = [i.rect for i in platforms] player = Player(self.surface) collectables = Collectables(self.surface) ship = Ship(self.surface) enemies = [] self.reset(running, player, ship, platforms, platform_rects, enemies, collectables, game_level) if game_level == 1 : music.load(Screen.GAME_MUSIC) music.play(-1) #This controls what happens when the game is lost def lost(self): music.stop() self.running = False self.image = self.load_image(Screen.DEATH_SCENE, self.rect.size) #This controls what happens when the game is won. def win(self): game_level = self.game_level + 1 self.new_game(game_level) """Draw checks if parts of the game should be drawn or not and calls their draw methods, also draws background and info text.""" def draw(self): self.surface.blit(self.image, (0,0)) if self.running: if self.platforms: for i in self.platforms: i.draw() if self.ship: self.ship.draw() if not self.ship.all_collected(): if self.enemies: for i in self.enemies: i.draw() if self.collectables: self.collectables.draw() if self.player : self.player.draw() lives_string = "Lives Remaining: {}".format(self.player.lives) level_string = "Level: {}".format(self.game_level) lives_text = self.font.render(lives_string, 1, WHITE) level_text = self.font.render(level_string, 1, WHITE) lives_text_size = self.font.size(lives_string) lives_text_pos = (self.surf_width - int(lives_text_size[0] * 1.2), int(lives_text_size[1] * 1.2)) level_text_size = self.font.size(level_string) level_text_pos = (int(level_text_size[0] * 0.2), int(level_text_size[1] * 1.2)) self.surface.blit(lives_text, lives_text_pos) self.surface.blit(level_text, level_text_pos) if self.menu: self.menu.draw() #checks what needs to be updated and calls their update functions def update(self): if self.game_over: self.lost() if self.game_won: self.win() if self.running and not self.menu: if not self.ship.all_collected(): #ensures there are always enough enemies on screen if self.enemies != None: exp_num_enemies = self.game_level * Screen.NUM_ENEMIES_PER_LEVEL while len(self.enemies) < exp_num_enemies: self.enemies.append(Enemy(self.surface, self.game_level)) for i in self.enemies: i.update(self.platform_rects) if self.collectables: self.collectables.update(self.platform_rects) if self.player: self.player.move_player(self.key_register) self.game_over = self.player.update(self.platform_rects, self.enemies, self.collectables, self.ship) if self.game_over: self.sound = self.set_sound("sounds/gameover.ogg") self.sound.play() if self.ship: self.game_won = self.ship.update() else: pass def menu_toggle(self): if not self.menu: self.menu = Menu(self, self.surface) else: self.menu = False def mouse_handler(self, pos): if self.menu: self.menu.mouse_handler(pos) elif self.game_over: self.reset() self.menu_toggle()