我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pygame.font()。
def ask(screen, question): "ask(screen, question) -> answer" pygame.font.init() current_string = [] display_box(screen, question + ": " + "".join(current_string)) while 1: inkey = get_key() if inkey == K_BACKSPACE: current_string = current_string[0:-1] elif inkey == K_RETURN: break elif inkey == K_MINUS: current_string.append("_") elif inkey <= 127: current_string.append(chr(inkey)) display_box(screen, question + ": " + "".join(current_string)) return "".join(current_string)
def __init__(self, colour, pos, text, handler=None, rectSize=None): if rectSize == None: image = pygame.image.load("assets/button.png").convert() size = (image.get_rect().width, image.get_rect().height) else: size = rectSize image = pygame.Surface(rectSize).convert() image.fill(colour) self.colour = colour self.image = image font = Font("assets/swiss911.ttf", 19) textImage = font.render(text, False, colours.BLACK) image.blit(textImage, (image.get_rect().width - textImage.get_rect().width - 10, image.get_rect().height - textImage.get_rect().height - 5)) LcarsWidget.__init__(self, colour, pos, size, handler) self.applyColour(colour) self.highlighted = False self.beep = Sound("assets/audio/panel/202.wav")
def buildlist(self): clr = 220, 230, 240 clr2 = 140, 150, 160 offsetx, offsety = 240, 30 self.clearlist() font = fonts[0][0] self.gamelist = [] cur = 0 for opt in Options: if self.current == cur: c = clr else: c = clr2 imgpos = font.text(c, opt, (offsetx, offsety), "midleft") self.gamelist.append(imgpos) offsety += 33 cur += 1
def textlined(self, color, text, center=None, pos='center'): darkcolor = [int(c//2) for c in color] if text is None: text = ' ' try: if gfx.surface.get_bytesize()>1: img1 = self.font.render(text, 1, color) img2 = self.font.render(text, 1, darkcolor) else: img1 = img2 = self.font.render(text, 0, color) img2 = self.font.render(text, 0, darkcolor) except (pygame.error, TypeError): img1 = img2 = pygame.Surface((10, 10)) newsize = img1.get_width()+4, img1.get_height()+4 img = pygame.Surface(newsize) img.blit(img2, (0, 0)) img.blit(img2, (0, 4)) img.blit(img2, (4, 0)) img.blit(img2, (4, 4)) img.blit(img1, (2, 2)) img = img.convert() img.set_colorkey((0,0,0), pygame.RLEACCEL) r = self._positionrect(img, center, pos) return [img, r]
def textshadowed(self, color, text, center=None, pos='center'): darkcolor = [int(c//2) for c in color] if text is None: text = ' ' try: if gfx.surface.get_bytesize()>1: img1 = self.font.render(text, 1, color) img2 = self.font.render(text, 1, darkcolor) else: img1 = img2 = self.font.render(text, 0, color) img2 = self.font.render(text, 0, darkcolor) except (pygame.error, TypeError): img1 = img2 = pygame.Surface((10, 10)) newsize = img1.get_width()+2, img1.get_height()+2 img = pygame.Surface(newsize) img.blit(img2, (2, 2)) img.blit(img1, (0, 0)) img = img.convert() img.set_colorkey((0,0,0), pygame.RLEACCEL) r = self._positionrect(img, center, pos) return [img, r]
def __init__(self): pygame.sprite.Sprite.__init__(self) self.font = pygame.font.Font(None, 20) self.font.set_italic(1) self.color = Color('white') self.lastscore = -1 self.update() self.rect = self.image.get_rect().move(10, 450)
def update(self): if SCORE != self.lastscore: self.lastscore = SCORE msg = "Score: %d" % SCORE self.image = self.font.render(msg, 0, self.color)
def __init__(self): # Resolution self.width = 800 self.height = 600 self.resolution = (self.width,self.height) #self.fullscreen = pygame.FULLSCREEN pygame.init() # Makes pygame work # Set the resolution self.screen = pygame.display.set_mode(self.resolution) # Set Title self.caption = pygame.display.set_caption('Main Menu') # Set default font self.font = pygame.font.Font(None, 30) self.Rects = Rects(self)
def display_box(screen, message): "Print a message in a box in the middle of the screen" fontobject = pygame.font.Font(None,18) pygame.draw.rect(screen, (0,0,0), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10, 200,20), 0) pygame.draw.rect(screen, (255,255,255), ((screen.get_width() / 2) - 102, (screen.get_height() / 2) - 12, 204,24), 1) if len(message) != 0: screen.blit(fontobject.render(message, 1, (255,255,255)), ((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10)) pygame.display.flip()
def system_checks(): # do system checks if not pygame.font: logger.error('Error: Fonts disabled') sys.exit(False) if not pygame.mixer: logger.error('Error: Sound disabled') sys.exit(False)
def __init__(self, colour, pos, message, size=1.0, background=None, handler=None): self.colour = colour self.background = background self.font = Font("assets/swiss911.ttf", int(19.0 * size)) self.renderText(message) # center the text if needed if (pos[1] < 0): pos = (pos[0], 400 - self.image.get_rect().width / 2) LcarsWidget.__init__(self, colour, pos, None, handler)
def renderText(self, message): if (self.background == None): self.image = self.font.render(message, True, self.colour) else: self.image = self.font.render(message, True, self.colour, self.background)
def checkdependencies(): "only returns if everything looks ok" msgs = [] #make sure this looks like the right directory if not os.path.isdir(CODEDIR): msgs.append('Cannot locate SolarWolf modules') if not os.path.isdir('data'): msgs.append('Cannot locate SolarWolf data files') #first, we need python >= 2.1 if int(sys.version[0]) < 2: errorbox('Requires Python-2.1 or Greater') #is correct pygame found? try: import pygame if pygame.ver < '1.5.6': msgs.append('Requires Pygame-1.5.6 or Greater, You Have ' + pygame.ver) except ImportError: msgs.append("Cannot import Pygame, install version 1.5.6 or higher") pygame = None #check that we have FONT and IMAGE if pygame: if not pygame.font: msgs.append('Pygame requires the SDL_ttf library, not available') if not pygame.image or not pygame.image.get_extended(): msgs.append('Pygame requires the SDL_image library, not available') if msgs: msg = '\n'.join(msgs) errorbox(msg) #Pretty Error Handling Code...
def __pygamebox(title, message): try: import pygame pygame.quit() #clean out anything running pygame.display.init() pygame.font.init() screen = pygame.display.set_mode((460, 140)) pygame.display.set_caption(title) font = pygame.font.Font(None, 18) foreg, backg, liteg = (0, 0, 0), (180, 180, 180), (210, 210, 210) ok = font.render('Ok', 1, foreg, liteg) okbox = ok.get_rect().inflate(200, 10) okbox.centerx = screen.get_rect().centerx okbox.bottom = screen.get_rect().bottom - 10 screen.fill(backg) screen.fill(liteg, okbox) screen.blit(ok, okbox.inflate(-200, -10)) pos = [10, 10] for text in message.split('\n'): if text: msg = font.render(text, 1, foreg, backg) screen.blit(msg, pos) pos[1] += font.get_height() pygame.display.flip() stopkeys = pygame.K_ESCAPE, pygame.K_SPACE, pygame.K_RETURN, pygame.K_KP_ENTER while 1: e = pygame.event.wait() if e.type == pygame.QUIT or \ (e.type == pygame.KEYDOWN and e.key in stopkeys) or \ (e.type == pygame.MOUSEBUTTONDOWN and okbox.collidepoint(e.pos)): break pygame.quit() except pygame.error: raise ImportError
def rendertext(self, font, text): return fonts[font][0].text(fonts[font][1], text)
def initialize(): pygame.font.init() return 1
def render(self, *args): return self.font.render(*args)
def set_underline(self, *args): return self.font.set_underline(*args)
def set_italic(self, *args): return self.font.set_italic(*args)
def set_bold(self, *args): return self.font.set_bold(*args)
def get_height(self): return self.font.get_height()
def text(self, color, text, center=None, pos='center', bgd=(0,0,0)): if text is None: text = ' ' try: if gfx.surface.get_bytesize()>1: img = self.font.render(text, 1, color, bgd) img.set_colorkey(bgd, pygame.RLEACCEL) else: img = self.font.render(text, 0, color) except (pygame.error, TypeError): img = pygame.Surface((10, 10)) img = img.convert() r = self._positionrect(img, center, pos) return [img, r]
def textbox(self, color, text, width, bgcolor, topmargin=6): sidemargin = 6 lines = [] for line in text.splitlines(): cursize = 0 build = '' for word in line.split(): wordspace = word + ' ' size = self.font.size(wordspace)[0] if size + cursize >= width: lines.append(build) cursize = size build = wordspace else: build += wordspace cursize += size lines.append(build) lineheight = self.font.get_linesize() height = len(lines) * lineheight + topmargin + sidemargin width += sidemargin * 2 surf = pygame.Surface((width, height)) surf.fill(bgcolor) pos = topmargin for line in lines: if line: img = self.font.render(line, 1, color, bgcolor) img.set_colorkey(bgcolor) surf.blit(img, (sidemargin, pos)) pos += lineheight return surf
def __pygame(title, message): try: import pygame, pygame.font pygame.quit() #clean out anything running pygame.display.init() pygame.font.init() screen = pygame.display.set_mode((460, 140)) pygame.display.set_caption(title) font = pygame.font.Font(None, 18) foreg = 0, 0, 0 backg = 200, 200, 200 liteg = 255, 255, 255 ok = font.render('Ok', 1, foreg) screen.fill(backg) okbox = ok.get_rect().inflate(20, 10) okbox.centerx = screen.get_rect().centerx okbox.bottom = screen.get_rect().bottom - 10 screen.fill(liteg, okbox) screen.blit(ok, okbox.inflate(-20, -10)) pos = [20, 20] for text in message.split('\n'): msg = font.render(text, 1, foreg) screen.blit(msg, pos) pos[1] += font.get_height() pygame.display.flip() while 1: e = pygame.event.wait() if (e.type == pygame.QUIT or e.type == pygame.MOUSEBUTTONDOWN or pygame.KEYDOWN and e.key in (pygame.K_ESCAPE, pygame.K_SPACE, pygame.K_RETURN)): break pygame.quit() except pygame.error: raise ImportError
def __init__(self, pos, geometry, font): self.pos = pos self.geometry = geometry self.font = font
def setScreen(self, screen, sysRes, sysVar): enderAPI.FormWidget.setScreen(self, screen, sysRes, sysVar) self.fontobj = self.fonts[self.font] self.getAllMouseEvents = True self.current_string = [] self.completeHandler = None self.completed = False self.selected = False
def __init__(self, x, y, width, height, text = "", font = defaultFont): """ Initialisation of a TextWidget parameters: int x-coordinate of the TextWidget (left) int y-coordinate of the TextWidget (top) int width of the TextWidget int height of the TextWidget string test of the TextWidget pygame.font.Font font of the TextWidget return values: - """ super(TextWidget, self).__init__(x, y, width, height) self._text = text self._font = font
def setFont(self, font): """ Set the TextWidget's text parameters: pygame.font.Font the Font to be set return values: TextWidget TextWidget returned for convenience """ if isinstance(font, fnt.Font): self._font = font self.markDirty() return self
def getFont(self): """ Return the TextWidget's font parameters: - return values: pygame.font.Font the TextWidget's font """ return self._font
def printInfo(self, label, value, xlocation, ylocation, debug = False): """ Prints information about what is currently going on in the dealership """ self.screen.blit(self.background, (0, 0)) if pygame.font: font = pygame.font.Font(None, 20) text = font.render(label + " %s" % value , 1, (255, 0, 0)) textpos = text.get_rect(left = xlocation, bottom = ylocation) self.screen.blit(text, textpos) pygame.display.update(textpos) if debug: print label, value, xlocation, ylocation
def text_objects(self, text, font): textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect()
def button(self, msg,x,y,w,h,action=None): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() #print(click) if x+w > mouse[0] > x and y+h > mouse[1] > y: pygame.draw.rect(self.screen, blue,(x,y,w,h)) if click[0] == 1 and action != None: action() else: pygame.draw.rect(self.screen, green, (x,y,w,h)) smallText = pygame.font.SysFont("comicsansms",20) textSurf, textRect = self.text_objects(msg, smallText) textRect.center = ( (x+(w/2)), (y+(h/2)) ) self.screen.blit(textSurf, textRect)
def printInfo(self, label, value, xlocation, ylocation, debug = False): """ Prints information about what is currently going on in the dealership """ self.screen.blit(self.background, (0, 0)) if pygame.font: font = pygame.font.Font(None, 36) text = font.render(label + " %s" % value , 1, (255, 0, 0)) textpos = text.get_rect(left = xlocation, top = ylocation) self.screen.blit(text, textpos) pygame.display.update(textpos) if debug: print label, value, xlocation, ylocation
def __init__(self): pygame.init() self.font = pygame.font.SysFont('Arial', 18) pygame.display.set_caption('Box Test') self.screen = pygame.display.set_mode((WIDTH,HEIGHT), 0, 32) self.screen.fill((white)) self.draw_grid_flag=True pygame.display.update()
def show_score(self): curser=10 self.rect = pygame.draw.rect(self.screen, (grey), (0,600 , WIDTH, 100)) for team in team_names: self.screen.blit(self.font.render(team, True, (255,0,0)), (curser, 610)) curser+=WIDTH/6 curser=10 for score in team_scores: self.screen.blit(self.font.render(str(score), True, (255,0,0)), (curser, 640)) curser+=WIDTH/6
def addText(self,pos,text): # print(pos,text) x = pos[0]*WIDTH/6+10 y= 100*pos[1]+35 color = red # print('Y',y) if y<100: color=yellow self.screen.blit(self.font.render(str(text), True, color), (x, y))
def __init__(self): pygame.init() self.font = pygame.font.SysFont('Open Sans', 32) pygame.display.set_caption('Box Test') self.screen = pygame.display.set_mode((WIDTH,HEIGHT+200), 0, 32) self.screen.fill((white)) pygame.display.update()
def show(self,q): # curser=0 self.rect = pygame.draw.rect(self.screen, (black), (0, 0, WIDTH, HEIGHT)) sizeX, sizeY = self.font.size(q) if (sizeX>WIDTH): print("TEXT TOOO LONG!!!") print('SHOW QUESTION:',r,c) self.screen.blit(self.font.render(q, True, (255,0,0)), (WIDTH/2-(sizeX/2), HEIGHT/2)) pygame.display.update()
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((WIDTH,800), 0, 32) self.font = pygame.font.SysFont('Arial', 32) self.timer_x_pos=(WIDTH/2)-(WIDTH/12) self.timer_y_pos=WIDTH/6 self.counter=0 self.startTime=0 self.elapsed=0
def show(self): self.elapsed = round(time.clock()-self.startTime,1) self.rect = pygame.draw.rect(self.screen, (blue), (self.timer_x_pos, 500, self.timer_y_pos, 100)) self.screen.blit(self.font.render(str(self.elapsed), True, (255,255,0)), (self.timer_x_pos+25,550)) if self.elapsed >= MAX_TIME_LIMIT: pygame.mixer.music.load('buzzer2.wav') pygame.mixer.music.play() timer.start()
def power_infos(screen): global displayTimeout global displayBacklight global check_power check_power = MyTimer(5, read_upis) read_upis() check_power.start() font = pygame.font.Font(filepath(MAIN_FONT), MAIN_FONTSIZE) black = pygame.Surface((LCD_WIDTH, LCD_HEIGHT)) background = pygame.Surface((LCD_WIDTH, LCD_HEIGHT)).convert() surf = pygame.Surface((LCD_WIDTH, LCD_HEIGHT)).convert() popup = pygame.Surface((LCD_WIDTH, LCD_HEIGHT)).convert() # if BACK_COLOR != None: # screen.fill(BACK_COLOR) # reset backlight count displayTimeout = time.time() while 1: y = 0 now = time.time() if displayBacklight == True: if now - displayTimeout >= displayDelayData[displayDelay]: if displayDelay != 0: toggle_backlight() power_screen(background, surf) update_event(screen) # screen.fill((0, 0, 0)) rotatedscreen = pygame.transform.rotate(surf, 0) screen.blit(rotatedscreen, (0, 0)) pygame.display.flip() pygame.time.wait(REFRESH_RATE) ################# # ---- MENUS ---- #################
def menu0(screen, options, title, titlesize=22, choicesize = 18, titlecolor=(255,255,255), choicecolor=(255,0,0)): global menupos menupos = 0 x = len(options)-1 while True: screen.fill(black) font = pygame.font.Font(pygame.font.get_default_font(),titlesize) label = font.render(title, 1, (titlecolor)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,0+10)) screen.blit(img_left, (m1_xy[0][0], m1_xy[0][1])) screen.blit(img_right, (m1_xy[1][0], m1_xy[1][1])) screen.blit(img_ok, (LCD_WIDTH/2-img_ok.get_width()/2, LCD_HEIGHT-img_ok.get_height())) # screen.blit(img_cancel, (LCD_WIDTH-img_cancel.get_width(), LCD_HEIGHT-img_cancel.get_height())) # Touchscreen for e in pygame.event.get(): if e.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if m1_left_pos.collidepoint(pos): if menupos == 0: menupos = x else: menupos = menupos-1 # debug_msg(menupos) if m1_right_pos.collidepoint(pos): if menupos == x: menupos = 0 else: menupos = menupos+1 # debug_msg(menupos) if img_ok_pos.collidepoint(pos): # debug_msg("ok") # debug_msg(menupos) return menupos break # if img_cancel_pos.collidepoint(pos): # print"cancel" text = str(options[menupos]) font = pygame.font.Font(pygame.font.get_default_font(),choicesize) label = font.render(text, 1, (choicecolor)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,LCD_HEIGHT/2-font.get_height()/2)) pygame.display.flip()
def changeValue_menu(screen, option, n, title, unit, titlesize=22, choicesize = 18, titlecolor=(255,255,255), choicecolor=(255,0,0)): global displayDelay i = n x = len(option)-1 while True: screen.fill(black) font = pygame.font.Font(pygame.font.get_default_font(),titlesize) label = font.render(title, 1, (white)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,0+10)) screen.blit(img_left, (m1_xy[0][0], m1_xy[0][1])) screen.blit(img_right, (m1_xy[1][0], m1_xy[1][1])) screen.blit(img_ok, (0, LCD_HEIGHT-img_ok.get_height())) screen.blit(img_cancel, (LCD_WIDTH-img_cancel.get_width(), LCD_HEIGHT-img_cancel.get_height())) # Touchscreen for e in pygame.event.get(): if e.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if m1_left_pos.collidepoint(pos): if i == 0: i = x else: i = i-1 if m1_right_pos.collidepoint(pos): if i == x: i = 0 else: i = i+1 if img_ok2_pos.collidepoint(pos): if option == displayDelayData: displayDelay = i saveSettings() network_infos(screen) if img_cancel_pos.collidepoint(pos): network_infos(screen) font = pygame.font.Font(pygame.font.get_default_font(),choicesize) text = str(option[i]) text+=unit if i == n: label = font.render(text, 1, (green)) else: label = font.render(text, 1, (choicecolor)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,LCD_HEIGHT/2-font.get_height()/2)) pygame.display.flip()
def changeKey_menu(screen, titlesize=22, choicesize = 16, titlecolor=(255,255,255), choicecolor=(255,255,255)): global hostapdConfig hostapdConfig = ParseINI('/etc/hostapd/hostapd.conf') key = hostapdConfig['global']['wpa_passphrase'] old_key = key # newkey = key while True: screen.fill(black) font = pygame.font.Font(pygame.font.get_default_font(),titlesize) label = font.render("Security key", 1, (white)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,0+10)) screen.blit(img_newkey, (LCD_WIDTH/2-img_newkey.get_width()/2, LCD_HEIGHT-img_newkey.get_height()*2)) screen.blit(img_ok, (0, LCD_HEIGHT-img_ok.get_height())) screen.blit(img_cancel, (LCD_WIDTH-img_cancel.get_width(), LCD_HEIGHT-img_cancel.get_height())) # Touchscreen for e in pygame.event.get(): if e.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if img_newkey_pos.collidepoint(pos): key = generateKey(WifiAPkeyLenght) if img_ok2_pos.collidepoint(pos): hostapdConfig['global']['wpa_passphrase'] = key write_hostapdConfig('/etc/hostapd/hostapd.conf') saveSettings() reset_wlan_ap(screen) network_infos(screen) if img_cancel_pos.collidepoint(pos): hostapdConfig['global']['wpa_passphrase'] = old_key network_infos(screen) font = pygame.font.Font(pygame.font.get_default_font(),choicesize) text = str(key) label = font.render(text, 1, (choicecolor)) screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,50)) # font = pygame.font.Font(pygame.font.get_default_font(),choicesize) # text = str(newkey) # label = font.render(text, 1, (choicecolor)) # screen.blit(label, (LCD_WIDTH/2-label.get_width()/2,70)) pygame.display.flip()