示例#1
0
 def test_match_font_name(self):
     """That match_font accepts names of various types"""
     font = pygame_font.get_fonts()[0]
     font_path = pygame_font.match_font(font)
     self.assertIsNotNone(font_path)
     font_b = font.encode()
     not_a_font = "thisisnotafont"
     not_a_font_b = b"thisisnotafont"
     good_font_names = [
         # Check single name bytes.
         font_b,
         # Check string of comma-separated names.
         ",".join([not_a_font, font, not_a_font]),
         # Check list of names.
         [not_a_font, font, not_a_font],
         # Check generator:
         (name for name in [not_a_font, font, not_a_font]),
         # Check comma-separated bytes.
         b",".join([not_a_font_b, font_b, not_a_font_b]),
         # Check list of bytes.
         [not_a_font_b, font_b, not_a_font_b],
         # Check mixed list of bytes and string.
         [font, not_a_font, font_b, not_a_font_b],
     ]
     for font_name in good_font_names:
         self.assertEqual(pygame_font.match_font(font_name), font_path,
                          font_name)
示例#2
0
    def test_match_font_comma_separated(self):
        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.assertTrue(pygame_font.match_font("thisisnotafont") is None)

        # Check comma separated list.
        names = ",".join(["thisisnotafont", fonts[-1], "anothernonfont"])
        self.assertFalse(pygame_font.match_font(names) is None)
        names = ",".join(["thisisnotafont1", "thisisnotafont2", "thisisnotafont3"])
        self.assertTrue(pygame_font.match_font(names) is None)
示例#3
0
    def test_match_font_comma_separated(self):
        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.assertTrue(pygame_font.match_font('thisisnotafont') is None)

        # Check comma separated list.
        names = ','.join(['thisisnotafont', fonts[-1], 'anothernonfont'])
        self.assertFalse(pygame_font.match_font(names) is None)
        names = ','.join(['thisisnotafont1', 'thisisnotafont2', 'thisisnotafont3'])
        self.assertTrue(pygame_font.match_font(names) is None)
示例#4
0
    def test_match_font_comma_separated(self):

        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.failUnless(pygame_font.match_font('thisisnotafont') is None)

        # Check comma separated list.
        names = ','.join(['thisisnotafont', fonts[-1], 'anothernonfont'])
        self.failIf(pygame_font.match_font(names) is None)
        names = ','.join(['thisisnotafont1', 'thisisnotafont2', 'thisisnotafont3'])
        self.failUnless(pygame_font.match_font(names) is None)
示例#5
0
    def test_match_font_comma_separated(self):

        fonts = pygame_font.get_fonts()

        # Check for not found.
        self.failUnless(pygame_font.match_font("thisisnotafont") is None)

        # Check comma separated list.
        names = ",".join(["thisisnotafont", fonts[-1], "anothernonfont"])
        self.failIf(pygame_font.match_font(names) is None)
        names = ",".join(["thisisnotafont1", "thisisnotafont2", "thisisnotafont3"])
        self.failUnless(pygame_font.match_font(names) is None)
示例#6
0
 def fonts_init(self, default_font_path, default_font_alias, size=30, color=(0,0,128,255), bgcolor=(0,0,0)):
     from pygame.font import match_font
     font_path = default_font_path or  match_font(default_font_alias)
     if(self.font_manager is None):
         self.font_manager = FontManagerExtended(font_path = font_path, alias=default_font_alias, size = size)
     else:
         raise ValueError, "sdl2_DisplayManager: fonts_init already completed previously.  Don't do it again."
示例#7
0
文件: occult.py 项目: trysdyn/occult
def load_font(font_name, font_size):
    """
    Attempt to load a font of the given name and size. Attempt in this order:

    1.) Attempt to load a font of the given name from the PWD
    2.) Append .ttf to the end and try again, if the name doesn't end in .ttf
    3.) Attempt to return a system font
    4.) Panic and return the system font "Sans", which should exist

    This is made complex by pyinstaller's propensity to make created EXEs crash
    when calling SysFont(), presumably due to not bundling Pygame's default
    font into the EXE properly.
    """
    try:
        # Try to just find the font in PWD
        return font.Font(font_name, font_size)
    except IOError:
        # If that failed, try it with .ttf appended
        if not font_name.endswith(".ttf"):
            try:
                return font.Font(font_name+".ttf", font_size)
            except IOError:
                pass
                
    # If that failed, try to find it in system fonts
    filename = font.match_font(font_name)
    if filename is not None:
        return font.Font(filename, font_size)
    else:
        # If all else fails, panic and use "Sans" as a last resort
        return font.SysFont("Sans", font_size)
示例#8
0
    def __init__(self, height, width, vertical=False, font=None):
        pygame_init()
        self.vertical = vertical
        self.height = height
        self.width = width

        if font is None:
            font = get_default_font()
        else:
            font_file = match_font(font)
            if font_file is None:
                raise ValueError(
                    "pygame cannot find any file for the selected font {}".
                    format(font))
            else:
                font = font_file

        if vertical:
            self._size = self._get_ideal_font_size(height, width, font)
        else:
            self._size = self._get_ideal_font_size(width, height, font)

        if self._size == 0:
            raise ValueError(
                "The selected font {} cannot be rendered in any size".format(
                    font))
        self._font = pygame_Font(font, self._size)
示例#9
0
    def test_match_font_italic(self):
        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        self.assertTrue(
            any(pygame_font.match_font(font, italic=True) for font in fonts)
        )
 def fonts_init(self, default_font_path, default_font_alias, size=30, color=(0,0,128,255), bgcolor=(0,0,0)):
     from pygame.font import match_font
     font_path = default_font_path or  match_font(default_font_alias)
     if(self.font_manager is None):
         self.font_manager = FontManagerExtended(font_path = font_path, alias=default_font_alias, size = size)
     else:
         raise ValueError, "sdl2_DisplayManager: fonts_init already completed previously.  Don't do it again."
示例#11
0
    def test_match_font_all_exist(self):
        fonts = pygame_font.get_fonts()

        # Ensure all listed fonts are in fact available, and the returned file
        # name is a full path.
        for font in fonts:
            path = pygame_font.match_font(font)
            self.failIf(path is None)
            self.failUnless(os.path.isabs(path))
示例#12
0
    def test_match_font_all_exist(self):
        fonts = pygame_font.get_fonts()

        # Ensure all listed fonts are in fact available, and the returned file
        # name is a full path.
        for font in fonts:
            path = pygame_font.match_font(font)
            self.failIf(path is None)
            self.failUnless(os.path.isabs(path))
示例#13
0
    def test_match_font_bold(self):

        fonts = pygame_font.get_fonts()

        # Look for a bold font.
        for font in fonts:
            if pygame_font.match_font(font, bold=True) is not None:
                break
        else:
            self.fail()
示例#14
0
    def test_match_font_italic(self):

        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        for font in fonts:
            if pygame_font.match_font(font, italic=True) is not None:
                break
        else:
            self.fail()
示例#15
0
    def test_match_font_italic(self):

        fonts = pygame_font.get_fonts()

        # Look for an italic font.
        for font in fonts:
            if pygame_font.match_font(font, italic=True) is not None:
                break
        else:
            self.fail()
示例#16
0
    def test_match_font_bold(self):

        fonts = pygame_font.get_fonts()
 
        # Look for a bold font.
        for font in fonts:
            if pygame_font.match_font(font, bold=True) is not None:
                break
        else:
            self.fail()
def render(engine, text, textsize, textcolor, font, backgroundcolor, imgwidth,
           imgheight):
    """Render a PNG using the given 'engine', based on the given parameters.
       'engine' can be either 'gimp' or 'pygame'.
    """
    if match_font(font) == None:
        raise FileNotFoundError(
            "The specified font '{}' could not be found.".format(font))

    renderer = eval('{}_renderer'.format(engine.lower()))
    renderer.render(text, textsize, textcolor, font, backgroundcolor, imgwidth,
                    imgheight)
示例#18
0
    def load_font(cls, name, size, bold, italic):
        h_key = hash((name, size, bold, italic))

        if h_key in cls.LOADED_FONTS:
            return cls.LOADED_FONTS[h_key]

        else:
            path = match_font(name, bold, italic)
            font = Font(path, size)
            cls.LOADED_FONTS[h_key] = font

            return font
示例#19
0
 def test_not_match_font_name(self):
     """match_font return None when names of various types do not exist"""
     not_a_font = "thisisnotafont"
     not_a_font_b = b"thisisnotafont"
     bad_font_names = [
         not_a_font,
         ",".join([not_a_font, not_a_font, not_a_font]),
         [not_a_font, not_a_font, not_a_font],
         (name for name in [not_a_font, not_a_font, not_a_font]),
         not_a_font_b,
         b",".join([not_a_font_b, not_a_font_b, not_a_font_b]),
         [not_a_font_b, not_a_font_b, not_a_font_b],
         [not_a_font, not_a_font_b, not_a_font],
     ]
     for font_name in bad_font_names:
         self.assertIsNone(pygame_font.match_font(font_name), font_name)
    def __init__(self, fontname, size, bold=False, font_file_path=None):
        super(HDFont, self).__init__()
        # init pyg

        # pygame.font.init()
        # p = pygame.font.match_font(fontname,bold)
        font_path = font_file_path
        if (font_path is None):
            font_path = match_font(fontname)
        try:
            p = sdl2_DisplayManager.inst().font_add(font_path=font_path,
                                                    font_alias=fontname,
                                                    size=None,
                                                    color=None,
                                                    bgcolor=None)
        except Exception, e:
            raise ValueError, "Specific font '%s' could not be found on your system or in path '%s' Please install/verify." % (
                fontname, font_file_path)
示例#21
0
 def __init__(self,
              button_text=None,
              input_font=None,
              font_size=None,
              font_color=(0, 0, 0),
              antialias=False,
              button_image=None,
              button_color=None,
              highlight_color=(255, 255, 255),
              click_color=(0, 0, 0),
              call_function=None,
              call_args=None,
              location=(0, 0)):
     sprite.Sprite.__init__(self)
     self.highlight_color = highlight_color
     self.click_color = click_color
     self.call_function = call_function
     self.call_args = call_args
     if button_image is not None:
         self.main_surface = button_image
     elif button_text is not None and font_size is not None:
         self.title = button_text
         if font is not None:
             draw_font = font.Font(input_font, font_size)
         else:
             draw_font = font.Font(font.match_font('arial'), font_size)
         temp = draw_font.render(button_text, antialias, font_color)
         self.main_surface = surface.Surface(
             (temp.get_width() + 4, temp.get_height() + 4))
         self.main_surface.set_colorkey(self.main_surface.get_at((0, 0)))
         if button_color is not None:
             draw.rect(self.main_surface,
                       button_color,
                       self.main_surface.get_rect(),
                       border_radius=4)
         self.main_surface.blit(temp, (2, 2))
     self.main_surface.convert()
     self.surface = self.main_surface.copy()
     self.rect = self.surface.get_rect()
     self.update_location(location, "center")
示例#22
0
文件: ui.py 项目: Davideddu/karaokivy
    def __init__(self, **kwargs):
        super(FontChooser, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.fonts = sorted(map(str, fonts.get_fonts()))

        data = [{'text': str(i), 'is_selected': i == self.font} for i in self.fonts]

        args_converter = lambda row_index, rec: {'text': rec['text'],
                                                 'size_hint_y': None,
                                                 'height': 25}

        self.list_adapter = ListAdapter(data=data, args_converter=args_converter, cls=ListItemButton, selection_mode='single', allow_empty_selection=False)
        self.list_view = ListView(adapter=self.list_adapter)
        self.list_adapter.bind(selection=self.on_font_select)

        self.label = Label(text="The quick brown fox jumps over the brown lazy dog. 0123456789", font_size="30dp", halign="center", size_hint_y=None)
        self.label.font_name = fonts.match_font(self.list_adapter.selection[0].text)
        self.label.bind(size=self.label.setter("text_size"))
        self.font = self.list_adapter.selection[0].text

        self.add_widget(self.list_view)
        self.add_widget(self.label)          
    def __init__(self, fontname, size, bold = False, font_file_path = None):
        super(HDFont, self).__init__()
        # init pyg

        # pygame.font.init()
        # p = pygame.font.match_font(fontname,bold)
        font_path = font_file_path
        if(font_path is None):
            font_path = match_font(fontname)
        p = sdl2_DisplayManager.inst().font_add(font_path=font_path, font_alias=fontname, size=None, color=None, bgcolor=None)

        if(p==None):
            raise ValueError, "Specific font could not be found on your system.  Please install '" + fontname + "'."
        self.pygFont = p # pygame.font.Font(p,size)

        self.name = fontname
        self.font_size=size
        self.char_widths = []
        for i in range(96):
            self.char_widths += [size]
            #self.char_widths += [ self.pygFont.size(str(chr(i+32)))[0] ]
        self.char_size = size #self.pygFont.get_height()
        (self.font_width, self.font_height) = sdl2_DisplayManager.inst().font_get_size("Z", self.name, self.font_size)
示例#24
0
    def __init__(self, **kwargs):
        super(FontChooser, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.fonts = sorted(map(str, fonts.get_fonts()))

        data = [{
            'text': str(i),
            'is_selected': i == self.font
        } for i in self.fonts]

        args_converter = lambda row_index, rec: {
            'text': rec['text'],
            'size_hint_y': None,
            'height': 25
        }

        self.list_adapter = ListAdapter(data=data,
                                        args_converter=args_converter,
                                        cls=ListItemButton,
                                        selection_mode='single',
                                        allow_empty_selection=False)
        self.list_view = ListView(adapter=self.list_adapter)
        self.list_adapter.bind(selection=self.on_font_select)

        self.label = Label(
            text=
            "The quick brown fox jumps over the brown lazy dog. 0123456789",
            font_size="30dp",
            halign="center",
            size_hint_y=None)
        self.label.font_name = fonts.match_font(
            self.list_adapter.selection[0].text)
        self.label.bind(size=self.label.setter("text_size"))
        self.font = self.list_adapter.selection[0].text

        self.add_widget(self.list_view)
        self.add_widget(self.label)
示例#25
0
 def on_font_select(self, instance, value):
     self.font = value[0].text
     self.label.font_name = fonts.match_font(value[0].text)
示例#26
0
文件: ui.py 项目: Davideddu/karaokivy
 def on_font_select(self, instance, value):
     self.font = value[0].text
     self.label.font_name = fonts.match_font(value[0].text)
示例#27
0
文件: codeinput.py 项目: jpoyau/kivy
 def _update_font(self, instance, fnt_name):
     font_name = fonts.match_font(fnt_name)
     if os.path.exists(font_name):
         instance.font_name = self.codeinput.font_name = font_name
def main():
    from os import sys

    if len(sys.argv) <= 1:
        show_commandline_help()

    import font
    from font import Font
    import layers
    from layers import HDTextLayer, TextLayer
    import time
    import sdl2
    t0 = time.clock()
    import ctypes
    from ctypes import byref, cast, POINTER, c_int, c_float, sizeof, c_uint32, c_double, c_voidp, c_void_p
    from sdl2 import endian

    exp_font_name = sys.argv[1]

    font_size = 48

    if len(sys.argv) > 2:
        font_size = int(sys.argv[2])

    sdl2_DisplayManager.Init(10, 10, 1)
    sdl2_DisplayManager.inst().fonts_init("Courier", "HHSam")

    font_path = match_font(exp_font_name)  #"coalition")
    sdl2_DisplayManager.inst().font_add(
        font_path=font_path, font_alias="export_font",
        size=font_size)  #, color=None, bgcolor=None)

    char_size = 0
    lChars = [chr(i + ord(' ')) for i in xrange(0, 95)]
    for char_offset, c in zip(xrange(0, 95), lChars):
        # surf = f.textHollow(c, line_color, interior_color, line_width, fill_color)
        (font_width, font_height) = sdl2_DisplayManager.inst().font_get_size(
            c, 'export_font', font_size)
        char_size = max(char_size, font_width, font_height)

    width = height = char_size * 10
    font_sizes = ''

    # hack stuff to re-attach the correctly sized window
    sdl2_DisplayManager.inst().window = sdl2.ext.Window("Font Preview",
                                                        size=(width, height))
    sdl2_DisplayManager.inst().texture_renderer = sdl2.ext.Renderer(
        sdl2_DisplayManager.inst().window)
    sdl2_DisplayManager.inst().fill = sdl2_DisplayManager.inst(
    ).texture_renderer.fill
    sdl2_DisplayManager.inst().clear = sdl2_DisplayManager.inst(
    ).texture_renderer.clear
    sdl2_DisplayManager.inst().factory = sdl2.ext.SpriteFactory(
        renderer=sdl2_DisplayManager.inst().texture_renderer)

    sdl2_DisplayManager.inst().show_window()

    frame = Frame(width, height)

    #BGR?
    interior_color = (255, 255, 255)
    line_width = 0
    #fill_color = (255,0,0)
    line_color = (1, 1, 1)

    for char_offset, c in zip(xrange(0, 95), lChars):
        # surf = f.textHollow(c, line_color, interior_color, line_width, fill_color)

        char_x = char_size * (char_offset % 10)
        char_y = char_size * (char_offset / 10)

        surf = sdl2_DisplayManager.inst().font_render_bordered_text_Faster(
            frame.pySurface, {
                'x': char_x,
                'y': char_y
            },
            c,
            font_alias='export_font',
            size=font_size,
            border_width=line_width,
            border_color=line_color,
            color=interior_color)

        (font_width, font_height) = sdl2_DisplayManager.inst().font_get_size(
            c, 'export_font', font_size)

        #font_sizes += format(font_width,'x')
        font_sizes += str(font_width)
        font_sizes += ","

    sdl2_DisplayManager.inst().screen_blit(
        source_tx=frame.pySurface,
        expand_to_fill=True)  #, area=(10,10,400,200))

    texture_renderer = sdl2_DisplayManager.inst().texture_renderer
    bk = sdl2.SDL_GetRenderTarget(texture_renderer.renderer)

    t = sdl2.render.SDL_CreateTexture(texture_renderer.renderer,
                                      sdl2.pixels.SDL_PIXELFORMAT_RGBA8888,
                                      sdl2.render.SDL_TEXTUREACCESS_TARGET,
                                      width, height)
    #create a new texture and blit the frame to it, then grab bits from that
    texture_renderer.clear((0, 0, 0, 0))
    sdl2.SDL_SetRenderTarget(texture_renderer.renderer, t)

    #sdl2_DisplayManager.inst().blit(source_tx=frame.pySurface, dest_tx = t, dest = (0,0,512,512))
    texture_renderer.copy(frame.pySurface, (0, 0, width, height),
                          (0, 0, width, height))

    pitch = c_int()
    bytes = c_void_p()
    rect = sdl2.SDL_Rect(0, 0, width, height)

    sdl2.SDL_LockTexture(t, rect, ctypes.byref(bytes), ctypes.byref(pitch))

    if endian.SDL_BYTEORDER == endian.SDL_LIL_ENDIAN:
        rmask = 0x000000FF
        gmask = 0x0000FF00
        bmask = 0x00FF0000
        amask = 0xFF000000
    else:
        rmask = 0xFF000000
        gmask = 0x00FF0000
        bmask = 0x0000FF00
        amask = 0x000000FF

    print rmask

    imgsurface = sdl2.surface.SDL_CreateRGBSurfaceFrom(bytes, width, height,
                                                       32, pitch, rmask, gmask,
                                                       bmask, amask)
    if not imgsurface:
        raise sdl2.ext.SDLError()

    sdl2.SDL_RenderReadPixels(texture_renderer.renderer, rect, 0, bytes, pitch)
    sdl2.SDL_SaveBMP(imgsurface, 'image.png')

    #4) Restore renderer's texture target
    sdl2.SDL_SetRenderTarget(texture_renderer.renderer, bk)

    #ss = sdl2.ext.SoftwareSprite(surf, True)

    #ss = sdl2.ext.SoftwareSprite(imgsurface, True)
    #sdl2.SDL_SaveBMP(ss.contents, "file.bmp")
    #
    #
    print font_sizes

    sdl2_DisplayManager.inst().flip()
    sdl2.SDL_Delay(2)
示例#29
0
from os import path
from pygame.locals import *

BLACK = (31, 36, 10)
GREY = (146, 126, 106)
BROWN = (104, 76, 60)
WHITE = (239, 216, 161)
BLUE = (60, 159, 156)
DARKBLUE = (24, 63, 57)
GREEN = (57, 87, 28)
GGREEN = (0, 255, 0)
YELLOW = (239, 183, 117)
RED = (239, 58, 12)
FONT = None

game_font = font.match_font('arial')
if game_font is not None:
    FONT = game_font

LOGO_FONT = path.join("Artwork", 'Heehaw.ttf')

TILE_SIZE = (64, 64)

# Initialize the clock to limit the frames per second
CLOCK = time.Clock()


def surface_setup(image, image_size, image_offset=(0, 0), color_key=None, scaling=None):
    return_surface = surface.Surface(image_size)
    return_surface.blit(image, (0, 0), rect.Rect(image_offset, image_size))
    if scaling is not None:
示例#30
0
 def __init__(self):
     self.scene = GameScene(Color(255, 255, 255))
     self.display = display.set_mode((800, 600))
     self.display.fill(self.scene.color)
     self.font = font.Font(font.match_font('bitstreamverasans'), 20)
示例#31
0
 def _update_font(self, instance, fnt_name):
     font_name = fonts.match_font(fnt_name)
     if os.path.exists(font_name):
         instance.font_name = self.codeinput.font_name = font_name
示例#32
0
 def set_font(self, size, *args):
     self.font = Font(match_font(*args), size)
示例#33
0
    def test_match_font_bold(self):
        fonts = pygame_font.get_fonts()

        # Look for a bold font.
        self.assertTrue(
            any(pygame_font.match_font(font, bold=True) for font in fonts))
示例#34
0
# Initialisation

display.init()
font.init()
screen = display.set_mode([320, 240])
background = Surface(screen.get_size())
background = background.convert()

# Récupération de la config

conf_file = open("../conf/wake.json")
conf = jload(conf_file)

# Définition des polices
font_filename = font.match_font(conf["general"]["font"])
font = font.Font(font_filename, 135)
#font_time = font.Font(font_filename, 135)

# Definition et coloration des images

image_temp = image.load("images/misc/temp.png")
image_rise = image.load("images/misc/rise.png")
image_set = image.load("images/misc/set.png")
image_mail = image.load("images/misc/mail.png")
image_news = image.load("images/misc/news.png")
image_cal = image.load("images/misc/cal.png")
color_surface(image_temp, hex_to_rgb(conf["general"]["front_color"]))
color_surface(image_rise, hex_to_rgb(conf["general"]["front_color"]))
color_surface(image_set, hex_to_rgb(conf["general"]["front_color"]))
color_surface(image_mail, hex_to_rgb(conf["general"]["front_color"]))
示例#35
0
# Initialisation

display.init()
font.init()
screen = display.set_mode([320, 240])
background = Surface(screen.get_size())
background = background.convert()

# Récupération de la config

conf_file = open("../conf/wake.json")
conf = jload(conf_file)

# Définition des polices
font_filename = font.match_font(conf["general"]["font"])
font = font.Font(font_filename, 135)
#font_time = font.Font(font_filename, 135)


# Definition et coloration des images

image_temp = image.load("images/misc/temp.png")
image_rise = image.load("images/misc/rise.png")
image_set = image.load("images/misc/set.png")
image_mail = image.load("images/misc/mail.png")
image_news = image.load("images/misc/news.png")
image_cal = image.load("images/misc/cal.png")
color_surface(image_temp, hex_to_rgb(conf["general"]["front_color"]))
color_surface(image_rise, hex_to_rgb(conf["general"]["front_color"]))
color_surface(image_set, hex_to_rgb(conf["general"]["front_color"]))
示例#36
0
def main():

    # initialize pygame

    pygame.init()
    
    # initialize screen
    
    info = display.Info()
    screenSize = (info.current_w, info.current_h)
    
    screen = display.set_mode(screenSize, pygame.FULLSCREEN)
    mouse.set_visible(False)

    # intialize clock

    clock = time.Clock()

    infoFont = font.Font(font.match_font('arial'), 12)

    # initialize game world
    
    world = World(screen)
    
    # start music
    
    mixer.music.load("resources/pad.ogg")
    mixer.music.set_volume(0.1)
    mixer.music.play(-1)

    # begin main game loop

    done = False
    while not done:
    
        # check for program exit signal
    
        for e in event.get():
            if e.type == pygame.QUIT:
                done = True

        # check for input
        
        keys = key.get_pressed()
        if keys[pygame.K_ESCAPE]:
            done = True
    
        # update game
        
        world.update(clock.tick())
        
        # render game
        world.draw()

        # draw fps
        
        fps = clock.get_fps()
        if DISPLAY_FPS:
            text = infoFont.render(str(int(round(fps))), True, (255, 255, 255))
            position = (screen.get_width() / 2 - text.get_width() / 2, 32)
            screen.blit(text, position)

        # add particles until the processor can't handle it
        if fps > FRAME_RATE + 5:
            world.addParticle()
        
        # flip buffer
    
        display.flip()

    # clean up

    pygame.quit()
示例#37
0
# Creation flags for subprocess.Popen
PROCESS_FLAGS=0

# font path for export
if exists('/usr/share/fonts/truetype/msttcorefonts'):
  ## - DEBIAN - ## 
  FONT_PATH='/usr/share/fonts/truetype/msttcorefonts'
elif exists('C:\\WINDOWS\\Fonts'):
  FONT_PATH='C:\\WINDOWS\\Fonts'
elif exists('/Library/Fonts'):
  FONT_PATH='/Library/Fonts'
else:
  try:
    # try to get the font path from the pygame module
    from pygame.font import match_font
    file_path=match_font('arial')
    if file_path:
      FONT_PATH=split(file_path)[0]
    else:
      FONT_PATH=''
  except ImportError:
    # if there is no pygame module installed, use the fonts from this program
    FONT_PATH=''
FONT_FILE='Arial.ttf'

from plot_script.config import user_config
if not 'plot' in user_config:
  user_config['plot']={}
if not 'font' in user_config['plot']:
  FONT_DESCRIPTION='Arial'
else:
 def _update_font(self, instance, fnt_name):
     instance.font_name = self.codeinput.font_name =\
         fonts.match_font(fnt_name)
示例#39
0
文件: main.py 项目: gbrls/algorithms
import pygame,sys, time
from pygame import font

pygame.init()
pygame.display.set_caption('Sudoku')
size = width, height = 900, 900

bc_color = 200, 200, 200
fg_color = 0,0,0

screen = pygame.display.set_mode(size)

font_rend = pygame.font.Font(font.match_font('ibmplexmono'), 50)
message = font_rend.render("9", True, fg_color)

w, h = 9, 9;
Game = [[0 for x in range(w)] for y in range(h)]


def valid(n, x,y):

    for i in range (0,9):
        if Game[x][i] == n:
            return False
        if Game[i][y] == n:
            return False
    
    sqrx, sqry = x//3, y//3
    freq = set(())

    for i in range(0,3):
示例#40
0
from pygame import font, sprite

FONT = font.match_font('Sans')


class Message(sprite.Sprite):
    """ Create text messages on screen
        Arguments:
            x, y -- int, destanation of message
            text -- str, message text
        Keyword arguments:
            font_size -- int
    """
    _msg = None
    _rect = None

    def __init__(self, x: int, y: int, text: str, font_size=22):
        sprite.Sprite.__init__(self)
        self.font = font.Font(FONT, font_size)
        self._x = x
        self._y = y
        self.text = text
        self._render_text()
        self._get_rect()

    def _render_text(self):
        self._msg = self.font.render(self.text, 1, (255, 255, 255))

    def _get_rect(self):
        self._rect = self._msg.get_rect()
        self._rect.x, self._rect.y = self._x - self._rect.width // 2, self._y
示例#41
0
def search_font(name):
    found_font = font.match_font(name)
    return found_font
示例#42
0
        maxHeight *= COLS

        if textureWidth < max(maxHeight, maxWidth):
            retFont = f
            break

        retFont = f

    return retFont

for fontFileShort in font.get_fonts():
    print fontFileShort

    if not fontFileShort.startswith('free'): continue

    fontFile = font.match_font(fontFileShort)
    
    # find a size.....
    for sqTextSize in goals:
        f = font.Font(fontFile, sqTextSize/COLS)
        #f = findGoal(sqTextSize, fontFile)
        print 'h', f.get_height()


        #maxHeight = f.size(chars)[1]
        #maxWidth = 0
        #for ch in chars:
        #    maxWidth = max(f.size(ch)[0], maxWidth)
        #sq = max(maxWidth, maxHeight)

        info = []
示例#43
0
def get_font(name, size):
    """
    Return a pygame.Font object from a name or file.

    :param name: Font name or path
    :type name: basestring
    :param size: Font size
    :type size: int
    :return: Font object
    :rtype: pygame.font.FontType
    """
    assert isinstance(size, int)
    if isinstance(name, _font.Font):
        font = name  # type: (_font.FontType,None)
        return font
    else:

        if name == '':
            raise ValueError('Font name cannot be empty')

        if size <= 0:
            raise ValueError('Font size cannot be lower or equal than zero')

        # Font is not a file, then use a system font
        if not path.isfile(name):
            font_name = name
            name = _font.match_font(font_name)

            if name is None:  # Show system available fonts
                from difflib import SequenceMatcher
                from random import randrange
                system_fonts = _font.get_fonts()

                # Get the most similar example
                most_similar = 0
                most_similar_index = 0
                for i in range(len(system_fonts)):
                    # noinspection PyArgumentEqualDefault
                    sim = SequenceMatcher(None, system_fonts[i],
                                          font_name).ratio()  # Similarity
                    if sim > most_similar:
                        most_similar = sim
                        most_similar_index = i
                sys_font_sim = system_fonts[most_similar_index]
                sys_suggestion = 'System font "{0}" unknown, use "{1}" instead'.format(
                    font_name, sys_font_sim)
                sys_message = 'Check system fonts with pygame.font.get_fonts() function'

                # Get examples
                examples_number = 3
                examples = []
                j = 0
                for i in range(len(system_fonts)):
                    font_random = system_fonts[randrange(0, len(system_fonts))]
                    if font_random not in examples:
                        examples.append(font_random)
                        j += 1
                    if j >= examples_number:
                        break
                examples.sort()
                fonts_random = ', '.join(examples)
                sys_message_2 = 'Some examples: {0}'.format(fonts_random)

                # Raise the exception
                raise ValueError('{0}\n{1}\n{2}'.format(
                    sys_suggestion, sys_message, sys_message_2))

        # Try to load the font
        font = None  # type: (_font.FontType,None)
        try:
            font = _font.Font(name, size)
        except IOError:
            pass

        # If font was not loaded throw an exception
        if font is None:
            raise IOError('Font file "{0}" cannot be loaded'.format(font))
        return font
示例#44
0
    FINISHED = auto()
    PATH     = auto()

class Color(Enum):
    
    WHITE  = (255,255,255)
    BLACK  = (  0,  0,  0)
    RED    = (255,  0,  0)
    GREEN  = (  0,255,  0)
    BLUE   = (  0,  0,255)
    YELLOW = (255,255,  0)
    GRAY   = (128,128,128)
    PURPLE = ( 61,0  , 96)

TILESIZE    = 30
MARGIN      = 3
BOXSIZE     = TILESIZE + MARGIN
BOARDWIDTH  = 20
BOARDHEIGHT = 20
FRAMERATE   = 30
TEXTHEIGHT = 80
DISPLAYWIDTH  = 2 * BOXSIZE * BOARDWIDTH + MARGIN + 2 * BOXSIZE
DISPLAYHEIGHT = BOXSIZE * BOARDHEIGHT + MARGIN + 2*TEXTHEIGHT

# FONT AND TEXT CONFIGURATION
font.init()
FONT_PATH = font.match_font("liberatonmone")
FONT_SIZE = 40
FONT      = font.Font(FONT_PATH,FONT_SIZE)
TEXTCOLOR = Color.WHITE.value