Ejemplo n.º 1
0
def make_standard_text(font_path, text, shape, padding = 0.1, color = (0, 0, 0), init_fontsize = 25):
    font = freetype.Font(font_path)
    font.antialiased = True
    font.origin = True
    fontsize = init_fontsize
    font.size = fontsize
    pre_remain = None
    if padding < 1:
        border = int(min(shape) * padding)
    else:
        border = int(padding)
    target_shape = tuple(np.array(shape) - 2 * border)
    while True:
        rect = font.get_rect(text)
        res_shape = tuple(np.array(rect[1:3]))
        remain = np.min(np.array(target_shape) - np.array(res_shape))
        if pre_remain is not None:
            m = pre_remain * remain
            if m <= 0:
                if m < 0 and remain < 0:
                    fontsize -= 1
                if m == 0 and remain != 0:
                    if remain < 0:
                        fontsize -= 1
                    elif remain > 0:
                        fontsize += 1
                break
        if remain < 0:
            if fontsize == 2:
                break
            fontsize -= 1
        else:
            fontsize += 1
        pre_remain = remain
        font.size = fontsize

    surf, rect = render_normal(font, text)
    if np.max(np.array(surf.shape) - np.array(target_shape)) > 0:
        scale = np.min(np.array(target_shape, dtype = np.float32) / np.array(surf.shape, dtype = np.float32))
        to_shape = tuple((np.array(surf.shape) * scale).astype(np.int32)[::-1])
        surf = cv2.resize(surf, to_shape)
    canvas = np.zeros(shape, dtype = np.uint8)
    tly, tlx = int((shape[0] - surf.shape[0]) // 2), int((shape[1] - surf.shape[1]) // 2)
    canvas[tly:tly+surf.shape[0], tlx:tlx+surf.shape[1]] = surf
    canvas = ((1. - canvas.astype(np.float32) / 255.) * 127.).astype(np.uint8)

    return cv2.cvtColor(canvas, cv2.COLOR_GRAY2RGB)
Ejemplo n.º 2
0
 def __init__(self, word_lst, font_lst, x, y):
     super().__init__()
     self.text = word_lst[randint(0, (len(word_lst) - 1))]
     self.fg_color = [(237, 105, 27), (166, 214, 201), (250, 185, 10)]
     self.bg_color = (0, 0, 0)
     self.font = ft.Font(
         FONT_PATH + font_lst[randint(0, (len(font_lst) - 1))], 80)
     # self.font.underline = True if randint(0, 1) else False
     self.rendered_ft = self.font.render(self.text,
                                         fgcolor=self.fg_color[randint(
                                             0, 2)],
                                         rotation=randint(-5, 5))
     self.image = self.rendered_ft[0]
     self.rect = self.image.get_rect()
     self.rect.x = x
     self.rect.y = y
     self.shadow = None
Ejemplo n.º 3
0
    def _setup_graphics(self):
        """
        Prepare the pygame graphics

        :return: pygame.screen canvas to draw on
        """
        freetype.init()

        size = (int(self.track.width * Engine.SCALE),
                int(self.track.height * Engine.SCALE))
        pygame.display.set_caption('Train-a-Train')
        icon = pygame.image.load(
            pkg_resources.resource_filename("traingame", 'visuals/icon.png'))
        pygame.display.set_icon(icon)
        screen = pygame.display.set_mode(size)

        train = pygame.image.load(
            pkg_resources.resource_filename("traingame", 'visuals/train.png'))
        train_blue = pygame.image.load(
            pkg_resources.resource_filename("traingame",
                                            'visuals/train-blue.png'))
        train_green = pygame.image.load(
            pkg_resources.resource_filename("traingame",
                                            'visuals/train-green.png'))
        train_white = pygame.image.load(
            pkg_resources.resource_filename("traingame",
                                            'visuals/train-white.png'))

        self.train = pygame.transform.scale(train, (78, 21))
        self.train_blue = pygame.transform.scale(train_blue, (78, 21))
        self.train_green = pygame.transform.scale(train_green, (78, 21))
        self.train_white = pygame.transform.scale(train_white, (78, 21))

        self.train_types = {
            "default": self.train,
            "blue": self.train_blue,
            "green": self.train_green,
            "white": self.train_white
        }

        font_size = Engine.SCALE * 3
        self.roboto_font = freetype.Font(pkg_resources.resource_filename(
            "traingame", 'visuals/roboto.ttf'),
                                         size=font_size)

        return screen
Ejemplo n.º 4
0
    def init_font(self, fs):
        """
        Initializes a pygame font.
        FS : font-state sample
        """

        # PARAM: underline, strong, oblique, strength
        font = freetype.Font(fs['font'], size=fs['size'])
        font.underline = fs['underline']
        font.underline_adjustment = fs['underline_adjustment']
        font.strong = fs['strong']
        font.oblique = fs['oblique']
        font.strength = fs['strength']
        char_spacing = fs['char_spacing']
        font.antialiased = True
        font.origin = True
        return font
def run():
    pygame.init()

    fontdir = os.path.dirname(os.path.abspath(__file__))
    print(fontdir)
    print(os.path.join(fontdir, "data", "sans.ttf"))
    font = freetype.Font(os.path.join(fontdir, "data", "sans.ttf"))

    screen = pygame.display.set_mode((800, 600))
    screen.fill(colors["white"])

    font.underline_adjustment = 0.5
    font.pad = True

    font.render_to(screen, (32, 25), "NFKC", size=16)
    font.render_to(
        screen,
        (32, 52),
        normalize("NFKC", STRING),
        colors["white"],
        colors["teal"],
        size=SIZE,
    )

    font.render_to(screen, (32, 200), "NFKD", size=16)

    font.render_to(
        screen,
        (32, 232),
        normalize("NFKD", STRING),
        colors["white"],
        colors["teal"],
        size=SIZE,
    )

    metrics = font.get_metrics(STRING, size=SIZE)
    print(metrics)

    pygame.display.flip()

    while 1:
        if pygame.event.wait().type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
            break

    pygame.quit()
Ejemplo n.º 6
0
    def __init__(self, text, font_path, fgcolor=None, speed=10):
        self.text = text

        if not freetype.get_init():
            freetype.init()

        self.font = freetype.Font(font_path)
        self.speed = speed

        self.delay = True
        self.direction = -1

        self.rendered_text, self.rendered_rect = self.font.render(
            self.text, fgcolor)
        self.fgcolor = fgcolor
        self.timer = datetime.now()
        self.rendered_rect.x = 0
        self.rendered_rect.y = 0
Ejemplo n.º 7
0
    def __init__(self, image, x, y, xscale, yscale, text, font_type=SANS):
        if image is not None:
            self.image = image
            self.rect = image.get_rect()
            self.rect[0] = x
            self.rect[1] = y
            self.rect[2] *= xscale
            self.rect[3] *= yscale
            self.rect[0] -= int(self.rect[2] / 2)
            self.rect[1] -= int(self.rect[3] / 2)
        else:
            self.image = None
            self.rect = pygame.Rect(x, y, 100, 100)
        self.font_size = 40
        self.text = text
        self.foname = font_type
        self.font = freetype.Font(self.foname, self.font_size)

        self.color = pygame.Color(0, 0, 0, 0)
Ejemplo n.º 8
0
    def draw_text(self,
                  screen,
                  color1=pygame.Color(100, 10, 30, 255),
                  color2=pygame.Color(40, 10, 40, 255),
                  style=pygame.freetype.STYLE_STRONG):

        color1[3] = 255 - self.color[3]
        color2[3] = 255 - self.color[3]

        "draws the text into the screen"
        self.font = freetype.Font(self.foname, self.font_size)

        self.font.underline_adjustment = 0
        self.font.pad = False
        self.trender = self.font.render(
            self.text,
            self.color,
        )
        self.twidth, self.theight = self.trender[1][2], self.trender[1][3]
        if self.image == None:
            dprint("yeet.")

        d = self.font.render_to(
            screen, (self.rect[0] + self.rect[2] / 2 - self.twidth / 2 - 3,
                     self.rect[1] + self.rect[3] / 2 - self.theight / 2),
            self.text,
            color1,
            None,
            style=style)

        self.font.render_to(
            screen, (self.rect[0] + self.rect[2] / 2 - self.twidth / 2,
                     self.rect[1] + self.rect[3] / 2 - self.theight / 2),
            self.text,
            color2,
            None,
            style=style)
        if self.image == None and self.text != "Гарри Поттер И ИИ":
            self.rect[2] = d.width
            self.rect[3] = d.height
        #dirtyrects.append(pygame.Rect(self.rect[0], self.rect[1], self.trender[1][2], self.trender[1][3]))
        dirtyrects.append(pygame.Rect(0, 0, 800, 450))
Ejemplo n.º 9
0
def pygame_freetype_font(text, curr_dir):
    pygame.init()
    freetype.init()
    # font =  freetype.SysFont("simsun",9)
    font = freetype.Font(os.path.join(curr_dir, "fonts", "SIMSUN.TTC"), 9)
    font.antialiased = False
    surf = font.render("中国", fgcolor=(0, 0, 0), bgcolor=(255, 255, 255))[0]
    # im_str = pygame.image.tostring(surf, 'RGB')
    # print(type(imgdata))
    # cv_image = cv2.cv.CreateImageHeader(surf.get_size(), cv.IPL_DEPTH_8U, 3)
    # cv2.cv.SetData(cv_image, imgdata)
    # image = surf.get_view('2').raw
    # image = np.array(image, dtype=np.uint8, copy=True)
    #nparr = np.fromstring(im_str, np.uint8)
    #img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    # image = np.fromstring(im_str, np.uint8)
    #utils.show(img_np)

    pygame.image.save(surf, os.path.join(curr_dir, "test", "pygame.png"))
Ejemplo n.º 10
0
    def test_issue_208(self):
        """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection

           Copying into theX11 PRIMARY selection (mouse copy/paste) would not
           work due to a confusion between content type and clipboard type.

        """

        from pygame import display, event, freetype
        from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
        from pygame.locals import KEYDOWN, K_y, QUIT

        success = False
        freetype.init()
        font = freetype.Font(None, 24)
        display.init()
        display.set_caption("Interactive X11 Paste Test")
        screen = display.set_mode((600, 200))
        screen.fill(pygame.Color("white"))
        text = "Scrap put() succeeded."
        msg = (
            "Some text has been placed into the X11 clipboard."
            " Please click the center mouse button in an open"
            " text window to retrieve it."
            '\n\nDid you get "{}"? (y/n)'
        ).format(text)
        word_wrap(screen, msg, font, 6)
        display.flip()
        event.pump()
        scrap.init()
        scrap.set_mode(SCRAP_SELECTION)
        scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
        while True:
            e = event.wait()
            if e.type == QUIT:
                break
            if e.type == KEYDOWN:
                success = e.key == K_y
                break
        pygame.display.quit()
        self.assertTrue(success)
Ejemplo n.º 11
0
    def init_font_model(self):
        newfontlist = []
        ys = np.arange(8, 200)
        A = np.c_[ys, np.ones_like(ys)]
        models = {}
        for fontname in self.fonts:
            font = freetype.Font(fontname, size=12)
            h = []
            for y in ys:
                h.append(font.get_sized_glyph_height(y))
            h = np.array(h)
            m, _, _, _ = np.linalg.lstsq(A, h)
            models[font.name] = m
            rect = font.get_rect('O')
            if rect.width:
                newfontlist.append(fontname)
        self.font_model = models
        self.fonts = newfontlist

        with open('font_px2pt.cp', 'w') as f:
            cp.dump(models, f)
Ejemplo n.º 12
0
    def _setup_graphics(self):
        """
        Prepare the pygame graphics

        :return: pygame.screen canvas to draw on
        """
        freetype.init()

        size = (int(self.track.width * Engine.SCALE),
                int(self.track.height * Engine.SCALE))
        pygame.display.set_caption('Train-a-Train')
        icon = pygame.image.load('visuals/icon.png')
        pygame.display.set_icon(icon)
        screen = pygame.display.set_mode(size)

        train = pygame.image.load('visuals/train.png')
        self.train = pygame.transform.scale(train, (78, 21))

        font_size = Engine.SCALE * 3
        self.roboto_font = freetype.Font('visuals/roboto.ttf', size=font_size)

        return screen
Ejemplo n.º 13
0
def clean_fonts(font_dir, fonts):
    pygame.init()
    newfontlist = []
    ys = np.arange(8, 200).astype(np.float)
    A = np.c_[ys, np.ones_like(ys)]
    models = {}
    for fontname in fonts:
        font = freetype.Font('{}/{}'.format(font_dir, fontname), size=12)
        h = []
        for y in ys:
            h.append(font.get_sized_glyph_height(y))
        h = np.array(h)
        m, _, _, _ = np.linalg.lstsq(A, h)
        models[font.name] = m
        rect = font.get_rect('O')
        if rect.width:
            newfontlist.append(fontname)
    font_model = models
    print('Total: {}, filtered: {}, saved: {}'.format(
        len(fonts),
        len(fonts) - len(newfontlist), len(newfontlist)))
    return font_model, newfontlist
Ejemplo n.º 14
0
import pickle as cp

pygame.init()

ys = np.arange(8, 200)
A = np.c_[ys, np.ones_like(ys)]

xs = []
models = {}  #linear model

#FS = FontState()
FS = glob.glob('data/fonts/japan_fonts/*.ttf')
#plt.figure()
#plt.hold(True)
for i in range(len(FS)):
    print(i)
    print(FS[i])
    font = freetype.Font(FS[i], size=12)
    h = []
    for y in ys:
        h.append(font.get_sized_glyph_height(float(y)))
    h = np.array(h)
    m, _, _, _ = np.linalg.lstsq(A, h)
    models[font.name] = m
    xs.append(h)

with open('font_px2pt.cp', 'wb') as f:
    cp.dump(models, f)
#plt.plot(xs,ys[i])
#plt.show()
Ejemplo n.º 15
0
def draw_info():
    color = pygame.Color(255, 255, 255)

    text = "Игра 'Гарри Поттер и ИИ'"
    font = freetype.Font(SANS, 40)
    trender = font.render(
        text,
        color,
    )
    twidth, theight = trender[1][2], trender[1][3]
    font.render_to(screen, (0, 0),
                   text,
                   pygame.Color(255, 255, 255),
                   None,
                   style=pygame.freetype.STYLE_STRONG)

    text = "Разрабатывалась учеником лицея №1"
    trender = font.render(
        text,
        color,
    )
    twidth, theight = trender[1][2], trender[1][3]
    font.render_to(screen, (0, 100),
                   text,
                   pygame.Color(255, 255, 255),
                   None,
                   style=pygame.freetype.STYLE_STRONG)

    text = "В одиночку. в игре задействован"
    trender = font.render(
        text,
        color,
    )
    twidth, theight = trender[1][2], trender[1][3]
    font.render_to(screen, (0, 300),
                   text,
                   pygame.Color(255, 255, 255),
                   None,
                   style=pygame.freetype.STYLE_STRONG)

    text = "Базовый пример обучаемой нейросети."
    trender = font.render(
        text,
        color,
    )
    twidth, theight = trender[1][2], trender[1][3]
    font.render_to(screen, (0, 400),
                   text,
                   pygame.Color(255, 255, 255),
                   None,
                   style=pygame.freetype.STYLE_STRONG)

    text = "Берсенёвым Ильёй Ивановичем"
    trender = font.render(
        text,
        color,
    )
    twidth, theight = trender[1][2], trender[1][3]
    font.render_to(screen, (0, 200),
                   text,
                   pygame.Color(255, 255, 255),
                   None,
                   style=pygame.freetype.STYLE_STRONG)
Ejemplo n.º 16
0
    def __init__(self,
                 w,
                 h,
                 *args,
                 alpha=False,
                 text="",
                 bgcolor=None,
                 fgcolor=BLACK,
                 font=None,
                 font_size=20,
                 underlined=False,
                 bold=False,
                 background=None,
                 enlarge=True,
                 offset=None,
                 **kwargs):
        super().__init__(w, h, alpha=alpha)
        #making sure arguments are valid
        if bgcolor == None:
            if background == None:
                if alpha == None:
                    raise ValueError(
                        f"A background, bgcolor, or alpha must be set")
        else:
            if background:
                raise ValueError(f"Can't set background and bgcolor")

        self.enlarge = enlarge
        self.offset = offset
        self.background = background

        #text properties
        self._text = text
        self.fgcolor = fgcolor
        self.bold = bold
        self.underlined = underlined

        #font
        self.font = freetype.Font(font, font_size)  #None means pg default
        self.font.underline = underlined
        self.font.strong = bold
        self.font.fgcolor = self.fgcolor

        #surface
        if background:
            self.bgsurf = pg.transform.scale(load_surf(background), (w, h))
        else:
            if bgcolor:
                self.bgcolor = bgcolor
            else:
                if alpha:
                    self.bgcolor = ALPHA
                else:
                    self.bgcolor = WHITE

            self.bgsurf = pg.Surface((w, h))
            self.bgsurf.fill(self.bgcolor)
        self.surf = self.bgsurf.copy()

        #evaluating offset
        if offset:
            if isinstance(offset, tuple):
                font_offset = Offset(*offset)
            elif isinstance(offset, Offset):
                font_offset = offset
            else:
                raise TypeError(
                    f"offset must of type tuple(int, int) not {type(offset)}")

        #resizing font
        needs_rescale = False
        trect = self.font.get_rect(text)
        srect = self.chg_area = self.surf.get_rect()

        if offset:  #applying offset
            srect.w -= font_offset.x * 2
            srect.h -= font_offset.y * 2

        if trect.w > srect.w or trect.h > srect.h:
            needs_rescale = True
        if needs_rescale or enlarge:
            ratios = (srect.w / trect.w, srect.h / trect.h)
            scale = min(ratios)
            self.font.size *= scale

        self.make_surf()
Ejemplo n.º 17
0
import numpy as np
import matplotlib.pyplot as plt
import cPickle as cp

pygame.init()

ys = np.arange(8, 200)
A = np.c_[ys, np.ones_like(ys)]

xs = []
models = {}  # linear model

FS = FontState()
# plt.figure()
# plt.hold(True)
for i in xrange(len(FS.fonts)):
    font = freetype.Font(FS.fonts[i], size=12)
    h = []
    for y in ys:
        h.append(font.get_sized_glyph_height(y))
    h = np.array(h)
    m, _, _, _ = np.linalg.lstsq(A, h)
    models[font.name] = m
    print("{}:\t{}".format(i, font.name))
    xs.append(h)

with open('font_px2pt.cp', 'w') as f:
    cp.dump(models, f)
# plt.plot(xs,ys[i])
# plt.show()
Ejemplo n.º 18
0
import sys, pygame
from pygame.locals import *
from pygame import freetype

pygame.init()
def wait_key():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_q):
                pygame.quit()
                sys.exit()


screen = pygame.display.set_mode((150, 100))
screen.fill((255,255,255))

font = freetype.Font(None, size=50)
font.origin = True
font.kerning = True # uncomment this to get the crash
text_surf, text_rect = font.render('Hello', (0,0,0), size=50)

screen.blit(text_surf, (0,0))

pygame.display.flip()
wait_key()
Ejemplo n.º 19
0
    def generate_sample(self,
                        display_text=None,
                        display_text_length=None,
                        outheight=None,
                        pygame_display=False,
                        random_crop=False,
                        substring_crop=-1,
                        char_annotations=False):
        """
        This generates the full text sample
        """

        if self.screen is None and pygame_display:
            self.screen = pygame.display.set_mode(self.sz)
            pygame.display.set_caption('WordRenderer')

        # clear bg
        # bg_surf = pygame.Surface(self.sz, SRCALPHA, 32)
        # bg_surf = bg_surf.convert_alpha()

        if display_text is None:
            # get the text to render
            display_text, label = self.corpus.get_sample(
                length=display_text_length)
        else:
            label = 0

        # print "generating sample for \"%s\"" % display_text

        # get a new font state
        fs = self.fontstate.get_sample()

        # clear bg
        # bg_surf = pygame.Surface(self.sz, SRCALPHA, 32)
        bg_surf = pygame.Surface(
            (round(2.0 * fs['size'] * len(display_text)), self.sz[1]),
            SRCALPHA, 32)

        font = freetype.Font(fs['font'], size=fs['size'])

        # random params
        display_text = fs['capsmode'](
            display_text) if fs['random_caps'] else display_text
        font.underline = fs['underline']
        font.underline_adjustment = fs['underline_adjustment']
        font.strong = fs['strong']
        font.oblique = fs['oblique']
        font.strength = fs['strength']
        char_spacing = fs['char_spacing']

        font.antialiased = True
        font.origin = True

        # colour state
        cs = self.colourstate.get_sample(2 + fs['border'])

        # baseline state
        mid_idx = int(math.floor(len(display_text) / 2))
        curve = [0 for c in display_text]
        rotations = [0 for c in display_text]
        if fs['curved'] and len(display_text) > 1:
            bs = self.baselinestate.get_sample()
            for i, c in enumerate(display_text[mid_idx + 1:]):
                curve[mid_idx + i + 1] = bs['curve'](i + 1)
                rotations[mid_idx + i + 1] = -int(
                    math.degrees(
                        math.atan(bs['diff'](i + 1) / float(fs['size'] / 2))))
            for i, c in enumerate(reversed(display_text[:mid_idx])):
                curve[mid_idx - i - 1] = bs['curve'](-i - 1)
                rotations[mid_idx - i - 1] = -int(
                    math.degrees(
                        math.atan(bs['diff'](-i - 1) / float(fs['size'] / 2))))
            mean_curve = sum(curve) / float(len(curve) - 1)
            curve[mid_idx] = -1 * mean_curve

        # render text (centered)
        char_bbs = []
        # place middle char
        rect = font.get_rect(display_text[mid_idx])
        rect.centerx = bg_surf.get_rect().centerx
        rect.centery = bg_surf.get_rect().centery + rect.height
        rect.centery += curve[mid_idx]
        bbrect = font.render_to(bg_surf,
                                rect,
                                display_text[mid_idx],
                                rotation=rotations[mid_idx])

        bbrect.x = rect.x
        bbrect.y = rect.y - rect.height
        char_bbs.append(bbrect)

        # render chars to the right
        last_rect = rect
        for i, c in enumerate(display_text[mid_idx + 1:]):
            char_fact = 1.0
            if fs['random_kerning']:
                char_fact += fs['random_kerning_amount'] * n.random.randn()
            newrect = font.get_rect(c)
            newrect.y = last_rect.y
            newrect.topleft = (last_rect.topright[0] +
                               char_spacing * char_fact, newrect.topleft[1])
            newrect.centery = max(
                0 + newrect.height * 1,
                min(self.sz[1] - newrect.height * 1,
                    newrect.centery + curve[mid_idx + i + 1]))
            try:
                bbrect = font.render_to(bg_surf,
                                        newrect,
                                        c,
                                        rotation=rotations[mid_idx + i + 1])
            except ValueError:
                bbrect = font.render_to(bg_surf, newrect, c)
            bbrect.x = newrect.x
            bbrect.y = newrect.y - newrect.height
            char_bbs.append(bbrect)
            last_rect = newrect
        # render chars to the left
        last_rect = rect
        for i, c in enumerate(reversed(display_text[:mid_idx])):
            char_fact = 1.0
            if fs['random_kerning']:
                char_fact += fs['random_kerning_amount'] * n.random.randn()
            newrect = font.get_rect(c)
            newrect.y = last_rect.y
            newrect.topright = (last_rect.topleft[0] -
                                char_spacing * char_fact, newrect.topleft[1])
            newrect.centery = max(
                0 + newrect.height * 1,
                min(self.sz[1] - newrect.height * 1,
                    newrect.centery + curve[mid_idx - i - 1]))
            try:
                bbrect = font.render_to(bg_surf,
                                        newrect,
                                        c,
                                        rotation=rotations[mid_idx - i - 1])
            except ValueError:
                bbrect = font.render_to(bg_surf, newrect, c)
            bbrect.x = newrect.x
            bbrect.y = newrect.y - newrect.height
            char_bbs.append(bbrect)
            last_rect = newrect

        bg_arr = self.get_ga_image(bg_surf)

        # colour text
        bg_arr[..., 0] = cs[0]

        # border/shadow
        if fs['border']:
            l1_arr, l2_arr = self.get_bordershadow(bg_arr, cs[2])
        else:
            l1_arr = bg_arr

        # do rotation and perspective distortion
        affstate = self.affinestate.sample_transformation(l1_arr.shape)
        perstate = self.perspectivestate.sample_transformation(l1_arr.shape)
        l1_arr[..., 1] = self.apply_perspective_arr(l1_arr[..., 1], affstate,
                                                    perstate)
        if fs['border']:
            l2_arr[...,
                   1] = self.apply_perspective_arr(l2_arr[..., 1], affstate,
                                                   perstate)
        if char_annotations:
            char_bbs = self.apply_perspective_rectim(char_bbs, l1_arr[..., 1],
                                                     affstate, perstate)
            # order char_bbs by left to right
            xvals = [bb.x for bb in char_bbs]
            idx = [i[0] for i in sorted(enumerate(xvals), key=lambda x: x[1])]
            char_bbs = [char_bbs[i] for i in idx]

        if n.random.rand() < substring_crop and len(
                display_text) > 4 and char_annotations:
            # randomly crop to just a sub-string of the word
            start = n.random.randint(0, len(display_text) - 1)
            stop = n.random.randint(min(start + 1, len(display_text)),
                                    len(display_text))
            display_text = display_text[start:stop]
            char_bbs = char_bbs[start:stop]
            # get new bb of image
            bb = pygame.Rect(self.get_rects_union_bb(char_bbs, l1_arr))
        else:
            # get bb of text
            if fs['border']:
                bb = pygame.Rect(self.get_bb(
                    grey_blit(l2_arr, l1_arr)[..., 1]))
            else:
                bb = pygame.Rect(self.get_bb(l1_arr[..., 1]))
        if random_crop:
            bb.inflate_ip(10 * n.random.randn() + 15,
                          10 * n.random.randn() + 15)
        else:
            inflate_amount = int(0.4 * bb[3])
            bb.inflate_ip(inflate_amount, inflate_amount)

        # crop image
        l1_arr = self.imcrop(l1_arr, bb)
        if fs['border']:
            l2_arr = self.imcrop(l2_arr, bb)
        if char_annotations:
            # adjust char bbs
            for char_bb in char_bbs:
                char_bb.move_ip(-bb.x, -bb.y)
        canvas = (255 * n.ones(l1_arr.shape)).astype(l1_arr.dtype)
        canvas[..., 0] = cs[1]

        # add in natural images
        try:
            canvas = self.add_fillimage(canvas)
            l1_arr = self.add_fillimage(l1_arr)
            if fs['border']:
                l2_arr = self.add_fillimage(l2_arr)
        except Exception:
            pass

        # add per-surface distortions
        l1_arr = self.surface_distortions(l1_arr)
        if fs['border']:
            l2_arr = self.surface_distortions(l2_arr)

        # compose global image
        blend_modes = [
            MJBLEND_NORMAL, MJBLEND_ADD, MJBLEND_MULTINV, MJBLEND_SCREEN,
            MJBLEND_MAX
        ]
        count = 0
        while True:
            globalcanvas = grey_blit(l1_arr,
                                     canvas,
                                     blend_mode=random.choice(blend_modes))
            if fs['border']:
                globalcanvas = grey_blit(l2_arr,
                                         globalcanvas,
                                         blend_mode=random.choice(blend_modes))
            globalcanvas = globalcanvas[..., 0]
            std = n.std(globalcanvas.flatten())
            count += 1
            if std > 20:
                break
            if count > 10:
                print "\tcan't get good contrast"
                return None
        canvas = globalcanvas

        # add global distortions
        canvas = self.global_distortions(canvas)

        # noise removal
        canvas = ndimage.filters.median_filter(canvas, size=(3, 3))

        # resize
        if outheight is not None:
            if char_annotations:
                char_bbs = self.resize_rects(char_bbs, canvas, outheight)
            canvas = resize_image(canvas, newh=outheight)

        # FINISHED, SHOW ME SOMETHING
        if pygame_display:
            rgb_canvas = self.stack_arr((canvas, canvas, canvas))
            canvas_surf = pygame.surfarray.make_surface(
                rgb_canvas.swapaxes(0, 1))
            # for char_bb in char_bbs:
            #     pygame.draw.rect(canvas_surf, (255,0,0), char_bb, 2)
            self.screen = pygame.display.set_mode(canvas_surf.get_size())
            self.screen.blit(canvas_surf, (0, 0))
            pygame.display.flip()

        return {
            'image': canvas,
            'text': display_text,
            'label': label,
            'chars': n.array([[c.x, c.y, c.width, c.height] for c in char_bbs])
        }
Ejemplo n.º 20
0
# __author__ = "tenukibestmove"
""" this code allows to prepare the algorithm which repairs the groups and 
the interactive goban made with the sdl / pygame"""

import numpy as np
import pygame
import pygame.freetype as fnt
from GameMakerExceptions import *

fnt.init()
pygame.display.init()
pygame.display.set_mode((700, 500))

#Police pour le texte (sujette à changement)
main_font = fnt.Font("./wellbutrin.ttf", 18)

#Constantes du module (y en beaucoup)
ALPHABET = "A.B.C.D.E.F.G.H.I.J.K.L.M.N.O.P.Q.R.S.T.U.V.W.X.Y.Z".split('.')
ALPHANUM_DICT = {ALPHABET[i]: i for i in range(len(ALPHABET))}
BLACK_STONE = pygame.image.load("pierre.png").convert_alpha()
WHITE_STONE = pygame.image.load("pierre2.png").convert_alpha()
BLACK_TEXTSURFACE = main_font.render('Noir', (0, 0, 0))[0]
WHITE_TEXTSURFACE = main_font.render('Blanc', (255, 255, 255))[0]
PLAYER_TEXTSAFEZONE = main_font.render('Blanc', (0, 0, 0))[1]
VOID_SURFACE = pygame.Surface(
    (0, 0))  #Surface vide (même si ça ne sert pas, je la garde au cas où)
PLAYER_TURN_COORDINATES = (
    585, 50)  #Coordonnées graphiques pour l'affichage du tour actuel
TURN_NUMBER_COORDINATES = (
    520, 50)  #Coordonnées graphiques pour l'affichage du numéro de tour
Ejemplo n.º 21
0
class GL:
    FRAME = 0


if __name__ == '__main__':

    pygame.init()
    freetype.init(cache_size=64, resolution=72)
    SCREENRECT = pygame.Rect(0, 0, 800, 1024)
    screen = pygame.display.set_mode(SCREENRECT.size, pygame.HWSURFACE, 32)
    BACKGROUND = pygame.image.load('Assets\\background.jpg').convert()
    BACKGROUND = pygame.transform.scale(BACKGROUND, (SCREENRECT.size))
    BACKGROUND.set_alpha(None)
    # FONT = freetype.Font(os.path.join('Assets\\Fonts\\', 'Gtek Technology.ttf'), size=12)
    # print(pygame.font.get_fonts(), pygame.font.match_font('bitstreamverasans'))
    FONT = freetype.Font('C:\\Windows\\Fonts\\Arial.ttf')
    FONT.antialiased = False
    clock = pygame.time.Clock()
    screen.blit(BACKGROUND, (0, 0))
    sprite_group = pygame.sprite.Group()
    All = pygame.sprite.RenderUpdates()

    class Player:
        def __init__(self):
            pass

        def alive(self):
            return True

    player = Player()
Ejemplo n.º 22
0
    def test(self, test_text, target_dir):
        import numpy as np
        import matplotlib
        import matplotlib.pyplot as plt

        #
        # suported_fonts = {'HanDingJianZhongHei-2.ttf':1 ,'MicrosoftYaqiHei-2.ttf':1}
        suported_fonts = self.fontFac.get_supported_fonts(test_text)

        # size
        sizes = [20]  #np.linspace(*self.font_style_cfg['size'][0:2], 4)
        # oblique
        obliques = [False]  #[True, False]
        # rotation
        rotations = [0]  #[0, 10]
        # strong
        strongs = [True, False]
        # wide (not supput rotated)
        wides = [False]
        # strength
        strengths = [0.1]

        # underline (not supput rotated)
        underlines = [False]  #[True, False]

        # fringe
        fringes = [0]
        # render to surface
        for font_name, _ in suported_fonts.items():
            font_file = self.fontFac.fonts_dict[font_name][0]
            for size in sizes:
                for oblique in obliques:
                    for rotation in rotations:
                        for strong in strongs:
                            for wide in wides:
                                for strength in strengths:
                                    for underline in underlines:
                                        for pixel in fringes:
                                            if pixel == 0:
                                                h = 0
                                                w = 0
                                            else:
                                                h = pixel
                                                w = pixel
                                            font = freetype.Font(
                                                font_file, size=int(size))
                                            font.oblique = oblique
                                            font.rotation = int(rotation)
                                            font.strong = strong
                                            if font.rotation == 0:
                                                font.wide = wide
                                                font.underline = underline
                                            font.strength = strength

                                            rect = font.get_rect(test_text)
                                            surf = pygame.Surface(
                                                (rect.width, rect.height),
                                                pygame.locals.SRCALPHA, 32)
                                            font.render_to(
                                                surf, (0, 0), test_text)

                                            if pixel > 0:
                                                font.render_to(
                                                    surf, (pixel, pixel),
                                                    test_text)

                                            arr = pygame.surfarray.pixels_alpha(
                                                surf
                                            ).swapaxes(
                                                0, 1
                                            )  # 获取图像的透明度(当render_to只传fgcolor背景就是透明的,值为0)

                                            # str
                                            font_name_str = os.path.splitext(
                                                font_name)[0]
                                            font_string = f'font{size}{font_name_str}_oblique{int(font.oblique)}_rotation{font.rotation}_strong{int(font.strong)}_wide{int(font.wide)}_strength{round(font.strength,2)}_underline{int(font.underline)}{font.underline_adjustment}_fringe{round(h,1)}-{round(w,1)}'
                                            plt.figure(font_string)
                                            plt.imshow(255 - arr, cmap='gray')
                                            plt.savefig(
                                                os.path.join(
                                                    target_dir,
                                                    font_string + '.jpeg'))
                                            plt.close()
Ejemplo n.º 23
0
def main():
    global background, buttons, alpha, screen, initor, main_title, room, dirtyrects, mouse_x, mouse_y, eventname, eventparams, screen, block, reload, btnpressing
    room = "menu"
    huetic = 0
    dialogcounter = 0
    reload = 0
    block = 0
    temptemp = 0
    btnpressing = 0
    thirteencounter = 0

    # Initialize SDL components
    pygame.init()
    screen = pygame.display.set_mode(SCREENRECT.size, 0)
    clock = pygame.time.Clock()

    #loadresses
    for pic in uis:
        if pic[0:7] == "ui_help"[0:7] and pic[0:13] != "ui_help_neuro"[0:13]:
            exec("Img." + str(pic[:pic.find(".")]) + "=load_image('" +
                 main_dir.replace("\\", "/") + "/ui/" + str(pic) + "' , 1)")
            continue
        elif pic[0:13] == "ui_help_neuro"[0:13]:
            exec("Img." + str(pic[:pic.find(".")]) + "=load_image('" +
                 main_dir.replace("\\", "/") + "/ui/" + str(pic) + "' , 0)")
            continue

        exec("Img." + str(pic[:pic.find(".")]) + "=load_image('" +
             main_dir.replace("\\", "/") + "/ui/" + str(pic) + "' , 1)")

    for pic in bgs:
        exec("Img." + str(pic[:pic.find(".")]) + "=load_image('" +
             main_dir.replace("\\", "/") + "/bgs/" + str(pic) + "' , 0)")

    for pic in spr:
        exec("Img." + str(pic[:pic.find(".")]) + "=load_image('" +
             main_dir.replace("\\", "/") + "/spr/" + str(pic) + "' , 1)")

    initor = initializator()
    initor.init_main_window()

    while True:
        #uservars init
        huetic += 2
        if reload > 0:
            clock.tick(FRAMES_PER_SEC)
            reload -= 1
            continue

        if reload < 0: block = 0
        mainhue = round(math.cos(huetic / 31.4) * 70 + 80)

        dialogs = [
            "Гарри, вот ты где!",  #dd                                                          0                                              |
            "Я тебя повсюду разыскиваю.",  #dd                                                  1                                                      |
            "Быстрее направляйся в класс заклинаний, Люпин вовсю ведёт урок",  #dd              2                                                                                          |
            "Люпин в Хогварце?",  #harry                                                        3                                                |
            "Да, ненадолго. Обучает заклинаниям.",  #dd                                         4                                                               |
            "Уже иду!",  #harry                                                                 5                                       |
            "Извините, я опоздал. Можно зайти?",  # harry                                       6                                |
            "Да, конечно. Сегодня мы изучаем 3 новых заклинания.",  # Lupin                     7                                |
            "Дети, это заклинание называется алохомора.",  #lupintoclass
            "чтобы его совершить проведите так палочкой",  #screen.blit ()scheme                                                                       8                          |
            "это заклинание называется акцио.",  # lupintoclass
            "Для него нужен лишь короткий взмах",  #screen.blit ()scheme
            "А это заклинание называется силенцио.",  # lupintoclass
            "Оно уже посложнее предыдущих",  #screen.blit ()scheme
            "Поттер, попробуй акцио. ",  #создать инстанс капчурера
            [
                "хорошо, теперь попробуй алохомору  ",
                "хорошо, теперь попробуй силенцио "
            ],  #l
            "Но профессор, как вы поняли, какое заклинание я применил?",  #g
            "Вы же всего лишь картинка в программе!",  #g
            "Как и ты. Дело в том, что твоё заклинание обрабатывает нейросеть.",  #l блит имэг
            "Вначале она принимает на вход 784 фрагмента твоего заклинания.",  #l
            "Затем она обрабатывает его и один из 3 выходных нейронов срабатывает.",  #l
            "На обучение этой нейросети потребовалось 150 тестов.",  #l
            "После тестов связи между нейронами корректируются для корректной работы.",  #l
            "Игра окончена. Для большей информации кликните на кнопку в меню 'инфо'",  #l
            ""
        ]

        faces = [[Img.potter0, Img.double_door1],
                 [Img.potter0, Img.double_door1],
                 [Img.potter0, Img.double_door1],
                 [Img.potter1, Img.double_door0],
                 [Img.potter0, Img.double_door1],
                 [Img.potter1, Img.double_door0], [Img.potter1, Img.lupin0],
                 [Img.potter0, Img.lupin1], [Img.lupin1, None],
                 [Img.lupin1, None], [Img.lupin1, None], [Img.lupin1, None],
                 [Img.lupin1, None], [Img.lupin1, None], [Img.lupin1, None],
                 [Img.lupin1, None], [Img.potter1, Img.lupin0],
                 [Img.potter1, Img.lupin0], [Img.potter0, Img.lupin1],
                 [Img.potter0, Img.lupin1], [Img.potter0, Img.lupin1],
                 [Img.potter0, Img.lupin1], [Img.potter0, Img.lupin1],
                 [None, None], [None, None]]

        actions = [
            None, None, None, None, None, None, None, None,
            "screen.blit(Img.ui_help_alohomora, (400-140,0)); block=1; reload=900",
            None,
            "screen.blit(Img.ui_help_accio, (400-140,0)); block=1; reload=900",
            None,
            "screen.blit(Img.ui_help_silencio, (400-140,0)); block=1; reload=15000",
            None, None, None, None, None,
            "screen.blit(Img.ui_help_neuro_struct, (400-140,0)); block=1; reload=900",
            None, None, None, None, None, "exit()"
        ]

        backs = [
            Img.bg_coridor,
            Img.bg_coridor,
            Img.bg_coridor,
            Img.bg_coridor,
            Img.bg_coridor,
            Img.bg_coridor,
            Img.bg_class_new,
            Img.bg_class_new,
        ]

        for i in range(len(dialogs)):
            if type(dialogs[i]) is not list:
                dialogs[i] = dialogs[i] + " "

        #
        clock.tick(FRAMES_PER_SEC)

        # Gather Events (idk what means gather)
        pygame.event.pump()
        keystate = pygame.key.get_pressed()
        if keystate[K_ESCAPE] or pygame.event.peek(QUIT):
            break
        mouse_x, mouse_y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]
        #

        # buttons hover
        for btnhover in buttons:
            if btnhover.rect[1] <= mouse_y <= btnhover.rect[1] + btnhover.rect[3] and \
                    btnhover.rect[0] <= mouse_x <= btnhover.rect[0] + btnhover.rect[2]:
                btnhover.color = (230, 230, 230, 128)
            else:
                btnhover.color = (255, 255, 255, 0)
        #

        # geteventinfo
        for e in pygame.event.get():

            eventname, eventparams = 0, 0
            if e.type != MOUSEMOTION:
                eventname, eventparams = pygame.event.event_name(
                    e.type), e.dict
            #

            #buttonspressing
            if eventname == "MouseButtonUp" and eventparams['button'] == 1:
                for chckprss in buttons:
                    if      chckprss.rect[1]<= mouse_y <= chckprss.rect[1]+chckprss.rect[3] and \
                            chckprss.rect[0]<= mouse_x <= chckprss.rect[0]+chckprss.rect[2]:
                        chckprss.pressed()
            if eventname == "MouseButtonDown" and eventparams['button'] == 1:
                btnpressing = 1
            if eventname == "MouseButtonUp" and eventparams['button'] == 1:
                btnpressing = 0
            #

        # dialog draw
        if room == "intro":
            if dialogcounter > 15:
                block = 0
            try:

                #pygame.display.update(SCREENRECT)
                mbox.update()
                temp = mbox.step(screen)
                mbox.draw(screen)
                pygame.display.update(SCREENRECT)
                block = 1
                if temp == "accio":
                    del mbox
                    print(temp)
                    block = 0
                    dialogcounter = 15

                if temp == "alohomora" and dialogcounter == 15:
                    del mbox
                    print(temp)
                    block = 0
                    thirteencounter = 1

                if temp == "silencio" and dialogcounter == 15 and thirteencounter == 1:
                    del mbox
                    print(temp)
                    block = 0
                    dialogcounter = 16

            except Exception as e:

                if dialogcounter == 14 or dialogcounter == 15:
                    print(e)
                    mbox = MagicBox(250 + 280 / 2, 10 + 280 / 2,
                                    Img.ui_capturer)

                    mbox.draw(screen)
                    mbox.step(screen)
                    dirtyrects = []
                    dirtyrects.append(SCREENRECT)

            try:
                currback = backs[dialogcounter]
            except:
                pass
            background = currback
            if dialogcounter != 14 and dialogcounter != 15:
                screen.blit(background, (0, 0))

            # next text and pictures when press
            if eventname == "MouseButtonDown" and eventparams[
                    'button'] == 1 and reload <= 0 and block != 1 and dialogcounter != 15 and dialogcounter != 14:
                reload = 50
                dialogcounter += 1
                dprint(dialogcounter)
            #

            for btnhover in buttons:
                if btnhover.rect[1] <= mouse_y <= btnhover.rect[1] + btnhover.rect[3] and \
                        btnhover.rect[0] <= mouse_x <= btnhover.rect[0] + btnhover.rect[2]:
                    btnhover.color = (230, 230, 230, 128)
                else:
                    btnhover.color = (255, 255, 255, 0)

            for actor in buttons:
                actor.draw_text(screen)

            LETTERAMOUNT = 29

            if dialogcounter != 15:
                diatext = [
                    dialogs[dialogcounter]
                    [0:dialogs[dialogcounter].rfind(" ", 0, LETTERAMOUNT)],
                    dialogs[dialogcounter]
                    [dialogs[dialogcounter].rfind(" ", 0, LETTERAMOUNT) +
                     1:dialogs[dialogcounter].rfind(
                         " ", dialogs[dialogcounter].
                         rfind(" ", 0, LETTERAMOUNT), dialogs[dialogcounter].
                         rfind(" ", 0, LETTERAMOUNT) + LETTERAMOUNT)],
                    dialogs[dialogcounter][dialogs[dialogcounter].rfind(
                        " ", dialogs[dialogcounter].
                        rfind(" ", 0, LETTERAMOUNT), dialogs[dialogcounter].
                        rfind(" ", 0, LETTERAMOUNT) + LETTERAMOUNT) +
                                           1:LETTERAMOUNT * 4]
                ]
            else:

                diatext = [
                    dialogs[dialogcounter][thirteencounter]
                    [0:dialogs[dialogcounter][thirteencounter].
                     rfind(" ", 0, LETTERAMOUNT)],
                    dialogs[dialogcounter][thirteencounter]
                    [dialogs[dialogcounter][thirteencounter].
                     rfind(" ", 0, LETTERAMOUNT) +
                     1:dialogs[dialogcounter][thirteencounter].rfind(
                         " ", dialogs[dialogcounter][thirteencounter].
                         rfind(" ", 0, LETTERAMOUNT), dialogs[dialogcounter]
                         [thirteencounter].rfind(" ", 0, LETTERAMOUNT) +
                         LETTERAMOUNT)],
                    dialogs[dialogcounter][thirteencounter]
                    [dialogs[dialogcounter][thirteencounter].rfind(
                        " ", dialogs[dialogcounter][thirteencounter].
                        rfind(" ", 0, LETTERAMOUNT), dialogs[dialogcounter]
                        [thirteencounter].rfind(" ", 0, LETTERAMOUNT) +
                        LETTERAMOUNT) + 1:LETTERAMOUNT * 4]
                ]

            font = freetype.Font(SANS, 40)
            #draw faces
            if faces[dialogcounter][0] is not None:
                screen.blit(
                    pygame.transform.scale(faces[dialogcounter][0],
                                           (256, 256)),
                    (0, 450 - 150 - 256 + 50))
            if faces[dialogcounter][1] is not None:
                mirroredimg = pygame.transform.flip(faces[dialogcounter][1],
                                                    True, False)
                screen.blit(pygame.transform.scale(mirroredimg, (256, 256)),
                            (800 - 256, 450 - 150 - 256 + 50))
            #
            if True:
                screen.blit(
                    pygame.transform.scale(
                        Img.ui_dialog_bg, (Img.ui_dialog_bg.get_width() * 2,
                                           Img.ui_dialog_bg.get_height() * 2)),
                    (0, 450 - 150))  # dialogbg
                dirtyrects.append(SCREENRECT)

            yoffset = 5
            for text in diatext:
                #dprint(yoffset)
                font.render_to(screen, (10, 450 - 150 + 10 + yoffset),
                               text,
                               pygame.Color(200, 50, 200, 230),
                               None,
                               style=pygame.freetype.STYLE_STRONG)
                font.render_to(screen, (10, 450 - 150 + 11 + yoffset),
                               text,
                               pygame.Color(200, 0, 50, 150),
                               None,
                               style=pygame.freetype.STYLE_STRONG)
                yoffset += 40
            curraction = actions[dialogcounter]
            if curraction is not None:
                exec(curraction)

        #

        # Clear screen and update actors
        if room != "intro":
            for actor in buttons:
                actor.erase(screen, background)
                actor.update()
            try:
                for actor in [main_title]:
                    actor.erase(screen, background)
                    actor.update()
            except:
                pass
            #
            # Draw everybody

            for actor in buttons:
                actor.draw(screen)
                actor.draw_text(screen)
            try:
                main_title.font_size = 100
                main_title.draw_text(screen,
                                     color2=pygame.Color(
                                         mainhue % 255,
                                         min((50 + mainhue) % 255, 255),
                                         min((70 + mainhue) % 255, 255), 255),
                                     color1=pygame.Color(30, 30, 30),
                                     style=pygame.freetype.STYLE_DEFAULT)
            except:
                pass
        #dirtyrects.append(SCREENRECT)
        pygame.display.update(dirtyrects)
        dirtyrects = []
        #

    pygame.time.wait(50)
Ejemplo n.º 24
0
def run():
    pygame.init()

    fontdir = os.path.dirname(os.path.abspath (__file__))
    font = freetype.Font(os.path.join (fontdir, "data", "sans.ttf"))

    screen = pygame.display.set_mode((800, 600))
    screen.fill (colors["grey_light"])

    font.underline_adjustment = 0.5
    font.pad = True
    font.render_to(screen, (32, 32), "Hello World", colors["red"],
                   colors['grey_dark'], ptsize=64,
                   style=freetype.STYLE_UNDERLINE|freetype.STYLE_OBLIQUE)
    font.pad = False

    font.render_to(screen, (32, 128), "abcdefghijklm", colors["grey_dark"],
                   colors["green"], ptsize=64)

    font.vertical = True
    font.render_to(screen, (32, 200), "Vertical?", colors["blue"],
                   None, ptsize=32)
    font.vertical = False

    font.render_to(screen, (64, 190), "Let's spin!", colors["red"],
                   None, ptsize=48, rotation=55)

    font.render_to(screen, (160, 290), "All around!", colors["green"],
                   None, ptsize=48, rotation=-55)

    font.render_to(screen, (250, 220), "and BLEND",
                   pygame.Color(255, 0, 0, 128), None, ptsize=64)

    font.render_to(screen, (265, 237), "or BLAND!",
                   pygame.Color(0, 0xCC, 28, 128), None, ptsize=64)

    # Some pinwheels
    font.origin = True
    for angle in range(0, 360, 45):
        font.render_to(screen, (200, 500), ")", pygame.Color('black'),
                       ptsize=48, rotation=angle)
    font.vertical = True
    for angle in range(15, 375, 30):
        font.render_to(screen, (600, 400), "|^*", pygame.Color('orange'),
                       ptsize=48, rotation=angle)
    font.vertical = False
    font.origin = False

    utext = pygame.compat.as_unicode(r"I \u2665 Unicode")
    font.render_to(screen, (298, 320), utext, pygame.Color(0, 0xCC, 0xDD),
                   None, ptsize=64)

    utext = pygame.compat.as_unicode(r"\u2665")
    font.render_to(screen, (480, 32), utext, colors["grey_light"],
                   colors["red"], ptsize=148)

    font.render_to(screen, (380, 380), "...yes, this is an SDL surface",
                   pygame.Color(0, 0, 0),
                   None, ptsize=24, style=freetype.STYLE_STRONG)

    pygame.display.flip()

    while 1:
        if pygame.event.wait().type in (QUIT, KEYDOWN, MOUSEBUTTONDOWN):
            break

    pygame.quit()
Ejemplo n.º 25
0
 def on_init(self) -> None:
     """Load font based on current localization setting."""
     self.font = freetype.Font(
         f'assets/fonts/monogram_extended_{CONFIG.localization}.ttf')
Ejemplo n.º 26
0
usleep = lambda x: time.sleep(x/1000000.0)

#Initialization
os.putenv('SDL_FBDEV', '/dev/fb0')
os.putenv('SDL_VIDEODRIVER', 'fbcon')
#os.putenv('SDL_MOUSEDRV', 'TSLIB')
#os.putenv('SDL_MOUSEDEV', '/dev/input/event0')
pygame.init()

#LCD Fill test
pygame.mouse.set_visible(False)
lcd = pygame.display.set_mode((480, 320))

#Font drawing
SURFACE = pygame.display.get_surface()
FONT_LT = freetype.Font("../fonts/HelveticaNeueLTStd-Lt.otf", size=64);
FONT_MD = freetype.Font("../fonts/HelveticaNeueLTStd-Md.otf", size=64);
FONT_ICONS = freetype.Font("../fonts/materialdesignicons-webfont.ttf", size=64, ucs4=True);

def clearScreen(color):
	global COLOR_BG
	COLOR_BG = color
	lcd.fill(COLOR_BG)

def colorAlphaMult(color, alpha):
    return pygame.Color(color.r, color.g, color.b, int(math.floor(color.a * alpha)))

def updateTimeBottom():
	#Get current time
	str_time = FONT_LT.render(strftime("%I:%M"), fgcolor=COLOR_WHITE, size=48);
	str_time[1].center = (240, 240)
Ejemplo n.º 27
0
    def __call__(self, text):
        font_name, font_file = self.fontFac.generate_font(text)
        # size
        size = int(get_random_value(*self.font_style_cfg['size']))
        font = freetype.Font(font_file, size=int(size))
        # oblique
        if random.random() < self.font_style_cfg['oblique']:
            font.oblique = True
        # rotation
        if random.random() < self.font_style_cfg['rotation'][0]:
            degree = get_random_value(*self.font_style_cfg['rotation'][1])
            degree = int(degree)
            font.rotation = degree
        if font_name not in self.pygame_cfg['FONTS']['fonts_strong_false']:
            """
            some fonts not suitable for strong effect
            """
            # strong
            if random.random() < self.font_style_cfg['strong']:
                font.strong = True
            # wide (not supput rotated)
            if font.rotation == 0 and font.strong == False:
                if random.random() < self.font_style_cfg['wide']:
                    font.wide = True
            # strength
            if font.strong or font.wide:
                strength = get_random_value(*self.font_style_cfg['strength'])
                strength = round(strength, 2)
                font.strength = strength

        # underline (not supput rotated)
        if font.rotation == 0:
            if random.random() < self.font_style_cfg['underline'][0]:
                font.underline = True
                adj_factor = get_random_value(
                    *self.font_style_cfg['underline'][1])
                adj_factor = round(adj_factor, 2)
                font.underline_adjustment = adj_factor

        # rendering
        if self.font_style_cfg['boundingbox']:
            surf, bounding_boxes = self.render_with_bounding_box(font, text)

        else:
            # render to surface
            surf, rect = font.render(text)
            if rect.height <= (size * 0.6):
                # height too small like '-', use size as height
                surf = pygame.Surface((rect.width, size),
                                      pygame.locals.SRCALPHA, 32)
                font.render_to(surf, (0, int((size - rect.height) / 2)), text)

            bounding_boxes = None

        # box for text
        if not font.underline:
            if random.random() < self.font_style_cfg['box'][0]:
                line_width = int(
                    get_random_value(*self.font_style_cfg['box'][1]))
                x, y = 0, 0  # position of box
                if random.random() < self.font_style_cfg['box_pos']:
                    x = int(
                        get_random_value(*self.font_style_cfg['box_pos_x']))
                    y = int(
                        get_random_value(*self.font_style_cfg['box_pos_y']))
                pygame.draw.rect(surf, (255, 0, 0),
                                 surf.get_rect().move(x, y), line_width)

        arr = pygame.surfarray.pixels_alpha(surf).swapaxes(
            0, 1)  # 获取图像的透明度(当render_to只传fgcolor背景就是透明的,值为0)

        # str
        font_name_str = os.path.splitext(font_name)[0]
        font_string = f'font{size}{font_name_str}_oblique{int(font.oblique)}_rotation{font.rotation}_strong{int(font.strong)}_wide{int(font.wide)}_strength{round(font.strength,2)}_underline{int(font.underline)}{font.underline_adjustment}'

        return font_string, arr, bounding_boxes
Ejemplo n.º 28
0
# Size tuples
WINDOW_SIZE = (800, 600)
SURFACE_SIZE = (400, 300)

# Temporarily put this here so that code runs in Joshua's computer
# Will comment this out when I push
pg.init()

# Initialise sound
pg.mixer.init(44100, 16, 2, 512)

# Freetype font
# Initialise the FreeType font system
ft.init()
freetype = ft.Font("assets/fonts/pixChicago.ttf", 8)
freetype.antialiased = False


class Scene:
    """Represents a scene in the program, which is analogous to the state of the game"""
    sound_library = {
        "Scroll": pg.mixer.Sound("assets/sound/sfx/confirm.ogg"),
        "Confirm": pg.mixer.Sound("assets/sound/sfx/confirm.ogg")
    }

    def __init__(self):
        self.manager = SceneManager(self)
        self.game_display = pg.Surface(SURFACE_SIZE)

    def handle_events(self):
Ejemplo n.º 29
0
    def gen_srnet_data_with_background(self):

        while True:
            # choose font, text and bg
            font = np.random.choice(self.font_list)
            text1, text2 = np.random.choice(self.text_list), np.random.choice(
                self.text_list)

            upper_rand = np.random.rand()
            if upper_rand < data_cfg.capitalize_rate + data_cfg.uppercase_rate:
                text1, text2 = text1.capitalize(), text2.capitalize()
            if upper_rand < data_cfg.uppercase_rate:
                text1, text2 = text1.upper(), text2.upper()
            bg = cv2.imread(random.choice(self.bg_list))

            # init font
            font = freetype.Font(font)
            #font = pygame.font.Font(font)
            font.antialiased = True
            font.origin = True

            # choose font style
            font.size = np.random.randint(data_cfg.font_size[0],
                                          data_cfg.font_size[1] + 1)
            font.underline = np.random.rand() < data_cfg.underline_rate
            font.strong = np.random.rand() < data_cfg.strong_rate
            font.oblique = np.random.rand() < data_cfg.oblique_rate

            # render text to surf
            param = {
                'is_curve':
                np.random.rand() < data_cfg.is_curve_rate,
                'curve_rate':
                data_cfg.curve_rate_param[0] * np.random.randn() +
                data_cfg.curve_rate_param[1],
                'curve_center':
                np.random.randint(0, len(text1))
            }
            surf1, bbs1 = render_text_mask.render_text(font, text1, param)
            param['curve_center'] = int(param['curve_center'] / len(text1) *
                                        len(text2))
            surf2, bbs2 = render_text_mask.render_text(font, text2, param)

            # get padding
            padding_ud = np.random.randint(data_cfg.padding_ud[0],
                                           data_cfg.padding_ud[1] + 1, 2)
            padding_lr = np.random.randint(data_cfg.padding_lr[0],
                                           data_cfg.padding_lr[1] + 1, 2)
            padding = np.hstack((padding_ud, padding_lr))

            # perspect the surf
            rotate = data_cfg.rotate_param[0] * np.random.randn(
            ) + data_cfg.rotate_param[1]
            zoom = data_cfg.zoom_param[0] * np.random.randn(
                2) + data_cfg.zoom_param[1]
            shear = data_cfg.shear_param[0] * np.random.randn(
                2) + data_cfg.shear_param[1]
            perspect = data_cfg.perspect_param[0] * np.random.randn(
                2) + data_cfg.perspect_param[1]
            surf1 = render_text_mask.perspective(surf1, rotate, zoom, shear,
                                                 perspect, padding)  # w first
            surf2 = render_text_mask.perspective(surf2, rotate, zoom, shear,
                                                 perspect, padding)  # w first

            # choose a background
            surf1_h, surf1_w = surf1.shape[:2]
            surf2_h, surf2_w = surf2.shape[:2]
            surf_h = max(surf1_h, surf2_h)
            surf_w = max(surf1_w, surf2_w)
            surf1 = render_text_mask.center2size(surf1, (surf_h, surf_w))
            surf2 = render_text_mask.center2size(surf2, (surf_h, surf_w))

            bg_h, bg_w = bg.shape[:2]
            if bg_w < surf_w or bg_h < surf_h:
                continue
            x = np.random.randint(0, bg_w - surf_w + 1)
            y = np.random.randint(0, bg_h - surf_h + 1)
            t_b = bg[y:y + surf_h, x:x + surf_w, :]

            # augment surf
            surfs = [[surf1, surf2]]
            self.surf_augmentor.augmentor_images = surfs
            surf1, surf2 = self.surf_augmentor.sample(1)[0]

            # bg augment
            bgs = [[t_b]]
            self.bg_augmentor.augmentor_images = bgs
            t_b = self.bg_augmentor.sample(1)[0][0]

            # render standard text
            i_t = render_standard_text.make_standard_text(
                self.standard_font_path, text2, (surf_h, surf_w))
            # get min h of bbs
            min_h1 = np.min(bbs1[:, 3])
            min_h2 = np.min(bbs2[:, 3])
            min_h = min(min_h1, min_h2)

            # get font color
            if np.random.rand() < data_cfg.use_random_color_rate:
                fg_col, bg_col = (np.random.rand(3) * 255.).astype(
                    np.uint8), (np.random.rand(3) * 255.).astype(np.uint8)
            else:
                fg_col, bg_col = colorize.get_font_color(
                    self.colorsRGB, self.colorsLAB, t_b)

            # colorful the surf and conbine foreground and background
            param = {
                'is_border':
                np.random.rand() < data_cfg.is_border_rate,
                'bordar_color':
                tuple(np.random.randint(0, 256, 3)),
                'is_shadow':
                np.random.rand() < data_cfg.is_shadow_rate,
                'shadow_angle':
                np.pi / 4 * np.random.choice(data_cfg.shadow_angle_degree) +
                data_cfg.shadow_angle_param[0] * np.random.randn(),
                'shadow_shift':
                data_cfg.shadow_shift_param[0, :] * np.random.randn(3) +
                data_cfg.shadow_shift_param[1, :],
                'shadow_opacity':
                data_cfg.shadow_opacity_param[0] * np.random.randn() +
                data_cfg.shadow_opacity_param[1]
            }
            _, i_s = colorize.colorize(surf1, t_b, fg_col, bg_col,
                                       self.colorsRGB, self.colorsLAB, min_h,
                                       param)
            t_t, t_f = colorize.colorize(surf2, t_b, fg_col, bg_col,
                                         self.colorsRGB, self.colorsLAB, min_h,
                                         param)

            # skeletonization
            t_sk = skeletonization.skeletonization(surf2, 127)
            break

        return [i_t, i_s, t_sk, t_t, t_b, t_f, surf2]
Ejemplo n.º 30
0
    gradient = linspace(255, 0, line.w)
    row = repeat(gradient[:, newaxis], [line.h], 1)

    array = dstack((rgb_array, row)).astype(dtype=uint8)
    # Create a line with alpha value coded in linear gradient degradation
    GR_LINE = pygame.image.frombuffer((array.transpose(1, 0, 2)).copy(order='C').astype(uint8),
                                      (array.shape[:2][0], array.shape[:2][1]), 'RGBA')
    GR_LINE = pygame.transform.smoothscale(GR_LINE, (380, GR_LINE.get_height()))
    i = 0
    FRAME = 0
    GL.FRAME = FRAME
    GL.PLAYER_GROUP = 0
    STOP_GAME = False
    QUIT = False

    font = freetype.Font('Assets\\Fonts\\Gtek Technology.ttf', size=14)

    All = LayeredUpdatesModified()

    """
    # PLAYER WIN 
    PlayerLost.containers = All
    PlayerLost.DIALOGBOX_READOUT_RED = DIALOGBOX_READOUT_RED
    PlayerLost.SKULL = SKULL
    PlayerLost(gl_=GL, font_=font, image_=FINAL_MISSION, layer_=0)
    """
    # PLAYER LOST
    PlayerWin.containers = All
    PlayerWin.DIALOGBOX_READOUT_RED = DIALOGBOX_READOUT_RED
    PlayerWin.SKULL = SKULL
    PlayerWin(gl_=GL, font_=font, image_=FINAL_MISSION, layer_=0, score_=950000)