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 __init__(self): self.gameSurf = display.get_surface().copy() self.drawWindow = display.get_surface() backgroundColor = (31, 97, 141, 150) title = SysFont('lucidaconsole', 35) subtitle = SysFont('lucidaconsole', 25) #distance between title and subtitle text textMargin = 10 #distance between edge of text and full opacity background textBackgroundMargin = 10 self.titleSurf = title.render("Cheat mode", True, Color('black')) self.subtitleSurf = subtitle.render("Click to exit", True, Color('black')) self.textBackgroundSurf = surface.Surface( (self.subtitleSurf.get_width() + 2 * textBackgroundMargin + 75, self.titleSurf.get_height() + self.subtitleSurf.get_height() + textMargin + 2 * textBackgroundMargin + 25), constants.SRCALPHA) self.textBackgroundSurf.fill(backgroundColor) self.titlePos = (self.drawWindow.get_width() / 2 - self.titleSurf.get_width() / 2, self.drawWindow.get_height() / 2 - self.titleSurf.get_height() - textMargin / 2) self.subtitlePos = (self.drawWindow.get_width() / 2 - self.subtitleSurf.get_width() / 2, self.drawWindow.get_height() / 2 + textMargin / 2) self.textBackgroundPos = (self.drawWindow.get_width() / 2 - self.textBackgroundSurf.get_width() / 2, self.drawWindow.get_height() / 2 - self.textBackgroundSurf.get_height() / 2)
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
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')
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)
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 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 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))
class Button: """A class that represents a button""" def __init__(self, game_set, screen, msg): """Starts the attributes of the button""" self.screen = screen self.screen_rect = screen.get_rect() #Define dimension and properties of the button self.width, self.height = 500, 50 #self.width, self.height = 200, 50 == self.width = 200 #self.height = 50 self.button_color = (0, 175, 0) self.text_color = (255, 255, 255) self.font = SysFont(None, 48) #Creating the rect object of the button and putting it in the center of the screen self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center #The message must be prepared only once self.prep_msg(msg) def prep_msg(self, msg): """Transform the string in a image and centralize the text in the button""" #render() will create an image with the string self.msg_image = self.font.render(msg, True, self.text_color, self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = self.rect.center def draw_button(self): """Draws a button in white, and following that, draws the message""" self.screen.fill(self.button_color, self.rect) self.screen.blit(self.msg_image, self.msg_image_rect)
class Button(object): """游戏的开始按钮""" def __init__(self, ai_settings, screen, msg): self.screen = screen self.ai_settings = ai_settings self.screen_rect = self.screen.get_rect() # 设置按钮各种属性 self.width, self.height = 100, 25 self.button_color = (0, 250, 0) self.text_color = (255, 255, 255) self.text_font = SysFont(None, 24) # 画出按钮 self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center # 将按钮上的文字渲染为图片,并将其与按钮居中对齐 self.text_image = self.text_font.render(msg, True, self.text_color, self.button_color) self.text_image_rect = self.text_image.get_rect() self.text_image_rect.center = self.rect.center def draw(self): """绘制""" # 绘制按钮外形 self.screen.fill(self.button_color, self.rect) # 绘制被渲染过的文字图片 self.screen.blit(self.text_image, self.text_image_rect)
class Button: def __init__(self, screen, msg): """Инициализирует атрибуты кнопки.""" self.screen = screen self.screen_rect = screen.get_rect() # Назначение размеров и свойств кнопок. self.width, self.height = 200, 50 self.button_color = (100, 255, 100) self.text_color = (255, 255, 255) self.font = SysFont(None, 48) # Построение объекта rect кнопки и выравнивание по центру экрана. self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center # Сообщение кнопки создается только один раз. self.prep_msg(msg) def prep_msg(self, msg): """Преобразует msg в прямоугольник и выравнивает текст по центру.""" self.msg_image = self.font.render(msg, True, self.text_color, self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = self.rect.center def draw_button(self): # Отображение пустой кнопки и вывод сообщения. self.screen.fill(self.button_color, self.rect) self.screen.blit(self.msg_image, self.msg_image_rect)
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)]
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 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)
class Button(): 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 prep_msg(self, msg): self.msg_image = self.font.render( msg, True, self.text_color, self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = self.rect.center def draw_button(self): self.screen.fill(self.button_color, self.rect) self.screen.blit(self.msg_image, self.msg_image_rect)
def show(self): screen = display.get_surface() draw.rect(screen, self._color, (self._x, self._y, self._width, self._height)) if not self.__controller.stopped: cell_x = self._x cell_y = self._y for line in self.__model.data: for cell in line: if cell == 1: draw.rect(screen, self.__living_cell_color, (cell_x, cell_y, self.__cell_size, self.__cell_size)) cell_x = cell_x + self.__cell_size cell_y = cell_y + self.__cell_size cell_x = self._x for child in self._children: child.show() else: font = SysFont('', 60) current_strategy_text = self.__current_strategy_text + self.__controller.strategy welcome_text = font.render(self.__welcome_message, True, PG_COLORS.get('white')) current_strategy = font.render(current_strategy_text, True, PG_COLORS.get('white')) instruction_text = font.render(self.__instruction_text, True, PG_COLORS.get('white')) text_width, text_height = font.size(self.__welcome_message) cs_text_width, cs_text_height = font.size(current_strategy_text) i_text_width, i_text_height = font.size(self.__instruction_text) screen.blit(welcome_text, (self._x + self._width / 2 - text_width / 2, self._y + self._height / 2 - text_height * 2.5)) screen.blit(instruction_text, (self._x + self._width / 2 - i_text_width / 2, self._y + self._height / 2 - text_height)) screen.blit(current_strategy, (self._x + self._width / 2 - cs_text_width / 2, self._y + self._height / 2 + text_height / 2))
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)
class Text(Component): def __init__(self, container, text="", fontType="", x=0, y=0, textSize=0, color=COLORS.WHITE, onActivate=None): self.text = text self.textSize = textSize self.color = color self.font = SysFont(fontType, self.textSize) self.size = self.font.size(self.text) self.surface = self.font.render(self.text, True, self.color) super().__init__(container, x, y, self.size, surface=self.surface, onActivate=onActivate) def setColor(self, color): color = [a if a < 255 else 255 for a in color] color = [a if a > 0 else 0 for a in color] self.color = color self.update() def setText(self, text): self.text = text self.update() def getText(self): return self.text def update(self): self.surface = self.font.render(self.text, True, self.color) self.rect = self.surface.get_rect() def select(self): self.setColor(COLORS.GREY) def unSelect(self): self.setColor(COLORS.BLACK)
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)
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))
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 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)
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 __init__(self, gameWon): self.gameSurf = display.get_surface().copy() self.drawWindow = display.get_surface() self.transparentSurf = surface.Surface( display.get_surface().get_size(), constants.SRCALPHA) color = (0, 255, 0, 127) if gameWon else (255, 0, 0, 127) text = "You Won!" if gameWon else "You Lost..." backgroundColor = (0, 255, 0) if gameWon else (255, 0, 0) title = SysFont('lucidaconsole', 25) subtitle = SysFont('lucidaconsole', 15) #distance between title and subtitle text textMargin = 10 #distance between edge of text and full opacity background textBackgroundMargin = 10 self.transparentSurf.fill(color) self.titleSurf = title.render(text, True, Color('black')) self.subtitleSurf = subtitle.render("Click to play again", True, Color('black')) self.textBackgroundSurf = surface.Surface( (self.subtitleSurf.get_width() + 2 * textBackgroundMargin, self.titleSurf.get_height() + self.subtitleSurf.get_height() + textMargin + 2 * textBackgroundMargin)) self.textBackgroundSurf.fill(backgroundColor) self.titlePos = (self.drawWindow.get_width() / 2 - self.titleSurf.get_width() / 2, self.drawWindow.get_height() / 2 - self.titleSurf.get_height() - textMargin / 2) self.subtitlePos = (self.drawWindow.get_width() / 2 - self.subtitleSurf.get_width() / 2, self.drawWindow.get_height() / 2 + textMargin / 2) self.textBackgroundPos = (self.drawWindow.get_width() / 2 - self.textBackgroundSurf.get_width() / 2, self.drawWindow.get_height() / 2 - self.textBackgroundSurf.get_height() / 2)
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 blit_cns_selection(self): v = self.ui_vars font = Font(self.CORE.font_family, self.CORE.fonts['obj_name'][0]) of_x, of_y = v.csel_ofx, v.csel_ofy cntr_w = v.disp_w - 2*v.cns_ss text = '' # Selection attrs / list if len(self.selection) == 1: text = self.TEXT.objects[self.selection[0].objkey] if self.debug: text += self.selection[0].get_address() index = 0 for key, value in self.selection[0].get_attrs().items(): icon = self.gfx.icons[key] vtext = font.render(str(value), False, self.colors.white) y = of_y + index*(v.cicos+v.cspc) self.screen.blit(icon, (of_x, y)) self.screen.blit(vtext, (of_x+v.cicos+v.cspc, y)) index += 1 elif len(self.selection) > 1: text = str(len(self.selection))+self.TEXT.obj_count_suffix sect_w = v.csel_cols*(v.cicos+v.csel_spc)-v.csel_spc i = 0 for obj in self.selection: texture = self.gfx.grayed[obj.objkey] x = (i% v.csel_cols) * (v.cicos+v.csel_spc) y = (i//v.csel_cols) * (v.cicos+v.csel_spc) x = x + cntr_w//2 + v.cns_ss - sect_w//2 y = y + v.disp_h - v.cns_ch + 2*v.csel_spc + v.csel_th self.screen.blit(texture, (x,y)) i += 1 if i > v.csel_cols * v.csel_rows: break # Selection main text text = font.render(text, False, self.colors.white) crect = text.get_rect() crect.top = v.disp_h - v.cns_ch crect.centerx = cntr_w//2 + v.cns_ss self.screen.blit(text, crect)
class Label(Node): def __init__(self, text, relative_x=0, relative_y=0, font_color=DEFAULT_FONT_COLOR, font_name=DEFAULT_FONT_NAME, font_size=DEFAULT_FONT_SIZE, ): super().__init__(relative_x, relative_y) self.text = text self.font_color = font_color self.font_name = font_name self.font_size = font_size self.font = SysFont(self.font_name, self.font_size) self.surface = self.font.render(self.text, True, self.font_color) def update(self): super().update() self.font = SysFont(self.font_name, self.font_size) self.surface = self.font.render(self.text, True, self.font_color) def draw(self, screen): screen.blit(self.surface, (self.x, self.y)) def get_width(self): return self.surface.get_width() def get_height(self): return self.surface.get_height() def is_colliding(self, pos): return pos[0] in range( self.x, self.x + self.get_width() ) and pos[1] in range( self.y, self.x + self.get_height() )
def __init__(self, text, position, next_scene, clicked_event=USEREVENT, *groups): super(Button, self).__init__(*groups) font = SysFont('tahoma', 32) self.name = text self.image = font.render(text, True, (255, 255, 255)) self.rect = self.image.get_rect() self.rect.center = position self.event = clicked_event self.next_scene = next_scene
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 Debug: surface: Surface tps: TimeTracker font: Font def __init__(self) -> None: self.tps = TimeTracker(perf_counter_ns) pass def set_surface(self, surface: Surface) -> None: self.font = SysFont(None, 25) self.surface = surface def draw_tps(self) -> None: image = self.font.render("TPS: " + str(self.tps.fps()), True, (255, 255, 255)) self.surface.blit(image, image.get_rect()) self.tps.tick()
def draw_text(surface, color, text, position, size, anchor=''): global font # if font is None or size > 256: font = SysFont('consolas', size * 3 // 4) textobj = font.render(text, 1, color) textrect = textobj.get_rect() if anchor == 'bottomleft': textrect.bottomleft = position elif anchor == 'topleft': textrect.topleft = position elif anchor == 'bottomright': textrect.bottomright = position elif anchor == 'topright': textrect.topright = position else: textrect.center = position surface.blit(textobj, textrect) return textrect
class Widget: def __init__(self, **kwargs): self.rect = Rect(kwargs.get('x', 0), kwargs.get('y', 0), kwargs.get('width', 200), kwargs.get('height', 50)) self.image = Surface((self.rect.width, self.rect.height)) self.background_image = kwargs.get('background_image', 0) self.background_image_pos = kwargs.get('background_image_pos', (0, 0)) self.background_color = kwargs.get('background_color', (32, 32, 32)) self.background_color_cover = kwargs.get('background_color_cover', self.background_color) self.background_color_click = kwargs.get('background_color_click', self.background_color) self.text = kwargs.get('text', '') self.font_size = kwargs.get('font_size', 20) self.font_color = kwargs.get('font_color', (255, 255, 255)) self.font_pos = kwargs.get('font_pos', None) self.font = SysFont('segoeui', self.font_size, 1) self.image.fill(self.background_color) self.onclick = kwargs.get('onclick', lambda: None) def show(self, surface): if self.background_image: self.image.blit(self.background_image, self.background_image_pos) font = self.font.render(self.text, 1, self.font_color) pos = self.font_pos or [ (self.rect.width - font.get_rect().width) // 2, (self.rect.height - font.get_rect().height) // 2 ] self.image.blit(font, pos) surface.blit(self.image, (self.rect.x, self.rect.y)) def _onclick(self): self.onclick() def update(self, events): if self.rect.collidepoint(*get_mouse_pos()) and get_mouse_pressed()[0]: self.image.fill(self.background_color_click) elif self.rect.collidepoint(*get_mouse_pos()): self.image.fill(self.background_color_cover) for event in events: if event.type == MOUSEBUTTONUP: self._onclick() else: self.image.fill(self.background_color)
class Statusbar(Sprite): padding = 8 font = 'Ubuntu Light' font_size = 22 foreground_color = (250,250,160) background_color = (0,0,12) 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 clear(self): self.image.fill(self.background_color) def write(self, text, color=None): self.text = text if color is not None: self.foreground_color = color self._update() def append(self, text): self.text = self.text + text self._update() def _update(self): self.clear() self.image.blit( self.font.render(self.text, True, self.foreground_color), (self.padding, self.padding) )
class ScoreBoard(object): """几分面板类""" 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 pre_socre(self): self.text_img = self.text_font.render(str(self.game_stats.score), True, self.text_color, self.ai_settings.bg_color) self.text_img_rect = self.text_img.get_rect() self.text_img_rect.right = self.screen_rect.right - 10 self.text_img_rect.top = 5 def blitme(self): self.pre_socre() self.screen.blit(self.text_img, self.text_img_rect)
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 display(self, g): g.win().blit(self.background, (self.x - self.offsetX, self.y - self.offsetY)) g.win().blit(self.talker.pic, (self.x - self.offsetX, self.y - self.offsetY)) w = self.talker.pic.get_width() x_text, y_text = self.x + w + 10, self.y + 5 font = SysFont("arial_unicode_ms", 40) words = [line.split(" ") for line in self.msg.splitlines()] space = font.size(' ')[0] for line in words: for word in line: word_surface = font.render(word, 1, (0, 0, 0)) word_width, word_height = word_surface.get_size() if x_text + word_width + self.offsetX >= self.background.get_width( ) + self.x: x_text = self.x + w + 10 # Reset the x. y_text += word_height # Start on new row. g.win().blit(word_surface, (x_text, y_text)) x_text += word_width + space x_text = self.x + w + 10 # Reset the x. y_text += word_height # Start on new row.
class Button: """ A button at the center of the screen """ 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 _render_msg(self, msg): self._msg_image = self._font.render(msg, True, self._settings.btn_txt_color) self._msg_image_rect = self._msg_image.get_rect() self._msg_image_rect.center = self.rect.center def draw(self): self._screen.fill(self._settings.btn_color, self.rect) self._screen.blit(self._msg_image, self._msg_image_rect)
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 Window: # A Window represents a display window with a title bar, # close box and interior drawing surface. def __init__(self, title, width, height): # Create and open a window to draw in. # - self is the new Window # - title is the str title of the window # - width is the int pixel width of the window # - height is the int pixel height of the window init() self.__surface__ = set_mode((width, height), 0, 0) set_caption(title) self.__font_name__ = '' self.__font_size__ = 18 self.__font__ = SysFont(self.__font_name__, self.__font_size__, True) self.__font_color__ = 'white' self.__bg_color__ = 'black' self.__auto_update__ = True try: self.stream = Stream() self.stream.start() except: pass def close(self): # Close the window # - self is the Window self.stream.stop() quit() 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 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 set_font_color(self, color_string): # Set the font color used to draw in the window # - self is the Window # - color_string is the str name of the font color self.__font_color__ = color_string def set_bg_color(self, color_string): # Set the background color used to draw in the window # - self is the Window # - color_string is the str name of the background color self.__bg_color__ = color_string def set_auto_update(self, true_false): # Set the background color used to draw in the window # - self is the Window # - true_or_false is a Boolean indicating if auto update should be on or off self.__auto_update__ = true_false def get_font_height(self): # Return the int pixel height of the current font. # - self is the Window return self.__font__.size('')[1] def get_font_color(self): # Return a str that represents the current window # font color # - self is the Window return self.__font_color__ def get_bg_color(self): # Return a str that represents the current window # background color # - self is the Window return self.__bg_color__ def set_bg_image(self, image_png, width, height): image = pygame.image.load(image_png) image = pygame.transform.scale(image, (self.get_width(), self.get_height())) self.__surface__.blit(image, [0, 0]) def get_width(self): # Return the int pixel width of the window's drawable # interior surface # - self is the Window return self.__surface__.get_width() def get_height(self): # Return the int pixel height of the window's drawable # interior surface # - self is the Window return self.__surface__.get_height() def clear(self): # Erase the window contents # - self is the Window if self.__auto_update__: update() def get_surface(self): # Return the Pygame.Surface object that represents the # interior drawing surface of the window # - self is the Window return self.__surface__ def draw_string(self, string, x, y, bg): # Draw a string in the window using the current font and # colors # - self is the Window # - string is the str object to draw # - x is the int x coord of the upper left corner of the # string in the window # - y is the int y coord of the upper left corner of the # string in the window text_image = self.__font__.render(string, True, Color(self.__font_color__), bg) self.__surface__.blit(text_image, (x, y)) if self.__auto_update__: text_rect = Rect((x, y), text_image.get_size()) update(text_rect) def input_string(self, prompt, x, y): # Draw a prompt string in the window using the current font # and colors. Check keys pressed by the user until an enter # key is pressed and return the sequence of key presses as a # str object. # - self is the Window # - prompt is the str to display # - x is the int x coord of the upper left corner of the # string in the window # - y is the int y coord of the upper left corner of the # string in the window key = K_SPACE answer = '' while key != K_RETURN: self.draw_string(prompt + answer + ' ', x, y) if not self.__auto_update__: update() key = self._get_key() key_state = get_pressed() if (K_SPACE <= key <= K_z): if key == K_SPACE: letter = ' ' else: letter = name(key) if key_state[K_LSHIFT] or key_state[K_RSHIFT] or key_state[ K_CAPSLOCK]: letter = letter.upper() answer = answer + letter if key == K_BACKSPACE: answer = answer[0:len(answer) - 1] return answer def get_string_width(self, string): # Return the int pixel width of the string using the current # font. # - self is the Window # - string is the str object return self.__font__.size(string)[0] def update(self): # Update the window by copying all drawn objects from the # frame buffer to the display. # - self is the Window update() def _get_key(self): # Poll the events until the user presses a key and return it. # Discard all other events. # - self is the Window event = poll() while event.type != KEYUP: event = poll() return event.key
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)
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()