def render(self, back, screen): font.init() myfont = font.SysFont('consolas', 30) textsurface = myfont.render('About', True, (255, 255, 255)) screen.blit(textsurface, (50, 100)) myfont = font.SysFont('consolas', 18) textsurface = myfont.render( 'Desenvolvido por Guilherme, Júlia e Hideki', True, (255, 255, 255)) screen.blit(textsurface, (16, 204)) # s = 'Pac-Man (conhecido em japonês com o nome de Puckman ou パックマン) é um jogo eletrônico criado pelo Tōru Iwatani para a empresa Namco, e sendo distribuído para o mercado americano pela Midway Games. Produzido originalmente para Arcade no início dos anos 1980, tornou-se um dos jogos mais jogados e populares no momento, tendo versões para diversos consoles e continuações para tantos outros, inclusive na atualidade' textsurface = myfont.render('Programação de Microcontroladores', True, (255, 255, 255)) screen.blit(textsurface, (56, 224)) myfont = font.SysFont('consolas', 20) textsurface = myfont.render('Pacman em Python -> PyCman', True, (255, 255, 255)) screen.blit(textsurface, (76, 324)) if back: textsurface = myfont.render('Go Back', True, (200, 200, 200)) else: textsurface = myfont.render('Go Back', True, (255, 255, 255)) screen.blit(textsurface, (200, 424))
def __init__(self, size, tilesize=100, message_font=None, glyph_font=None, margin=50, circle=False, tile_cls=None): Board.__init__(self, size, tile_cls) font.init() message_font = message_font or (None, 60) glyph_font = glyph_font or (None, 70) self.message_font = font.Font(message_font[0], message_font[1]) self.glyph_font = font.Font(glyph_font[0], glyph_font[1]) n = tilesize + 1 self.margin = margin self.scr = display.set_mode((size[0]*n + margin*2, size[1]*n + margin*2)) self.scr.fill(white) self.sfc = Surface(self.scr.get_size()) self.sfc = self.sfc.convert() self.sfc.fill(white) self.scr.blit(self.sfc, (0,0)) self.tilesize = tilesize self.circle = circle self.tile_locs = [[ (iround(margin+x+tilesize/2) , iround(margin+y+tilesize/2)) for x in range(0, size[0]*n, n)] for y in range(0, size[1]*n, n)] for tile in self: self.mkgui_tile(tile.loc) self.scr.blit(self.sfc, (0,0)) display.flip()
def get_lines(self): """Create a series of lines that will fit on the provided rect""" font.init() requested_lines = self.string.splitlines() for requested_line in requested_lines: if self.font.size(requested_line)[0] > self.rect_ext.width: words = requested_line.split(' ') # if any of our words are too long to fit, return. for word in words: if self.font.size(word)[0] >= self.rect_ext.width: raise Exception( 'The word %s is too long to fit in the rect ' 'passed.' % word) # Start a new line accumulated_line = '' for word in words: test_line = accumulated_line + word + ' ' # Build the line while the words fit. if self.font.size(test_line)[0] < self.rect_ext.width: accumulated_line = test_line else: self.lines.append(accumulated_line) accumulated_line = word + ' ' self.lines.append(accumulated_line) else: self.lines.append(requested_line)
def __init__(self, display_w, display_h): pygame.init() mixer.init() font.init() # check if the mixer was successfully initialized if mixer.get_init() is None: print("Failed to initialize the audio mixer module.") if font.get_init() is None: print("Failed to initialize the font module.") self.fps = 120 self.world = None self.gui = Gui(self) # Create screen display with 32 bits per pixel, no flags set self.display = pygame.display.set_mode((display_w, display_h), pygame.HWSURFACE, 32) self.delta_time = 0.0 self.debug = False self.paused = False self.print_fps = False self.worlds = list() self.game = None
def __init__(self, screen: Surface, screenResolution: Rectangle, rp): font.init() self.rp = rp self.screen = screen self.history = [] self.cmdhistory = [] self.screenRes = screenResolution self.IdCounter = 0 self.Open = False self.UserInput = "" self.kpointer = False self.DebugPointer = True self.DebugVariables = {} #Options self.DebugColor = Color(0, 255, 0) self.PauseColor = Color(0, 255, 0) self.Background = Color().setHex("#313131") self.UserInputColor = Color().setHex("#212121") self.TextColor = Color().setHex("#eeeeee") self.TextToShow = 5 self.TextToShowOpen = 20 self.TextSize = 13 self.VectorTextSize = 12 self.LineMargin = 3 self.TopMargin = 5 self.LeftMargin = 5 self.BottomMargin = 5 self.DebugMargin = Margin(5, 5) self.DebugLineMargin = Margin(bottom=3) self.KeyDelay = 15 self.Font = font.SysFont("Consolas", self.TextSize) self.Font_v = font.SysFont("Consolas", self.VectorTextSize)
def __init__(self, screen, boxw=BOXW, boxh=BOXH, borderw=BORDERW, boxc=BOXC, borderc=BORDERC, textc=TEXTC, fontfile=FONTFILE, fontsize=FONTSIZE, fontspace=FONTSPACE, transtable=None, cb=None, cbargs=None): self.__dict__.update(locals()) self.inupleft = ((screen.get_width() - boxw) / 2, (screen.get_height() - boxh) / 2) self.outupleft = tuple(i - borderw for i in self.inupleft) self.fontupleft = tuple(i + boxh / 10 for i in self.inupleft) self.irect = (self.inupleft, (boxw, boxh)) self.orect = (self.outupleft, tuple(b + 2 * borderw for b in (boxw, boxh))) font.init() self.fontobj = font.Font(fontfile, fontsize) pygame.key.set_repeat(250, 50)
def test_font_file_not_found(self): # A per BUG reported by Bo Jangeborg on pygame-user mailing list, # http://www.mail-archive.com/[email protected]/msg11675.html pygame_font.init() self.failUnlessRaises(IOError, pygame_font.Font, 'some-fictional-font.ttf', 20)
def __init__(self, width, height): Surface.__init__(self, (width, height)) font.init() self.dir_path = path.dirname(path.realpath(__file__)) self.assets_path = path.join(self.dir_path, 'Assets') self.fonts_path = path.join(self.assets_path, 'Fonts') self.rssTree = None self.width = width self.height = height self.today = None self.fill((255, 255, 255)) self.titleBar_textOffset = (0, -2) self.titleBar_heightRatio = .4 self.titleBar_bgColor = (39,40,34) self.titleBar_textColor = (186, 111, 23) self.titleBar_font = ('OpenSans-Bold.ttf', int(height * .3067)) self.titleBar_text = 'Important Academic Deadlines' self.RenderTitleBar() self.scrollBarSpeed = 5 self.scrollBar_heightRatio = 1.0 - self.titleBar_heightRatio self.scrollBar_bgColor = (242,242,242) self.scrollBar_textColor = (0,0,0) self.scrollBar_textOffset = (0, 0) self.scrollBar_font = ('OpenSans-Regular.ttf', int(height * .33333)) self.scrollBar_textSeperator = ' | ' self.scrollBar = Surface((self.width, self.height * (1.0 - self.titleBar_heightRatio))) self.scrollBar.fill(self.scrollBar_bgColor) self.scrollX1 = 0 self.scrollX2 = 0 self.UpdateContents() self.scrollBar.convert()
def __init__(self, pygameWindow,gameVariable,images): # bool hodnoty self.notOver = True self.startGame = False self.closeGame = False self.loadGame = False self.gameVariable = gameVariable # okno self.window = pygameWindow self.images = images #velkosti self.rectWidth = pygameWindow.get_width() / 3 self.rectHeight = pygameWindow.get_height() / 10 self.rectX = (pygameWindow.get_width() / 2) - (self.rectWidth / 2) # Rect(top,left, width, height) self.nazovHryRect = Rect(0,0,self.window.get_width(),pygameWindow.get_height()/3) self.newGameRect = Rect(self.rectX, 150, self.rectWidth, self.rectHeight) self.loadGameRect = Rect(self.rectX, 250, self.rectWidth, self.rectHeight) self.exitRect = Rect(self.rectX, 350, self.rectWidth, self.rectHeight) # font a texty font.init() self.font = font.SysFont("norasi",int(self.rectHeight/2)) #iniclializacia lablov self._initLabel()
def __init__(self): self._files = FileResolver() # Store keyboard keys and corresponded sounds self._key_sound = {} # Load keymap settings with open(self._files.keymap_path) as f: self._keymap = yaml.safe_load(f) # Lower buffer to lower sound delay mixer.init(44100, -16, 2, 256) # Set higher channels number, allows to play many sounds # at the same time without stopping previously started ones mixer.set_num_channels(20) # Get any mono font, if no mono fonts use system default fonts = tuple(filter(lambda txt: 'mono' in txt, font.get_fonts())) win_font = fonts[0] if fonts else None font.init() self._font = font.SysFont(win_font, self.FONT_SIZE) # Set up the window win_height = len(self._keymap) * self.FONT_SIZE + 2 * self.MARGIN self._screen = display.set_mode((self.WINDOW_WIDTH, win_height)) display.set_caption(self.WINDOW_CAPTION)
def __init__(self, screen): sprite.Sprite.__init__(self) self.code = 2 self.start = time.get_ticks() self.image = surface.Surface(screen) self.image.fill(Color("white")) font.init() self.label = font.Font.render("Niveles", True, Color("yellow"))
def __init__(self, text, location, color=(0, 0, 0)): if not font.get_init(): font.init() self.fnt = font.Font(ui_enums.DEFAULT_FONT, ui_enums.DEFAULT_FONT_SIZE) self.srf = self.fnt.render(text, 1, color) self.color = color self.location = location self.update()
def __init__(self, display): font.init() self.display = display self.menu_font = font.Font('freesansbold.ttf', 32) self.selected_index = 0 self.menu_text = ["Graj", "Zapisz", "Wyjdz"] self.blocker = False self.set_game_scene = False # linia 37
def defaultbox(screen, orect, text): irect = (tuple(i + BORDERW for i in orect[0]), tuple(b - 2 * BORDERW for b in orect[1])) fontupleft = tuple(i + 2 for i in irect[0]) font.init() fontobj = font.Font(FONTFILE, FONTSIZE) textbox(screen, orect, irect, fontupleft, fontobj, text, borderc=BORDERC, boxc=BOXC, textc=TEXTC)
def Init(): global font_path global basic_font global rendered_text global huge_font font.init() basic_font = font.Font(font_path, 32) huge_font = font.Font(font_path, 64) rendered_text = None
def __init__(self, default_font=pyfont.get_default_font(), default_size=16): pyfont.init() self.default_font = UIFont(pyfont.Font(default_font, default_size), default_size, default_font) self.fonts = { self.serialize(default_font, default_size): self.default_font }
def __init__(self, inventory, size): font.init() self.font = font.Font( join('source', 'assets', 'fonts', 'gameFont.ttf'), 24) self.inventory = inventory self.size = size # size of the menu in pixels self.frame = textures['inventory_menu_frame'] self.cursor = 0 self.input_master = InventoryHandler(self)
def main(): print "#"*31 print "### Welcome to MindMixer ###" print "####### Version 0.1beta #######" print """Have a look at the sourcecode! Change stuff to suit your needs! The program will hopefully be self explaining. Hafe fun!""" print "#"*31 selftests() global N while 1: print "(Hint: while training, you can hit SPACE to abort)" print "Hit '"+KEYLEFT+"' if the",str(N)+". previous image is identical to the one shown" print "Hit '"+KEYRIGHT+"' if the",str(N)+". previous sound is identical to the one heard" while 1: print "Ready to train with N=%i?" %(N), if ask(): break else: print "Do you wish to train with N set to a different value? Choosing 'No' exits the program.", if ask(): n = int(raw_input("Ok, enter the desired value here: ")) while n < 1: print "N must be 1 or higher!" n = int(raw_input("Enter a value higher than 1: ")) N = n else: print "bye" sys.exit(1) display.init() display.set_mode(RESOLUTION, FULLSCREEN) font.init() mixer.init(44100) event.set_grab(True) mouse.set_visible(False) trials = gentrials() for trial in trials: if not trial.runtrial(): break display.quit() vis = 0.0 acu = 0.0 for trial in trials: if trial.result[0]: vis+=1 if trial.result[1]: acu+=1 vp = (vis/(MINTRIALS+N))*100 ap = (acu/(MINTRIALS+N))*100 message = "percentage in visual modality:%i\npercentage in acoustic modality:%i\n" %(int(vp),int(ap)) print message if vp >= UPPERTH and ap >= UPPERTH: N+=1 elif (vp < LOWERTH or ap < LOWERTH) and N > 1: N-=1
def __init__(self, size, actions): font.init() self.font = font.Font( join('source', 'assets', 'fonts', '3Dventure.ttf'), 32) self.size = size # size of the menu in pixels self.actions = actions # Dictionary with all the possible actions. Key is the index, value is the action. self.frame = textures['main_action_menu_frame'] self.cursor = 0 self.input_master = MainActionMenuHandler(self)
def test_segfault_after_reinit(self): """ Reinitialization of font module should not cause segmentation fault """ import gc font = pygame_font.Font(None, 20) pygame_font.quit() pygame_font.init() del font gc.collect()
def __init__(self, game): self.game = game self.viewport = None display.init() font.init() self.fonter = font.SysFont('monospace', 16) self.screen = display.set_mode((config.screenW, config.screenH), DOUBLEBUF, 32) display.set_caption("Smash the tanks!")
def init(): state = 0 display.init() font.init() settings = load_settings_file() screen = display.set_mode(settings.frame_resolution, DOUBLEBUF) display.set_caption("beeSim") display.set_icon(game_icon) return state, screen, settings
def __init__(self): D.init() F.init() D.set_mode((0, 0), pygame.NOFRAME) self.main_surface = D.get_surface() background = I.load("DB.jpg").convert() self.main_surface.blit(background, (0, 0)) D.flip() D.set_caption("DIVE")
def __init__(self, offset=(0, 0)): self.BG_COLOR = Settings.BG_COLOR self.BOARD_BG_COLOR = Settings.BOARD_BG_COLOR self.COLOR = Settings.COLOR self.SIDE = Settings.SQUARE_SIDE self.WIDTH = 4 * self.SIDE + 2 * self.MARGIN self.HEIGHT = self.WIDTH + self.FONT_SIZE font.init() self.font = font.Font(Settings.FONT, self.FONT_SIZE) self.font_sf = self.font.render('Next', True, self.COLOR) self.rect = Rect(offset[0], offset[1], self.WIDTH, self.HEIGHT)
def __init__(self, screen, scoredict): self.screen = screen self.screen.fill(pygame.Color("black")) self.width = screen.get_width() self.height = screen.get_height() #self.scorelist = scorelist self.scoredict = {"ABC": 1000, "XYZ": 550} self.color = pygame.Color("white") font.init() self.fontsize = int(self.height/15) self.message = font.Font(None, self.fontsize) self.offset = (100,100)
def __init__(self): print '%s here' % self.__name__() if android: android.init() android.map_key(android.KEYCODE_MENU, K_ESCAPE) init() display.set_mode((X_MAX, Y_MAX)) font.init() self.location = Location(self.location_index)
def __init__( self, screen, message, position, allowed_keys = [], background = (255, 255, 255), text = (255, 0, 0) ): pyfont.init() self.screen = screen self.message = message self.position = position if allowed_keys: self.allowed_keys = allowed_keys self.colours = { 'screen': background, 'text': text } self.font = pyfont.Font( None, 36 )
def __init__(self): font.init() display.init() # init screen self.raw_w, self.raw_h = len( FIELD[0]) * TILE_scale, len(FIELD) * TILE_scale self.scale = 1 self.resolution = int(self.raw_w * self.scale), int(self.raw_h * self.scale) self.display_surface = display.set_mode(self.resolution, FULLSCREEN) # init a debug font self.debug_font = font.Font(font.get_default_font(), 10) self.effect_smoke = []
def __init__(self): self.Our_Airplane = self.__make_airplane__(0, 0, 0, 0, MY_ID, own=True) self.Other_Airplanes = [] pg.init() font.init() self.gD = pg.display.set_mode((WIDTH, int(HEIGHT * 0.9))) pg.display.set_caption('Simulation') self.clock = pg.time.Clock() self.gD.fill(BACKGROUNG_COLOR) pg.display.update() self.clock.tick(SAMPLING_TIME) self.gameExit = False return
def __init__(self,service,folder): logging.debug('RoomBerry __init__') pg.init() pg.display.set_caption(CAPTION) pg.display.set_mode(SCREEN_SIZE) self.__screen = pg.display.get_surface() self.__screenRect = self.__screen.get_rect() logging.debug('Roomberry __init__ freetype init') pgfont.init() logging.debug('Roomberry __init__ freetype sysfont') logging.debug('Font size') # Wish me luck self.__roomFolder=service.calendar(folder)
def _InitializeComponents(self, frequency, channels): # Initialize pygame. font.init() display.init() mixer.pre_init(frequency) mixer.init() mixer.set_num_channels(channels) mouse.set_visible(False)
def _textDimensions(self, text, size: "points", fontFamily: str) -> (int, int): '''Determines the width of rendered text on a specific device. Don't call this directly; use a function to normalize Dip and font such that no errors would be raised.''' # FUTURE: factor in weight print("Calculating...") # DEBUG fonts.init() font = fonts.SysFont(fontFamily, size) width, height = font.size(text) return (width, height)
def test_core_game(): """Test Game.""" font.init() display.init() mixer.init() screen = display.set_mode(SCREEN_SIZE) images = collect_images() game = Game(images) for event in pygame.event.get(): game.start_events(event) game.update() game.draw()
def __init__(self,string,window): font.init() self.text = string self.myfont = font.SysFont("Arial", 20) self.render_font = self.myfont.render(string, 1, C.black) w = self.render_font.get_width() h = self.render_font.get_height() self.winh = window.get_height() self.rect = Rect(0,self.winh,w,h) self.movein = False self.moveout = False self.hold = False self.hold_start = 0
def ask(question): "ask(question) -> answer" font.init() answer = "" tmp = window.copy() display_box("{}: {}".format(question, answer)) while 1: inkey = get_key() if inkey == K_BACKSPACE: answer = answer[0:-1] elif inkey == K_RETURN: break elif inkey == K_MINUS: answer.append("_") elif inkey <= 127: answer += chr(inkey) display_box("{}: {}".format(question, answer)) window.blit(tmp, (0, 0)) return answer
def __init__(self, screen, message, position, allowed_keys=[], background=(255, 255, 255), text=(255, 0, 0)): pyfont.init() self.screen = screen self.message = message self.position = position if allowed_keys: self.allowed_keys = allowed_keys self.colours = {'screen': background, 'text': text} self.font = pyfont.Font(None, 36)
def main(model_path, board_image_path, algorithm): display.init() font.init() desktop_size = get_display_size() try: model = ModelLoadingModule(model_path).run() print() board_layout, start_dirt, start_pos, final_pos = ReadingBoardModule( model, board_image_path).run() path = SolvingModule(board_layout, start_dirt, start_pos, final_pos, algorithm).run() print() MainGameModule(desktop_size, board_layout, path).run() except (GameQuit, KeyboardInterrupt): pass
def drawDimSelection(self): global button6, button8 Surface.fill(self.win, CHECK2) rectWidth = BUTTONHEIGHT * 1.6 rectHeight = BUTTONHEIGHT button6 = Rect(WIDTH/2-rectWidth/2, HEIGHT/2-rectHeight/2-rectHeight/1.5, rectWidth, rectHeight) button8 = Rect(WIDTH/2-rectWidth/2, HEIGHT/2-rectHeight/2+rectHeight/1.5, rectWidth, rectHeight) draw.rect(self.win, CHECK1, button6) draw.rect(self.win, CHECK1, button8) font.init() f = font.SysFont('Arial', 60) text6 = f.render('6 X 6', False, BLACK) text8 = f.render('8 X 8', False, BLACK) Surface.blit(self.win, text6, (button6.left+text6.get_width()/2-10, button6.top+text6.get_height()/2+5)) Surface.blit(self.win, text8, (button8.left+text8.get_width()/2-10, button8.top+text8.get_height()/2+5)) display.update()
def __init__(self): """ Initialize the Tic Tac Toe game by initializing the base PygameApp class, but with a specific size and title, then override some of the default behaviors. """ backgroundsurface = pygame.image.load("./tictactoe/tictactoe.png") # call the pygameapp base initializer, using the size of the image super(TTTApp, self).__init__(backgroundsurface.get_size(), False, "Tic Tac Toe") # initialize the font system font.init() # now override the background attribute of the application self.background = backgroundsurface # allow selecting who goes first self.gameover = True self.endmessage("[H]uman or [C]omputer first?") self.awaitingupdate = True
def __init__(self): display.init() font.init() mixer.init(buffer=0) self.screen_size = [800, 500] self.surface = display.set_mode(self.screen_size) life_image = image.load(Utils.get_path("image/icon.png")).convert_alpha() display.set_icon(life_image) display.set_caption("Ping Pong") display.set_icon(life_image) self.theme_sound = mixer.Sound(Utils.get_path("sound/menu-screen-theme.wav")) self.theme_sound.set_volume(0.25) if Setting.MUSIC: self.theme_sound.play(-1) self.switch_screen(Setting.MENU_SCREEN)
def __init__(self, width, height): Surface.__init__(self, (width, height)) self.width = width self.height = height self.fill((242, 242, 242)) # You need this if you intend to display any text font.init() self.dir_path = path.dirname(path.realpath(__file__)) self.assets_path = path.join(self.dir_path, 'Assets') # notice the 'Fonts' folder is located in the 'Assets' self.fonts_path = path.join(self.assets_path, 'Fonts') self.bcLogoFile = 'ButteCollegeLogo.png' self.welcomeTextFont = (path.join(self.fonts_path, 'OpenSans-Bold.ttf'), int(height * .3)) self.welcomeTextTop = 'Welcome to' self.welcomeTextBottom = 'the Media Center' self.Render()
def initWindow(self, size = None): if (size == None): self.size = Config.screen_size display.init() font.init() self.screen = display.set_mode( self.size, flags.FULLSCREEN if Config.fullscreen else flags.RESIZABLE ) display.set_caption(Config.screen_caption) #Initializing bachground surface self.background = Surface(self.size).convert() self.background.fill(Config.background_color) #Initializing raycast engine self.raycast = Raycast(self.size) self.loadTextures() self.default_font = font.SysFont('Arial', 15)
def __init__(self, text, loc, color=(0, 0, 0), bg_color=None, callback=None, fnt=DEFAULT_FONT, size=DEFAULT_FONT_SIZE, bold=False, underline=False, italics=False): if not font.get_init(): font.init() self.fnt = font.Font(fnt, size) self.fnt.set_bold(bold) self.fnt.set_underline(underline) self.fnt.set_italic(italics) if bg_color is not None: self.srf = self.fnt.render(text, 1, color, bg_color) else: self.srf = self.fnt.render(text, 1, color) self.width = self.srf.get_width() self.height = self.srf.get_height() self.location = loc self.callback = callback
def __init__(self, position, font, text="", textcolor=(0, 0, 255), bgcolor=(0, 0, 0)): """A non-user-editable text box for displaying things on screen. font - a pygame.freetype.Font object. Size, style, text color, and rotation may be changed by editing the appropriate member variables of the font object position - an (x,y) coordinate pair for the top-left corner of the text box textcolor - the color of the rendered font. An (r,g,b) triple. bgcolor - the background color of the rendered font. An (r,g,b) triple. The background will be transparent if bgcolor is None """ Widget.__init__(self, position) ft.init() # initialize the font module only if we need to # multiple initializations are safe self.font = font self._text = text self.textcolor = textcolor self.bgcolor = bgcolor
import pygame from pygame import font from pygame.event import Event from pygame.font import Font from pygame.rect import Rect from pygame.sprite import Sprite from pygame import Surface from pygame.transform import scale from pygame.locals import * from .editor import Editor ###################################################################### # inits font.init() ###################################################################### # constants BLACK = (0, 0, 0) WHITE = (255, 255, 255) FONT = Font(None, 8) SPECIALS = ["/", "{", "}"] WHITESPACE = {"n": "\n"} WARN_BUFF = """\ Warning: buffer not emptied, try increasing rect height or rect width and add more columns\n""" ######################################################################
from pygame import Surface, font, Color, event, K_ESCAPE, QUIT, KEYDOWN, MOUSEBUTTONUP from Buttons import Button SIZE = (600, 350) PL_W = 30 PL_H = 30 BG_IMG = load('bg.png') BACKGROUND = scale(BG_IMG, SIZE) ALFAVIT = ('А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К', 'Л','М','Н','О','П','Р','С','Т','У','Ф', 'Х','Ц','Ч','Щ','Ш','Ъ','Ы','Ь','Э','Ю','Я','_',',','.') window = set_mode(SIZE) screen = Surface(SIZE) font.init() # инициализация шрифтов обязательна, иначе модуль font не будет работать ff = font.Font('fonts/Segoe Print Regular.ttf', 23) Alfavit = Group() # группа алфавита message_group = Group() # группа кнопок сообщения message_list = [] # данный список нужен для передачи сообщения в дешифрующую функцию encode_message_group = Group() # группа кнопок зашифрованного сообщения button_group = Group() # группа кнопок управления decode_message = Group() # группа кнопок дешифрованного сообщения # добавляем кнопки с помощью модуля Button pl = Button(x=300, y=30, width=175, height=35, text='Зашифровать', text_size=32, color=Color("#bf3030")) button_group.add(pl) pl = Button(300, 70, 175, 35, 'Дешифровать', 32, Color("#bf3030")) button_group.add(pl) pl = Button(300, 110, 175, 35, 'Стереть', 32, Color("#bf3030"))
def synesthesize(self, image, colors, fontname): """ Purpose: Take an image, replace all the colors with words associated with the colors, saves the image to disk Inputs: Image to be adulterated, colors to be used Outputs: Filename of created image """ textsize = 14 font.init() self.texter = font.SysFont(fontname, textsize) (letWidth, letHeight) = self.texter.size('a') self.iSimp = ImageSimpler() self.preimg = self.iSimp.simplify(image, colors, 25) self.img = self.preimg.resize((self.preimg.size[0], int(self.preimg.size[1] * (letWidth/letHeight)))) pixor = self.img.load() newH = self.img.size[1] * letHeight newW = self.img.size[0] * letWidth self.synpic = Surface((newW, newH)) self.synpic.fill((255,255,255)) #replace pixels with words. One pixel -> one character. Oh hai, linear packing approximation... x = 0 y = 0 def check_fit(space, color): if space <= 25: if self.all_combos[color][space]: word = self.all_combos[color][space].pop() self.all_combos[color][space].appendleft(word) return word else: if space >= 8: return check_fit(floor(space/2), color) + check_fit(ceil(space/2), color) else: return "!" * int(space) else: shift = randint(0,4) return check_fit(floor(space/2) - shift, color) + check_fit(ceil(space/2) + shift, color) def get_space(x,y, color): x1 = x while x < self.img.size[0] and webcolors.rgb_to_name(pixor[x,y]) is color: x += 1 return x - x1 def paint_picture(x, y): while y < self.img.size[1]: pixel = pixor[x,y] color = webcolors.rgb_to_name(pixel) space = get_space(x,y, color) string = check_fit(space, color) drawn = self.texter.render(string, True, pixel) self.synpic.blit(drawn, (x * letWidth, y * letHeight)) x += (len(string)) if x >= self.img.size[0]: y += 1 x = 0 paint_picture(x,y) name = ''.join([choice(string.ascii_letters + string.digits) for n in range(30)]) PyImage.save(self.synpic, 'creations/' + name + '.jpg') return 'creations/' + name + '.jpg'
def __init__(self): self.console = Surface((600, 85), SRCALPHA, 32) self._clear_log() font.init() self.font = SysFont('Arial', 14) self.messages = []
import logging log = logging.getLogger("R.Compat") try: from pygame import freetype except: from pygame import font as pyfont pyfont.init() def freetypeFont(font, size): try: return freetype.Font(font, ptsize = size) except(TypeError): pass except(NameError): return pyfont.Font(font, size) try: return freetype.Font(font, size = size) except(TypeError): pass def freetypeRender(freetypeFont, value, color, rotation=0, size=0): try: return freetypeFont.render( text = value, fgcolor = color, bgcolor = None, rotation = rotation, size = size) except(Exception) as e: log.debug("layer 1 compat on freetypeRender: " + e.message) try: return freetypeFont.render(value, color, None, rotation, ptsize = size)
import pygame import pygame.font as f import pygame.locals as pl import random from vgd import colors pygame.init() f.init() # names = ["Caleb", "Noah", "Desmond", "Philip", "Jalon", "Daniel", "Chris", "Tim", "Alaul", "Kaylyn", "Alex", "Jiaqi", "Jeff", "Dane", "Ricardo" ] names = ["Chris", "Kaylyn", "Jalon", "Alaul", "Dane", "Caleb", "Ricardo"] counts = [1.0] * len(names) screen_width = 300 screen_height = 100 main_surface = pygame.display.set_mode((screen_width,screen_height)) pygame.display.set_caption("") BACKGROUND = colors["white"] text_maker = f.Font("fonts/Roboto-Regular.ttf", 40) def weighted_random(weights): tot = sum(weights) num = random.random() * tot running = 0 for i in range(1,len(weights)): running += weights[i] if num < running:
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # #Import modules import sys,os,time,httplib2,urllib import math as maths from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GL.ARB.framebuffer_object import * from OpenGL.GL.EXT.framebuffer_object import * from pygame.font import Font as PygameFont,init from pygame.image import tostring as image_to_string,load as image_load,save as pygame_save,fromstring as pygame_fromstring init() #Initialise the font. from pygame import Rect from textrect import render_textrect from ctypes import * from objc import * cscalelib = CDLL(os.path.dirname(sys.argv[0]) + "/C++ Extensions/cscalelib.dylib") #Load C++ library c_2dcoordinate = c_double * 2 #Coordinates for (x,y) c_3dcoordinate = c_double * 3 #Coordinates for (x,y,z) c_colour = c_float * 4 #RGBA in array def c_coordinates(coordinates,type): c_array = type * len(coordinates) coordinates = [tuple(x) for x in coordinates] return c_array(*coordinates) loadBundle("Scalelib Cocoa Framework",globals(),"/Users/matt/Programming/A computing project - TimeSplitters game/Development/Cocoa Scalelib/Scalelib Cocoa Framework/build/Release/Scalelib Cocoa Framework.framework/") #Load Objective-C library #Constants TOP_LEFT = 1
def setUp(self): pygame_font.init()
def test_init(self): pygame_font.init()
"""PyGame bitmap and texmap fonts""" from OpenGLContext.scenegraph.text import fontprovider, font from OpenGL.GL import * from OpenGLContext.debug.logs import text_log from pygame import font as pygame_font from pygame import image, surfarray, transform import pygame, traceback, os from Numeric import transpose, shape, zeros pygame_font.init() pygame.init() class PyGameBitmapFont( font.NoDepthBufferMixIn, font.BitmapFontMixIn, font.Font ): """A PyGame-provided Bitmap Font """ format = "bitmap" def __init__( self, fontStyle = None, filename = None, size = None, ): self._displayLists = {} self.fontStyle = fontStyle or None if filename is None or size is None: fontFile, weight, italics, size = PyGameFontProvider.match( fontStyle ) self.font = pygame_font.Font( fontFile, int(size)) self.filename = filename self.size = size if __debug__: