def init(): font.init() main_font = font.Font(os.path.join( FONTPATH, "Press_Start_2P/PressStart2P-Regular.ttf"), size=FONT_DEFAULT_SIZE) main_font.antialiased = False FONTS.update({"main": main_font})
def get_font_image_from_pygame(font_file, font_size, text): import pygame from pygame import freetype pygame.init() freetype.init() try: font = freetype.Font(font_file, font_size) font.antialiased = random.random()>0.5 styles = [freetype.STYLE_DEFAULT,freetype.STYLE_NORMAL,freetype.STYLE_OBLIQUE, freetype.STYLE_STRONG,freetype.STYLE_UNDERLINE,freetype.STYLE_WIDE] while True: try: style =random.choice(styles) rtext = font.render(text, (0, 0, 0), (255, 255, 255), style=style)[0] break except: print("rechoise font style for",font_file) data = pygame.image.tostring(rtext, 'RGBA') _img = Image.frombytes("RGBA",rtext.get_size(),data) size = _img.size img=Image.new("RGBA",(size[0]+100,size[1]+100),(255,255,255)) img.paste(_img,(50,50)) return img except: raise Exception("Error font %s" % font_file)
def __init__(self): freetype.init() cur_file_path = os.path.dirname(__file__) font_dir = os.path.join(cur_file_path, data_cfg.font_dir) self.font_list = os.listdir(font_dir) self.font_list = [os.path.join(font_dir, font_name) for font_name in self.font_list] self.standard_font_path = os.path.join(cur_file_path, data_cfg.standard_font_path) color_filepath = os.path.join(cur_file_path, data_cfg.color_filepath) self.colorsRGB, self.colorsLAB = colorize.get_color_matrix(color_filepath) text_filepath = os.path.join(cur_file_path, data_cfg.text_filepath) self.text_list = open(text_filepath, 'r').readlines() self.text_list = [text.strip() for text in self.text_list] bg_filepath = os.path.join(cur_file_path, data_cfg.bg_filepath) self.bg_list = open(bg_filepath, 'r').readlines() self.bg_list = [img_path.strip() for img_path in self.bg_list] self.surf_augmentor = Augmentor.DataPipeline(None) self.surf_augmentor.random_distortion(probability = data_cfg.elastic_rate, grid_width = data_cfg.elastic_grid_size, grid_height = data_cfg.elastic_grid_size, magnitude = data_cfg.elastic_magnitude) self.bg_augmentor = Augmentor.DataPipeline(None) self.bg_augmentor.random_brightness(probability = data_cfg.brightness_rate, min_factor = data_cfg.brightness_min, max_factor = data_cfg.brightness_max) self.bg_augmentor.random_color(probability = data_cfg.color_rate, min_factor = data_cfg.color_min, max_factor = data_cfg.color_max) self.bg_augmentor.random_contrast(probability = data_cfg.contrast_rate, min_factor = data_cfg.contrast_min, max_factor = data_cfg.contrast_max)
def initialize(): print("Initializing") pygame.display.init() freetype.init() start_screen() pygame.display.flip()
def get_font_height_to_size_ratio(font_name): """ Find the ratio between a font size and the corresponding textbox height in pixels. The returned ratio is height/size :type font_name: str """ freetype.init() font = Font(find_font(font_name), size=100) size = font.size("hfbpqgXQ,") return size[1] / 100.0
def __init__(self, text, font_path, surface_width, fgcolor): self.text = text if not freetype.get_init(): freetype.init() self.font = freetype.Font(font_path) self.rendered_text, self.rendered_rect = self.font.render( self.text, fgcolor) self.fgcolor = fgcolor self.rendered_rect.y = 0 self.rendered_rect.x = (surface_width - self.rendered_rect.width) / 2
def main(): pygame.init() freetype.init() font = '/home/qianyu/fonts/english_ttf/arial.ttf' font = freetype.Font(font) font.antialiased = True font.origin = True text = 'canvas' shape = (224, 448) i_t = make_standard_text(font, text, shape) cv2.imshow('i_t', i_t) cv2.waitKey()
def draw(self): """ Inicializa la fuente (por defecto del sistema) y la pinta en el lienzo con la posición, letra y color establecidas :return: """ # print(self.posicion) freetype.init() font = freetype.Font(None, 12) font.render_to(surf=self.screen, dest=self.posicion, text=self.aminoacido, fgcolor=self.color)
def Init(self): global G_gameInfo, G_surface # here we set the size of the window and its caption text G_surface = pygame.display.set_mode( (G_gameInfo["width"], G_gameInfo["height"]) ) pygame.display.set_caption( G_gameInfo["gameTitle"] ) # we need all text fonts ready before starting drawing freetype.init() self.bigTitleFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["bigTitle"]["size"] ) self.smallTitleFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["smallTitle"]["size"] ) self.winTitleFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["winTitle"]["size"] ) self.newGameFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["newGame"]["tsize"] ) self.scoreTitleFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["scoreTitle"]["tsize"] ) self.scoreValueFont = freetype.Font( G_gameInfo["tileFont"], G_gameInfo["scoreValue"]["tsize"] )
def setUp(self): ft.init() if 'fixed' not in self._TEST_FONTS: # Inconsolata is an open-source font designed by Raph Levien # Licensed under the Open Font License # http://www.levien.com/type/myfonts/inconsolata.html self._TEST_FONTS['fixed'] = ft.Font(self._fixed_path) if 'sans' not in self._TEST_FONTS: # Liberation Sans is an open-source font designed by Steve Matteson # Licensed under the GNU GPL # https://fedorahosted.org/liberation-fonts/ self._TEST_FONTS['sans'] = ft.Font(self._sans_path)
def __init__(self, lvl, sizex, backscroll, font_path=None, font_size=48): pygame.sprite.Sprite.__init__(self) freetype.init() self.lvl = lvl self.sizex = sizex self.ground_list = pygame.sprite.Group() self.plat_list = pygame.sprite.Group() self.enemy_list = pygame.sprite.Group() self.myfont = None self.settings_values(200,200,30,4,backscroll) if font_path is not None and font_size is not None: self.myfont = freetype.Font(font_path, font_size)
def __init__(self, pos, width, height): self.border_overlap = 5 self.pos = pos self.border_pos = (pos[0] - self.border_overlap, pos[1] - self.border_overlap) self.width = width self.border_width = width self.height = height self.border_height = height freetype.init() self.font = freetype.SysFont("Ariel", 24) self.current_text = '' self.current_colour = (0, 0, 0) self.history = deque() self.text_size = 24 self.text_space = 25
def test_resolution(self): was_init = ft.was_init() if not was_init: ft.init() try: ft.set_default_resolution() resolution = ft.get_default_resolution() self.assertEqual(resolution, 72) new_resolution = resolution + 10 ft.set_default_resolution(new_resolution) self.assertEqual(ft.get_default_resolution(), new_resolution) ft.init(resolution=resolution+20) self.assertEqual(ft.get_default_resolution(), new_resolution) finally: ft.set_default_resolution() if was_init: ft.quit()
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
class Button(sp.DirtySprite): COLOR = (0, 255, 0) COLORO = (0, 63, 0) COLORP = (0, 127, 0) pgfont.init() FONT = pgfont.SysFont('Tahoma', 16) def __init__(self, text, rect, fn, args=tuple()): super().__init__() self.text = text self.rect = rect self.fn = fn self.args = args self.imageBase = pg.Surface((rect.width, rect.height)) self.imageMouseOver = pg.Surface((rect.width, rect.height)) self.imageMousePress = pg.Surface((rect.width, rect.height)) self.image = self.imageBase self.__createImages__() self.pressed = False def __createImages__(self): text_image, r = Button.FONT.render(self.text, Button.COLOR) text_top_left = ((self.rect.width - text_image.get_width()) // 2, (self.rect.height - text_image.get_height()) // 2) img_rect = self.image.get_rect() gfx.rectangle(self.imageBase, img_rect, Button.COLOR) self.imageBase.blit(text_image, text_top_left) self.imageMouseOver.fill(Button.COLORO) gfx.rectangle(self.imageMouseOver, img_rect, Button.COLOR) self.imageMouseOver.blit(text_image, text_top_left) self.imageMousePress.fill(Button.COLORP) gfx.rectangle(self.imageMousePress, img_rect, Button.COLOR) self.imageMousePress.blit(text_image, text_top_left) def contains_pt(self, pt): return self.rect.collidepoint(pt) def mouse_over(self): self.image = self.imageMouseOver def un_mouse_over(self): self.image = self.imageBase def press(self): self.image = self.imageMousePress self.pressed = True def unpress(self): self.image = self.imageBase self.pressed = False def release(self): self.image = self.imageBase if self.pressed: self.fn(*self.args)
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
class MultilineLabel(sp.Sprite): COLOR = Color.GREEN pgfont.init() FONT = pgfont.SysFont('Tahoma', 20) PARA_MARGIN = 15 LINE_MARGIN = 5 def __init__(self, text, x, y, max_w): super().__init__() self.text = text self.x, self.y = x, y self.maxW = max_w self.__createImage__() def __createImage__(self): para_list = [] self.h = 0 for paragraph in self.text.splitlines(): sf, h = self.__createParagraphImage__(paragraph) para_list.append((sf, h)) self.h += h + MultilineLabel.PARA_MARGIN self.image = pg.Surface((self.maxW, self.h)) curr_y = 0 for sf, h in para_list: self.image.blit(sf, (0, curr_y)) curr_y += h + MultilineLabel.PARA_MARGIN def __createParagraphImage__(self, text): word_list = text.split() line_list = [] line_sf_list = [] h = 0 next_line = word_list.pop(0) while next_line: curr_line, next_line = next_line, "" while MultilineLabel.FONT.get_rect(curr_line).width < self.maxW: if not word_list: break curr_line += " " + word_list.pop(0) else: curr_line, next_line = curr_line.rsplit(" ", 1) line_list.append(curr_line) for l in line_list: sf, r = MultilineLabel.FONT.render(l, MultilineLabel.COLOR) line_sf_list.append((sf, r)) h += r.height + MultilineLabel.LINE_MARGIN image = pg.Surface((self.maxW, h)) curr_y = 0 for sf, r in line_sf_list: image.blit(sf, (0, curr_y)) curr_y += r.height + MultilineLabel.LINE_MARGIN return image, h @property def rect(self): return pg.Rect(self.x, self.y, self.maxW, self.h)
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"))
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)
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
class StatusBox(sp.DirtySprite): COLOR = Color.GREEN pgfont.init() FONT = pgfont.SysFont('Tahoma', 16) def __init__(self, text, x, y, anchor=None, font=None, text_color=None): super().__init__() self.text = text self.x, self.y = x, y self.anchor = anchor if font is None: self.font = StatusBox.FONT else: self.font = font if text_color is None: self.textColor = StatusBox.COLOR else: self.textColor = text_color self.__createImage__() def __createImage__(self): self.image, r = self.font.render(self.text, self.textColor) if self.anchor == 'N': top_left = self.x - self.image.get_width() // 2, self.y elif self.anchor == 'W': top_left = self.x, self.y - self.image.get_height() // 2 elif self.anchor == 'NW': top_left = self.x, self.y else: # default to center top_left = (self.x - self.image.get_width() // 2, self.y - self.image.get_height() // 2) self.rect = pg.Rect(*top_left, self.image.get_width(), self.image.get_height()) def update_text(self, text=None, color=None): if text is not None: self.text = text if color is not None: self.textColor = color if not (color is None and text is None): self.__createImage__()
class ColorButton(sp.DirtySprite): pgfont.init() FONT = pgfont.SysFont('Tahoma', 16) def __init__(self, text, rect, color): super().__init__() self.text = text self.rect = rect self.color = tuple(component / 2 for component in color) self.imageBase = pg.Surface((rect.width, rect.height)) self.color_p = color self.imageMouseOver = pg.Surface((rect.width, rect.height)) self.imageMousePress = pg.Surface((rect.width, rect.height)) self.image = self.imageBase self.__createImages__() self.pressed = False def __createImages__(self): self.imageBase.fill(self.color) self.imageMousePress.fill(self.color_p) def contains_pt(self, pt): return self.rect.collidepoint(pt) def press(self): self.image = self.imageMousePress self.pressed = True def unpress(self): self.image = self.imageBase self.pressed = False def release(self): self.image = self.imageBase self.pressed = False
def init(): global dummyfont freetype.init() DigiText.font = freetype.get_default_font()
# BGS project by La Branche (https://discord.gg/AD7H4jX) # Developpers : Antoine D., Kernel # GameMaker file -- classes and functions for the game # __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 = (
import ast import node from node import Node from collections import OrderedDict import pygame.gfxdraw import copy import numpy as np import time import os import compile font.init() pygame.init() edit = ( #sized 8x16 "XXXXXXX ", " X ", " X ", " X ", " X ", " X ", " X ", " X ", " X ", " X ", " X ", " X ",
""" # 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)
class TextBox(sp.DirtySprite): COLOR = (0, 0, 255) COLORO = (0, 0, 63) COLORP = (127, 127, 255) pgfont.init() FONT = pgfont.SysFont('Tahoma', 20) def __init__(self, rect, enterFn=lambda x: None, defaultText=""): super().__init__() self.text = defaultText self.rect = rect self.enterFn = enterFn self.imageBase = pg.Surface((rect.width, rect.height)) self.imageMouseOver = pg.Surface((rect.width, rect.height)) self.imageMousePress = pg.Surface((rect.width, rect.height)) self.image = self.imageBase self.imgRect = self.image.get_rect() self.__typingImages__() self.__staticImages__() self.active = False def __staticImages__(self): gfx.rectangle(self.imageBase, self.imgRect, TextBox.COLOR) self.imageMouseOver.fill(TextBox.COLORO) gfx.rectangle(self.imageMouseOver, self.imgRect, TextBox.COLOR) if self.text: staticTextImage, r = TextBox.FONT.render(self.text, TextBox.COLOR) self.imageBase.blit(staticTextImage, self.textTopLeft) self.imageMouseOver.blit(staticTextImage, self.textTopLeft) def __typingImages__(self): self.imageMousePress.fill((0, 0, 0)) gfx.rectangle(self.imageMousePress, self.imgRect, TextBox.COLORP) if self.text: textImage, r = TextBox.FONT.render(self.text, TextBox.COLORP) self.textTopLeft = ((self.rect.width - textImage.get_width()) // 2, (self.rect.height - textImage.get_height()) // 2) self.imageMousePress.blit(textImage, self.textTopLeft) self.image = self.imageMousePress def containsPt(self, pt): return self.rect.collidepoint(pt) def mouseOver(self): if not self.active: self.image = self.imageMouseOver def unMouseOver(self): if not self.active: self.image = self.imageBase def activate(self): self.__typingImages__() self.image = self.imageMousePress self.active = True def addText(self, c): self.text += c self.__typingImages__() def removeText(self): if len(self.text) > 0: self.text = self.text[:-1] self.__typingImages__() def clearText(self): self.text = "" self.__typingImages__() def deactivate(self): self.__staticImages__() self.image = self.imageBase self.active = False
class Sidebar(Menu): pgfont.init() HEADERFONT = pgfont.SysFont('Tahoma', 16) TEXTFONT = pgfont.SysFont('Tahoma', 14) CHFONT = pgfont.SysFont('Tahoma', 12) CL_LINES = 8 CH_LINES = 5 def __init__(self, x, w, h, game, serverBridge): super().__init__(w, h) self.x = x self.game = game self.gameMap = self.game.map self.serverBridge = serverBridge w -= self.gameMap.w marginX, marginY = 3, 2 # partition the sidebar pStart, pEnd = 0, 0.6 cStart, cEnd = pEnd, 0.8 mStart, mEnd = cEnd, 1.0 # make the planet section numP = len(self.gameMap) pMarginX = marginX pMarginY = marginY hPerP = ((pEnd - pStart) * h) / (numP + 1) - pMarginY self.addLabel('PLANETS', x + w // 2, pStart * h, font=Sidebar.HEADERFONT, anchor='N') for i, p in enumerate(self.gameMap): top = (i + 1) * (hPerP + pMarginY) + (pStart * h) self.addImage(p.image, (x, top), (hPerP, hPerP)) self.addStatusBox(p.name, p.name, x + hPerP + pMarginX, top + (hPerP // 2), anchor='W', font=Sidebar.TEXTFONT) # make the clusters section cMarginX = marginX cMarginY = marginY hPerC = ((cEnd - cStart) * h) / (Sidebar.CL_LINES + 1) - cMarginY self.addLabel('GROUPS', x + w // 2, cStart * h, font=Sidebar.HEADERFONT, anchor='N') for i in range(Sidebar.CL_LINES): top = (i + 1) * (hPerC + cMarginY) + (cStart * h) self.addStatusBox('cl' + str(i), "", x + hPerC + cMarginX, top + (hPerC // 2), anchor='W', font=Sidebar.TEXTFONT) # chat and menu section mMarginX = marginX mMarginY = marginY mH = (mEnd - mStart) * h chHistH = 0.5 self.chatHist = [(self.game.teamNo, "Press 't' to chat")] for line in range(Sidebar.CH_LINES): lineH = chHistH * mH / Sidebar.CH_LINES y = (line + 1 / 2) * lineH + mStart * h self.addStatusBox('ch' + str(line), "", x + mMarginX, y, anchor='W', font=Sidebar.CHFONT) chBoxStartY, chBoxEndY = 0.5, 0.75 ggButStartY, ggButEndY = chBoxEndY, 1.0 chButStartX = 0.75 self.addTextBox( 'chat', pg.Rect(x + mMarginX, mStart * h + chHistH * mH, chButStartX * w - 3 * mMarginX / 2, (chBoxEndY - chBoxStartY) * mH), self.sendChat) self.addButton( 'CHAT', pg.Rect(x + chButStartX * w + mMarginX / 2, mStart * h + chHistH * mH, w - (chButStartX * w + mMarginX * 3 / 2), (chBoxEndY - chBoxStartY) * mH), self.sendChat) self.addButton( 'SURRENDER', pg.Rect(x + mMarginX, mStart * h + ggButStartY * mH, w - 2 * mMarginX, (ggButEndY - ggButStartY) * mH), self.lose) gfx.line(self.bg, x, 0, x, h, (0, 255, 0)) self.refreshChat() def refresh(self): # update the planet list for p in self.gameMap: if p.needsUpdate: if p.teamNo is None: col = Team.NEUTRAL_COLOR else: col = Team.teams[p.teamNo].color if p.units.count is None: text = p.name else: text = p.name + (' (%d)' % p.units.count) self.updateStatusBox(p.name, text=text, color=col) p.needsUpdate = False # update the ships list clusters = sorted(filter(lambda t: t[1].teamNo == self.game.teamNo, iter(self.game.clusterNames.items())), key=lambda t: len(t[1]), reverse=True) color = Team.teams[self.game.teamNo].color for i in range(Sidebar.CL_LINES): if i >= len(clusters): self.updateStatusBox('cl' + str(i), text="") else: name, cl = clusters[i] text = "Group %d to %s (%d)" % (name, cl.dest, len(cl)) self.updateStatusBox('cl' + str(i), text=text, color=color) def sendChat(self): self.serverBridge.sendMsg(('ch', self.getTextBox('chat'))) self.textBoxActive = None self.textBoxDict['chat'].clearText() def refreshChat(self): for (pNo, msg), line in zip(self.chatHist, reversed(range(Sidebar.CH_LINES))): self.updateStatusBox('ch' + str(line), text=msg, color=Team.teams[pNo].color) def handleServerMsg(self, pkType, pk): if pkType == 'ch': self.chatHist.insert(0, pk) if len(self.chatHist) > Sidebar.CH_LINES: self.chatHist.pop() self.refreshChat() elif pkType == 'exit': self.chatHist.insert(0, (self.game.teamNo, 'Server disconnected.')) def lose(self): self.serverBridge.sendMsg(('gg', None))
try: sys.path.append("pygame_cffi") import pygame except e: print(e) sys.path.remove("pygame_cffi") import pygame if hasattr(pygame, 'cffi'): print("loaded pygame_cffi") from pygame import display, image, Rect, time flags = pygame.RESIZABLE#|pygame.DOUBLEBUF display.init() from pygame import freetype freetype.init(cache_size=1024) import lemon_platform lemon_platform.SDL = True import lemon_client, rpcing_frames import keybindings import replay from rpcing_frames import Font, Line
from __future__ import annotations import math import pygame as pg from pygame import gfxdraw from pygame import freetype freetype.init() def draw_circle(surface, x, y, radius, color): gfxdraw.aacircle(surface, x, y, radius, color) gfxdraw.filled_circle(surface, x, y, radius, color) def render_text(font, text, size, fgcolor, bgcolor=(0, 0, 0, 0)): txt_surface, _ = font.render(text, fgcolor, bgcolor, freetype.STYLE_DEFAULT, 0, size) return txt_surface
def draw_board(board, dice, expec, ref_expec, directory, filename, surf=None, render=False): # Color initialization red = (255, 0, 0) green = (0, 255, 0) orange = (255, 165, 0) blue = (0, 0, 255) dark_blue = (0, 0, 128) sky_blue = (0, 191, 255) white = (255, 255, 255) black = (0, 0, 0) pink = (255, 200, 200) forest_green = (34, 139, 34) peru = (205, 133, 63) lime_green = (50, 205, 50) grey = (205, 201, 201) orange_red = (255, 69, 0) pale_turquoise = (175, 238, 238) die_color = [black, forest_green, orange, red] tile_color = [lime_green, sky_blue, pink, peru] tile_emoji = [u"👟", u"⏮", u"◀", u"🔂", u"🏁"] # 🌀 🔙 🕸 surfX = 2760 surfY = 480 surfM = 20 if surf is None: surf = Surface((surfX, surfY)) else: surfX //= 2 surfY //= 2 surfM //= 2 # white background surf.fill(white) # squares coordinates size = (surfX - 2 * surfM) / 16 x_co = surfM + np.append( 1.5 * size * np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 2.0 * size * np.array([3, 4, 5, 6])) y_co = surfM + 1.5 * size * np.array([0] * 11 + [1] * 4) co_map = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 10, 11, 12, 13] nmb_offset_x = 9 nmb_offset_y = 7 tile_emoji_offset = np.split((np.array([ 8 + nmb_offset_x, 11 + nmb_offset_y, 12 + nmb_offset_x, 8 + nmb_offset_y, 10.5 + nmb_offset_x, 6 + nmb_offset_y, 8 + nmb_offset_x, 3 + nmb_offset_y, 10, 10 ])) / 100 * size, 5) # draw cases def print_case(surf, x, y, values): def print_text(text, pos, color, emoji=False): text = str(text) ft = freetype.Font("seguisym.ttf", round( size * 0.3)) if emoji else freetype.SysFont( 'Calibri', round(size * 0.2)) text = ft.render(text, fgcolor=color) surf.blit(text[0], pos) tile = values[2] emoji_offset = tile_emoji_offset[tile] draw.rect(surf, grey, (x, y, size, size), 0) # draw.rect(surf, tile_color[tile], (x, y, size*0.5, size*0.4), 0) draw.rect(surf, black, (x, y, size * 0.5, size * 0.4), 0) draw.rect(surf, black, (x, y, size * 0.5, size * 0.4), 2) print_text(values[0], (x + 0.045 * size, y + 0.05 * size), white) print_text(tile_emoji[tile], (x + +emoji_offset[0], y + +emoji_offset[1]), tile_color[tile], emoji=True) # Die def draw_die_face(face, x, y): face_width = size * 0.4 radius = face_width / 8.0 center = (int(round(x + face_width / 2.0)), int(round(y + face_width / 2.0))) radius = int(round(radius)) face_width = round(int(face_width)) if face != 2: draw.circle(surf, white, center, radius) draw.circle(surf, black, center, radius, 2) if face != 1: draw.circle(surf, white, (center[0] - radius * 2, center[1] + radius * 2), radius) draw.circle(surf, black, (center[0] - radius * 2, center[1] + radius * 2), radius, 2) draw.circle(surf, white, (center[0] + radius * 2, center[1] - radius * 2), radius) draw.circle(surf, black, (center[0] + radius * 2, center[1] - radius * 2), radius, 2) die = values[1] nx = x + 0.1 * size ny = y + size * 0.5 draw.rect(surf, die_color[die], (nx, ny, size * 0.4, size * 0.4), 0) draw.rect(surf, black, (nx, ny, size * 0.4, size * 0.4), 3) # print_text(die, (nx+0.1*size, ny+0.05*size), white) if die > 0: draw_die_face(die, nx, ny) # Gradient bar def draw_gradient(c1, c2, x, y, width, height, proportion): act_h = 0 step = (c2 - c1) / height draw.rect(surf, (black if proportion <= 1 else red), (x - 1, y - height, width + 3, height + 3), 0) while (act_h / height - proportion) < 0.01 and act_h <= height: act_c = c1 + step * act_h act_y = y - act_h draw.line(surf, act_c, (x, act_y), (x + width, act_y), 1) act_h += 1 proportion = values[3] nx = x + size * 0.6 ny = y + size * 0.9 draw_gradient(np.array(pale_turquoise), np.array(orange_red), nx, ny, size * 0.3, size * 0.7, proportion) # Outer border draw.rect(surf, black, (x, y, size, size), 3) freetype.init() for x, y, ind in zip(x_co, y_co, co_map): if ind != 14: print_case( surf, x, y, [ind + 1, dice[ind], board[ind], expec[ind] / ref_expec]) else: draw.rect(surf, black, (x, y, size, size), 0) draw.rect(surf, black, (x, y, size, size), 3) ft = freetype.Font("seguisym.ttf", 140) text = ft.render(tile_emoji[4], fgcolor=white) surf.blit( text[0], (x + tile_emoji_offset[4][0], y + tile_emoji_offset[4][1])) # draw lines x_l = surfM + size + np.append( np.append(1.5 * size * np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 2 * size * np.array([2, 3, 4, 5, 6])), size * np.array([3, 14])) y_l = surfM + size / 2 + np.append( np.append(1.5 * size * np.array([0] * 10), 1.5 * size * np.array([1] * 5)), np.array([0] * 2)) dir_l = [[1, 0]] * 10 + [[2, 0]] * 5 + [[2, 3]] + [[-2, 3]] for x, y, d in zip(x_l, y_l, dir_l): draw.line(surf, black, (x, y), (x + d[0] * size / 2, y + d[1] * size * 0.5), 3) # save picture if not render: if not os.path.exists(directory): os.makedirs(directory) image.save(surf, os.path.join(directory, filename)) return None else: return image
else: self.move_left() self.count += 1 self.dt += self.gl.TIME_PASSED_SECONDS 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:
# try: import glob import pygame from pygame import freetype from vec2d import Vec2D from load import load_image # except ImportError as message: # raise SystemExit(message) if not freetype.was_init(): freetype.init() if not pygame.font.get_init(): pygame.font.init() class Button(pygame.sprite.Sprite): """Button with a set look and changeable label, centered in the button. Gets highlighted when flagged by a keyboard button. """ def __init__(self, label, position=Vec2D(0, 0)): """Initialize all attributes and run the initial update. Changes in the font may cause a label that was fitting the button to not do so anymore.