def _initPygame(self): pygame.init() self.screen = pygame.display.set_mode(Game.SCREEN_SIZE) pygame.display.set_caption('Snake Game') self.game_font = SysFont(Game.FONT, 72) self.new_game_font = SysFont(Game.FONT, 48) self.score_font = SysFont(Game.FONT, 32)
def set_font_name(self, name): # Set the name of the window font used to draw strings # - self is the Window # - name is the str name of the font self.__font_name__ = name self.__font__ = SysFont(self.__font_name__, self.__font_size__, True)
def __init__(self, surface): self.surface = surface self.status = 0 # 0: auto; 1: manul self.iter = 0 self.ftw = 120 self.font = SysFont('Comic Sans MS', 32) self.draw_help()
class Scoreboard(): def __init__(self, game): self.settings = game.settings self.screen = game.screen self.stats = game.stats self.screen_rect = self.screen.get_rect() self.font = SysFont(None, 70) self.text_color = (255, 255, 255) self.score = self.stats.score self.best = 0 self.prep_score() self.prep_time() def prep_score(self): rounded_score = round(self.stats.score, -1) score_str = "{:,}".format(rounded_score) self.image_score = self.font.render(score_str, True, self.text_color) self.score_rect = self.image_score.get_rect() self.score_rect.top = self.screen_rect.top + 20 self.score_rect.right = self.screen_rect.right - 20 def prep_time(self): format_time = "%02d:%02d" % (self.stats.minutes, self.stats.seconds) self.image_time = SysFont(None, 30).render(format_time, True, (150, 150, 150)) self.time_rect = self.image_time.get_rect() self.time_rect.topright = self.score_rect.bottomright self.time_rect.top += 10 def blit_score(self): self.screen.blit(self.image_score, self.score_rect) self.screen.blit(self.image_time, self.time_rect)
def __init__(self): self.started = False self.fill_colour_min = Color(200, 167, 238) self.fill_colour_max = Color(138, 167, 200) self.circ_colour_min = Color(100, 20, 55) self.circ_colour_max = Color(0, 66, 127) self.circ_pos_min = Vector2(50, 50) self.circ_pos_max = Vector2(350, 350) self.lerp_n = 0 self.lerp_speed = 0.05 self.bg_colour = (240, 160, 212) self.area_info = (0, 0, 450, 450) self.cell_amt = 18 self.back_colour = Color(231, 242, 198) self.cell_colour = Color(200, 200, 227) self.cell_size = (self.area_info[2] // self.cell_amt, self.area_info[3] // self.cell_amt) self.play_rect = Rect(self.area_info) self.play_surf = Surface(self.area_info[2:]) self.play_surf.fill(self.back_colour) self.circ_radius = 25 self.fruit = Collectible(self.cell_size, self.cell_amt) self.draw_checkerboard() self.font = SysFont("Arial", 30) self.text = self.font.render("Text on screen.", False, self.bg_colour)
def set_font_size(self, point_size): # Set the point size of the window font used to draw strings # - self is the Window # - point_size is the int point size of the font self.__font_size__ = point_size self.__font__ = SysFont(self.__font_name__, self.__font_size__, True)
def init_text_ui(self): # ui button surface ui_text_list = [] if self.width == 0: ui_text_list.append( SysFont(self.font, self.font_size).render(self.text, True, self.color)) else: # text[start_pointer:end_pointer-1]: characters displayed in a line start_pointer = 0 # character start of the line end_pointer = 0 # character end of the line while end_pointer < len(self.text): text_width = SysFont(self.font, self.font_size).render( self.text[start_pointer:end_pointer], True, self.color).get_width() if text_width >= self.width: ui_text_list.append( SysFont(self.font, self.font_size).render( self.text[start_pointer:(end_pointer - 1)], True, self.color)) start_pointer = end_pointer - 1 else: end_pointer += 1 # Add the last text element ui_text_list.append( SysFont(self.font, self.font_size).render( self.text[start_pointer:end_pointer], True, self.color)) return ui_text_list
def blit_resources(self): v = self.ui_vars font = Font(self.CORE.font_family, self.CORE.fonts['resource'][0]) txt_right = v.disp_w - v.rsr_icos - 2*v.rsr_spc ico_left = v.disp_w - v.rsr_icos - v.rsr_spc h = v.rsr_icos + v.rsr_spc self.screen.blit(self.gfx.icons['wood'], (ico_left, v.rsr_spc)) self.screen.blit(self.gfx.icons['iron'], (ico_left, h+v.rsr_spc)) self.screen.blit(self.gfx.icons['fuel'], (ico_left, 2*h+v.rsr_spc)) plr = self.player wood_amount = font.render(str(plr.r_wood), False, self.colors.white) w_rect = wood_amount.get_rect() w_rect.right = txt_right w_rect.top = v.rsr_spc iron_amount = font.render(str(plr.r_iron), False, self.colors.white) i_rect = iron_amount.get_rect() i_rect.right = txt_right i_rect.top = h + v.rsr_spc fuel_amount = font.render(str(plr.r_fuel), False, self.colors.white) f_rect = fuel_amount.get_rect() f_rect.right = txt_right f_rect.top = 2*h + v.rsr_spc self.screen.blit(wood_amount, w_rect) self.screen.blit(iron_amount, i_rect) self.screen.blit(fuel_amount, f_rect)
def prep_time(self): format_time = "%02d:%02d" % (self.stats.minutes, self.stats.seconds) self.image_time = SysFont(None, 30).render(format_time, True, (150, 150, 150)) self.time_rect = self.image_time.get_rect() self.time_rect.topright = self.score_rect.bottomright self.time_rect.top += 10
def __init__(self): self.started = False self.bg_colour = (240, 160, 212) self.area_info = (0, 0, 450, 450) self.cell_amt = 18 self.back_colour = Color(231, 242, 198) self.cell_colour = Color(200, 200, 227) self.cell_size = (self.area_info[2] // self.cell_amt, self.area_info[3] // self.cell_amt) self.play_rect = Rect(self.area_info) self.play_surf = Surface(self.area_info[2:]) self.play_surf.fill(self.back_colour) self.circ_radius = 25 self.fruit = Collectible(self.cell_size, self.cell_amt) self.score = 0 self.snake = Snake(self.cell_size, self.cell_amt) self.snake_is_dead = False self.draw_checkerboard() self.font = SysFont("Arial", 30) self.text = self.font.render("Score: 0", False, self.back_colour)
def drawSummary(self, screen): """ draws a summary """ x = 30 y = 50 fontObj = SysFont("Monospace", 18, bold=True) time = 0 rowHeight = fontObj.get_height() + 2 for world in self.worlds: time = max(time, world.time) renderedFitness = fontObj.render("Fitness: {0:.2f}".format(world.nn.fitness), 1, (255, 255, 255)) if (y + rowHeight > (constants.screenHeight - 95)): y = 50 x += 260 if x + renderedFitness.get_width() > constants.screenWidth: break # draw vertical line pygame.draw.line(screen, (100, 100, 100), (x - 10, 45), (x - 10, constants.screenHeight - 100), 2) # draw horizontal line (if still on first column) elif x < 100: pygame.draw.line(screen, (100, 100, 100), (25, y + rowHeight - 3), (constants.screenWidth - 25, y + rowHeight - 3), 2) screen.blit(renderedFitness, (x, y)) y += rowHeight # draw the time renderedTime = pygame.font.SysFont("Monospace", 34, bold=True).render("Time: {0:.2f}".format(time), 1, (255, 255, 255)) screen.blit(renderedTime, ((constants.screenWidth - renderedTime.get_width()) // 2, 10))
def text(self, text): self._text = text font = SysFont('consola', 60) self._font = font.render(self._text, True, (255, 0, 0)) # well, figure out what the font's width is depended on self.content['font'] = [self._font, (self.rect.centerx - self._font.get_width() / 2, self.rect.centery - self._font.get_height() / 2)]
def __init__(self, resourcemgr, team, level): super(InGame, self).__init__(resourcemgr) self.tilemgr = TileManager(resourcemgr, level) self.unitmgr = UnitManager(resourcemgr, STATES.INGAME, team, level) self.lw = self.tilemgr.lw self.lh = self.tilemgr.lh self.team = team # self.bar = Bar(config) music.load(os.path.join(resourcemgr.main_path, 'sound/yyz.ogg')) self.camera = Camera(0, 0, self.lw, self.lh, resourcemgr) font = SysFont(FONTS, int(48 * resourcemgr.scale), True) self.win_msg = font.render('YOU WINNN!!! GGGG GGGGGGGGGGGGGGG', 1, WHITE) self.win_msg_rect = self.win_msg.get_rect( centerx=self.camera.rect.w / 2, centery=self.camera.rect.h / 4) self.lose_msg = font.render('You lost. What the f**k, man?', 1, BLACK) self.lose_msg_rect = self.win_msg.get_rect( centerx=self.camera.rect.w / 2, centery=self.camera.rect.h / 4) self.mouse_rect = Rect(0, 0, 0, 0) self.x_first = 0 self.y_first = 0 self.won = False self.lost = False self.gg = load_sound(resourcemgr.main_path, 'gg.ogg') self.lose = load_sound(resourcemgr.main_path, 'lose.ogg')
def __init__(self, ai_settings, game_status, screen): self.ai_settings = ai_settings self.game_stats = game_status self.screen = screen self.screen_rect = self.screen.get_rect() self.text_font = SysFont(None, 18) self.text_color = (120, 30, 30)
def display_abacus_add_subtract_problem( screen, color, separator_bead_color, upper_left, height, operands, line_spacing=1.2, font=None, ): if font is None: font = SysFont('Lucida Console', height) x_ul, y_ul = upper_left max_digits = max(len(digitize(operand)) for operand in operands) column_width = height_to_width(height) max_sign_width = 0. for row_n, operand in enumerate(operands): x_row = x_ul y_row = y_ul + row_n * height * line_spacing digits = digitize(abs(operand)) n_digits = len(digits) sign = '+' if operand >= 0 else '-' sign_surface = font.render(sign, True, color) sign_width = sign_surface.get_width() max_sign_width = max(sign_width, max_sign_width) screen.blit(sign_surface, (x_row, y_row)) draw_columns( screen, color, (x_row + sign_width + (max_digits - n_digits) * column_width, y_row), height, digits, separator_bead_color=separator_bead_color, ) row_n = len(operands) x_rect_left = x_ul x_rect_right = (x_ul + max_sign_width + max_digits * column_width) y_rect_top = (y_ul + height * (row_n * line_spacing - .25 * (line_spacing - 1.))) y_rect_bottom = (y_rect_top + .25 * (line_spacing - 1.) * height) polygon(screen, color, [ (x_rect_left, y_rect_top), (x_rect_right, y_rect_top), (x_rect_right, y_rect_bottom), (x_rect_left, y_rect_bottom), ]) # coordinates of where to draw the rightmost digit # of the response return ((x_ul + sign_width + max_digits * column_width), y_ul + row_n * height * line_spacing)
def text(self, value): self._text = value font = SysFont('consola', self.font_size) self._font = font.render(self._text, True, (255, 0, 0)) self.content['font'] = [self._font, ( self.rect.centerx - self._font.get_width() / 2, self.rect.centery - self._font.get_height() / 2)]
def set_font_name(self, name): """Set the name of the window font used to draw strings. :param name: the str name of the font """ self.__font_name__ = name self.__font__ = SysFont(self.__font_name__, self.__font_size__, True)
def __init__(self,screen,text_start_point=define.TEXT_START_POINT,font=define.TEXT_FONT,font_size=define.FONT_SIZE,): try: self.font = Font(font,font_size) except IOError: print "bad font file name or i/o error,sys will load default font" self.font = SysFont("simsunnsimsun",font_size,False,False) self.screen = screen self.text_start_point = text_start_point
def __init__(self, resourcemgr): super(Intro, self).__init__(resourcemgr) self.bg = resourcemgr.get_background_image(BACKGROUNDS.INTRO) self.bg_rect = self.bg.get_rect() font = SysFont(FONTS, int(52 * self.resourcemgr.scale), True) self.msg = font.render('Sprayed Studios Presents...', 1, RED) self.msg_rect = self.msg.get_rect(centerx=self.bg_rect.w / 2, centery=self.bg_rect.h / 10)
def __init__(self, settings: Settings, screen: Surface): self._settings = settings self._screen = screen self._screen_rect = screen.get_rect() self._font = SysFont(None, settings.scoreboard_font_size) self._margin = settings.scoreboard_margin self.render_all(0, 0, 1, settings.health_limit, settings.ammo_limit)
def set_font_size(self, point_size): """Set the point size of the window font used to draw strings. :param point_size: the int point size of the font """ self.__font_size__ = point_size self.__font__ = SysFont(self.__font_name__, self.__font_size__, True)
class Renderer: path = rootpath + '/GA/result/figure/' size = (1440, 192) def __init__(self, surface): self.surface = surface self.status = 0 # 0: auto; 1: manul self.iter = 0 self.ftw = 120 self.font = SysFont('Comic Sans MS', 32) self.draw_help() def on_space(self): if self.status == 0: self.status = 1 self.ftw = 120 else: self.status = 0 def on_left(self): if self.status == 1 and self.iter > 0: self.iter -= 1 def on_right(self): if self.status == 1 and self.iter < Renderer.get_file_num() - 1: self.iter += 1 def draw_help(self): if self.status == 1: text_surface = self.font.render( 'Iteration' + str(self.iter) + "(>>)", True, (0, 0, 0)) else: text_surface = self.font.render( 'Iteration' + str(self.iter) + "(||)", True, (0, 0, 0)) self.surface.blit(text_surface, [0, 0]) def draw_level(self): img = image.load(Renderer.path + 'iteration%d.jpg' % self.iter) img = transform.scale(img, Renderer.size) self.surface.blit(img, [0, 0]) if self.status == 0: if self.ftw > 0: self.ftw -= 1 return if self.iter < Renderer.get_file_num() - 1: self.iter += 1 self.ftw += 120 def update(self): self.draw_level() self.draw_help() @staticmethod def get_file_num(): _, _, files = os.walk(Renderer.path).__next__() return len(files)
def __init__(self): Sprite.__init__(self, Game.current.sprites) Game.current.sprites.change_layer(self, Game.LAYER_ABOVE_BG) self.font = SysFont(self.font, 22) self.image = Surface(( Game.current.board.rect.width, self.font.get_linesize() + self.padding * 2 )) self.text = "" self.rect = self.image.get_rect()
def blit_loading(self): clrs = self.colors v = self.ui_vars font = Font(self.CORE.font_family, self.CORE.fonts['loading'][0]) text = font.render(self.TEXT.loading, False, clrs.white) rect = text.get_rect() rect.centerx = v.disp_cx rect.centery = v.disp_cy self.screen.fill(clrs.gdark) self.screen.blit(text, rect)
def T(cw, txt, x, y, r=0, g=0, b=0, aliasing=1, size=20, center=True): """allows the display of text on screen with or without centering the text will be displayed in the window 'cw' """ font = SysFont(None, size) text = font.render(txt, aliasing, (r, g, b)) if center: textpos = text.get_rect(centery=y, centerx=x) else: textpos = (x, y) cw.blit(text, textpos)
def __init__(self, settings: Settings, screen: Surface, msg): self._screen = screen self._settings = settings self._width, self._height = settings.btn_size self._font = SysFont(None, settings.btn_font_size) self.rect = Rect(0, 0, self._width, self._height) self.rect.center = screen.get_rect().center self._render_msg(msg)
def generateNewTextImage(self) -> NoReturn: from Mangers.graph_manager import DimensionsManger diments = DimensionsManger() fontInit() font = SysFont(get_default_font(), diments.VerticesDiments.fontSize) keyImage = font.render(str(self.name), True, Colors.VerticesColors.OnVertexDefaultColor) wText, hText = font.size(str(self.name)) self.wTextHalf, self.hTextHalf = wText // 2, hText // 2 self.textImage = keyImage self.isMoved = True
def __init__(self, world): self._world = world # update the entityfactory to a rendered version self._world.worldgen.ef = RenderEntityFactory() # attach the renderer for the player self._world.player.renderer = renderent.RenderPlayer(self._world.player) # the background texture self._background = pygame.transform.scale(texhandler.Textures.gameBG.surface, (2 * screenWidth, screenHeight)) self._overlays = texhandler.adjustedSurface(texhandler.Textures.overlays, height=32) self._fontObj = SysFont("Monospace", 20, bold=True)
def __init__(self, ai_setting, screen, stats): self.ai_setting = ai_setting self.stats = stats self.screen = screen self.screen_rect = screen.get_rect() self.text_color = (30, 30, 30) self.font = SysFont(None, 48) self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships()
def __init__(self, maxHealth: int, isPlayer1: bool, nick: str) -> None: # region DocString """ Creates a `HealthBar` object ### Arguments `maxHealth {int}`: `summary`: the starting health of the player `isPlayer1 {bool}`: `summary`: boolean to display the bar in the right direction `nick {str}`: `summary`: the username of the player """ # endregion super().__init__() self.isPlayer1 = isPlayer1 # region Gauge sprite self.gaugeImg = load(Game.GAUGE_PATH).convert_alpha() self.gaugeRect = self.gaugeImg.get_rect() self.gaugeRect.move_ip( 10 if self.isPlayer1 else Game.SIZE[0] - self.gaugeRect.width - 10, 10) # endregion # region Bar sprite self.lifeImg = load(Game.LIFEBAR_PATH).convert_alpha() self.lifeRect = self.lifeImg.get_rect() self.lifeRect.move_ip( 10 if self.isPlayer1 else Game.SIZE[0] - self.lifeRect.width - 10, 10) # endregion if not self.isPlayer1: self.gaugeImg = flip(self.gaugeImg, True, False) self.lifeImg = flip(self.lifeImg, True, False) self.nick = SysFont(Game.FONT, 30).render(nick.strip(), False, Color.WHITE) self.nickRect = self.nick.get_rect() self.nickRect.move_ip( 15 if self.isPlayer1 else Game.SIZE[0] - self.nickRect.width - 15, self.gaugeRect.height + 15, ) self.playerHealth = maxHealth self.maxHealth = maxHealth
class Scoreboard(): def __init__(self, ai_setting, screen, stats): self.ai_setting = ai_setting self.stats = stats self.screen = screen self.screen_rect = screen.get_rect() self.text_color = (30, 30, 30) self.font = SysFont(None, 48) self.prep_score() self.prep_high_score() self.prep_level() self.prep_ships() def show_score(self): self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.high_score_image, self.high_score_rect) self.screen.blit(self.level_image, self.level_rect) self.ships.draw(self.screen) def prep_score(self): rounded_score = round(self.stats.score, -1) score_str = "{:,}".format(rounded_score) self.score_image = self.font.render( score_str, True, self.text_color, self.ai_setting.bg_color) self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def prep_high_score(self): high_score = int(round(self.stats.high_score, -1)) high_score_str = "{:,}".format(high_score) self.high_score_image = self.font.render( high_score_str, True, self.text_color, self.ai_setting.bg_color) self.high_score_rect = self.high_score_image.get_rect() self.high_score_rect.centerx = self.screen_rect.centerx self.high_score_rect.top = 20 def prep_level(self): self.level_image = self.font.render( str(self.stats.level), True, self.text_color, self.ai_setting.bg_color) self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_ships(self): self.ships = Group() for ship_number in range(self.stats.ships_left): ship = Ship(self.ai_setting, self.screen) ship.rect.x = 10 + ship_number * ship.rect.width ship.rect.y = 10 self.ships.add(ship)
def __init__(self, game_set, stats, screen): """Initialize the score attributes""" self.screen = screen self.screen_rect = screen.get_rect() self.stats = stats self.game_set = game_set #Font configurations self.text_color = (250, 250, 250) self.font = SysFont(None, 23) #Prepara the images of score board self.prep_images()
def __init__(self, game): self.settings = game.settings self.screen = game.screen self.stats = game.stats self.screen_rect = self.screen.get_rect() self.font = SysFont(None, 70) self.text_color = (255, 255, 255) self.score = self.stats.score self.best = 0 self.prep_score() self.prep_time()
def __init__(self, resourcemgr): super(Menu, self).__init__(resourcemgr) self.bg = resourcemgr.get_background_image(BACKGROUNDS.MAIN_MENU) self.bg_rect = self.bg.get_rect() font = SysFont(FONTS, int(48 * self.resourcemgr.scale), True) self.msg = font.render('RTS TEST 3000XX', 1, WHITE) self.msg_rect = self.msg.get_rect(centerx=self.bg_rect.w / 2, centery=self.bg_rect.h / 6) self.start = Button((self.bg_rect.w - 100) / 2, self.bg_rect.h * (7 / 10.0), BUTTONS.START, resourcemgr) self.edit = Button((self.bg_rect.w - 100) / 2, self.bg_rect.h * (4 / 5.0), BUTTONS.EDIT, resourcemgr)
def __init__(self, ai_setting, screen, msg): self.screen = screen self.screen_rect = screen.get_rect() self.width = 200 self.height = 50 self.button_color = (0, 255, 0) self.text_color = (255, 255, 255) self.font = SysFont(None, 48) self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center self.prep_msg(msg)
def __init__(self, resourcemgr, level=None): super(Editor, self).__init__(resourcemgr) self.tilemgr = TileManager(resourcemgr, level) self.lw = self.tilemgr.lw self.lh = self.tilemgr.lh self.camera = Camera(0, 0, self.lw, self.lh, resourcemgr) self.current_tile = 0 self.font = SysFont(FONTS, int(48 * self.resourcemgr.scale), True)
def render_fill(cls, text, font_info, surface): font = SysFont(font_info.name, font_info.size) font.set_bold(font_info.bold) font.set_italic(font_info.italic) words = text.split() word_surfaces = [] whitespace = font.render(" ", True, font_info.fcolor, font_info.bcolor) for word in words: word_surfaces.append(font.render(word, True, font_info.fcolor, font_info.bcolor)) sf_width = surface.get_width() line = [] line.free = sf_width lines = [line] max_height = max([surface.get_height() for surface in word_surfaces]) cur_height = max_height for sf in word_surfaces: if lines[-1].free == sf_width: assert(sf_width < sf.get_width()) lines[-1].append(sf) lines[-1].free -= sf.get_width() else: if sf.get_width() + whitespace.get_width() > lines[-1].free: lines[-1].append(sf) lines[-1].free -= sf.get_width() + whitespace.get_width() else: if (cur_height + (1 + font_info.spacing) * max_height < surface.get_width()): assert(sf_width < sf.get_width()) line = [] pass
class Hud(object): def __init__(self): self.hud = Surface((65, 70), SRCALPHA, 32) self.font = SysFont('Arial', 14) def draw(self, character, screen): self._clear() hp = character.hp.value ac = character.ac.get_value() xp = character.get_xp() hp_surface = self.font.render('HP: ' + str(hp), False, Color(255, 255, 255)) ac_surface = self.font.render('AC: ' + str(ac), False, Color(255, 255, 255)) xp_surface = self.font.render('XP: ' + str(xp), False, Color(255, 255, 255)) self.hud.blit(hp_surface, (10, 5)) self.hud.blit(ac_surface, (10, 25)) self.hud.blit(xp_surface, (10, 45)) screen.blit(self.hud, (950, 10)) def _clear(self): self.hud.fill(Color(255, 255, 0, 50))
class MyText(object): #传入screen以访问主屏幕 def __init__(self,screen,text_start_point=define.TEXT_START_POINT,font=define.TEXT_FONT,font_size=define.FONT_SIZE,): try: self.font = Font(font,font_size) except IOError: print "bad font file name or i/o error,sys will load default font" self.font = SysFont("simsunnsimsun",font_size,False,False) self.screen = screen self.text_start_point = text_start_point def get_text(self,text_content=""): #接受原始文字数据 self.text_content = text_content #字体显示,一次仅显示一行,通过多次显示来完成显示 def text_display(self,text_color=(0,0,0)): line_height = self.font.get_linesize() char_per_line = define.TEXT_SCREEN_SIZE[0]/line_height text_length = len(self.text_content) #print char_per_line,line_height,len(self.text_content) y = self.text_start_point[1] range_times = text_length/char_per_line #绘制文字背景 text_bg = pygame.image.load('ui/window.png').convert_alpha() self.screen.blit(text_bg,define.TEXT_WINDOW_POINT) #绘制文字 for i in xrange(range_times+1): #用切片保证文字正确换行 txt_in_line = self.text_content[i*char_per_line:(i+1)*char_per_line] if txt_in_line == "": break self.screen.blit(self.font.render(txt_in_line,True,text_color),(self.text_start_point[0],y)) y += line_height def selection_display(self,select_order,text_color=(0,0,0)): line_height = self.font.get_linesize() #这里的select_order从0开始,这个方法的目的在于绘制选项文字,为button类对象提供一个简单的文字绘制方法 self.screen.blit(self.font.render(self.text_content,True,text_color),(self.text_start_point[0],self.text_start_point[1]+line_height*select_order)) def display_by_speed(self,display_speed): #字体显示速度,用字的数量计,单位“字/0,1秒” self.speed = display_speed pass
def change_state(next_state, resourcemgr): resourcemgr.screen.fill(BLACK) font = SysFont(FONTS, int(48 * resourcemgr.scale), True) text = font.render('Loading...', 1, WHITE) textpos = text.get_rect(centerx=resourcemgr.screen.get_width() / 2, centery=resourcemgr.screen.get_height() / 4) resourcemgr.screen.blit(text, textpos) pygame.display.flip() current_state = None if next_state == STATES.INTRO: current_state = Intro(resourcemgr) elif next_state == STATES.MENU: current_state = Menu(resourcemgr) elif next_state == STATES.INGAME: current_state = InGame(resourcemgr, 0, os.path.join(resourcemgr.main_path, 'scenarios/test.ics')) elif next_state == STATES.EDITOR: current_state = Editor(resourcemgr) return current_state
def render_column(cls, lines, font_info, surface): font = SysFont(font_info.name, font_info.size) font.set_bold(font_info.bold) font.set_italic(font_info.italic) line_surfaces = [] for line in lines: line_surfaces.append(font.render(line, True, font_info.fcolor, font_info.bcolor)) max_height = max([sf.get_height() for sf in line_surfaces]) spacing = ((surface.get_height() - max_height * len(lines)) / (len(lines) + 1)) for sf, y in zip(line_surfaces, range(spacing, surface.get_height(), spacing + max_height)): surface.blit(sf, (0, y))
class Console(object): def __init__(self): self.console = Surface((600, 85), SRCALPHA, 32) self._clear_log() font.init() self.font = SysFont('Arial', 14) self.messages = [] def log(self, message): self.messages.append(message) def draw(self, screen): msgs = self.messages[-4:len(self.messages)] msgs.reverse() self._clear_log() i = 65 for msg in msgs: text_surface = self.font.render(msg, False, Color(255, 255, 255)) self.console.blit(text_surface, (10, i)) i -= 20 screen.blit(self.console, (20, 670)) def _clear_log(self): self.console.fill(Color(255, 255, 255, 50))
class Game(object): SCREEN_SIZE = (800, 600) FPS = 10 FONT = get_default_font() def __init__(self): self._initPygame() self.snake_group = pygame.sprite.Group() self.block_group = pygame.sprite.Group() self.clock = pygame.time.Clock() self.snake = Snake(self.snake_group) self.block = Block(Game.SCREEN_SIZE, self.block_group) self.game_over = False self.score = 0 def _initPygame(self): pygame.init() self.screen = pygame.display.set_mode(Game.SCREEN_SIZE) pygame.display.set_caption('Snake Game') self.game_font = SysFont(Game.FONT, 72) self.new_game_font = SysFont(Game.FONT, 48) self.score_font = SysFont(Game.FONT, 32) def newGame(self): self.snake_group.empty() self.block_group.empty() self.block = Block(Game.SCREEN_SIZE, self.block_group) self.snake = Snake(self.snake_group) self.game_over = False def render(self): self.snake.draw() self.screen.fill(BLACK) self.snake_group.draw(self.screen) self.block_group.draw(self.screen) self.displayScore() def displayScore(self): score_text = self.score_font.render("Score: %d" % self.score, 1, WHITE) self.screen.blit(score_text, (0, 0)) def handleInput(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) pressed_key = pygame.key.get_pressed() if pressed_key[K_LEFT]: self.snake.left() if pressed_key[K_RIGHT]: self.snake.right() if pressed_key[K_UP]: self.snake.up() if pressed_key[K_DOWN]: self.snake.down() def gameOver(self): self.score = 0 game_over_text = self.game_font.render('Game Over', 1, RED) new_game_text = self.new_game_font.render( 'Press Enter to new game', 1, RED) self.screen.blit(game_over_text, (250, 250)) self.screen.blit(new_game_text, (200, 300)) pressed_key = pygame.key.get_pressed() if pressed_key[K_RETURN]: self.newGame() def run(self): while True: self.handleInput() if any([self.snake.collidesItSelf(), self.snake.outOfTheScreen()]): self.gameOver() else: if self.snake.collidesWithBlock(self.block): self.score += 10 self.block.group.remove(self.block) self.block = Block(Game.SCREEN_SIZE, self.block_group) self.render() pygame.display.flip() self.clock.tick(Game.FPS)
def _draw_item_quantity(self, screen, slot, quantity): quantity_surface = SysFont('Arial', 12, bold=True).render(str(quantity), False, self.SLOT_FONT_COLOR) screen.blit(quantity_surface, (self._item_quantity_pos(quantity_surface.get_size(), slot)))
def __init__(self): self.hud = Surface((65, 70), SRCALPHA, 32) self.font = SysFont('Arial', 14)
def __init__(self): self.console = Surface((600, 85), SRCALPHA, 32) self._clear_log() font.init() self.font = SysFont('Arial', 14) self.messages = []
class Editor(State): def __init__(self, resourcemgr, level=None): super(Editor, self).__init__(resourcemgr) self.tilemgr = TileManager(resourcemgr, level) self.lw = self.tilemgr.lw self.lh = self.tilemgr.lh self.camera = Camera(0, 0, self.lw, self.lh, resourcemgr) self.current_tile = 0 self.font = SysFont(FONTS, int(48 * self.resourcemgr.scale), True) def set_tile(self): x, y = mouse.get_pos() x += self.camera.rect.x y += self.camera.rect.y for t in self.tilemgr.tiles: if t.rect.collidepoint(x, y): t.set_tile(self.current_tile) break def get_tile(self): x, y = mouse.get_pos() x += self.camera.rect.x y += self.camera.rect.y for t in self.tilemgr.tiles: if t.rect.collidepoint(x, y): self.current_tile = t.kind break def render_kind(self): text = "Current Tile: %s" % self.tilemgr.tile_labels[self.current_tile] msg = self.font.render(text, 1, WHITE) msg_rect = msg.get_rect( centerx=self.resourcemgr.screen.get_rect().w / 2, centery=self.resourcemgr.screen.get_rect().h / 6 ) self.resourcemgr.screen.blit(msg, msg_rect) def input(self, event, next_state): next_state = super(Editor, self).input(event, next_state) self.camera.input(event) if event.type == KEYDOWN: if event.key == K_ESCAPE: self.tilemgr.save_tiles("map1.map") next_state = set_next_state(next_state, STATES.MENU) elif event.type == MOUSEBUTTONDOWN: if event.button == MOUSE.LEFT: self.set_tile() elif event.button == MOUSE.RIGHT: self.get_tile() elif event.button == MOUSE.WHEELUP: self.current_tile -= 1 if self.current_tile < 0: self.current_tile = self.tilemgr.total_tile_kinds - 1 elif event.button == MOUSE.WHEELDOWN: self.current_tile += 1 if self.current_tile > self.tilemgr.total_tile_kinds - 1: self.current_tile = 0 elif event.type == MOUSEMOTION and mouse.get_pressed()[0]: self.set_tile() return next_state def logic(self, clock, next_state): self.camera.logic(clock.get_time()) return next_state def render(self): self.resourcemgr.screen.fill(BLACK) self.tilemgr.render(self.camera) self.render_kind()