def __init__(self, x: int, y: int, radius: int, background_color: tuple, slider_color: tuple, text_color: tuple): self.x = x self.y = y self.radius = radius self.background_color = background_color self.slider_color = slider_color self.text_color = text_color self.white_font = Font(constants.NANUMSQUARE_REGULAR_FONT, radius // 3, (255, 255, 255)) self.black_font = Font(constants.NANUMSQUARE_REGULAR_FONT, radius // 3, (0, 0, 0)) self.background_surface = self.get_colored_font_by_color(self.background_color) \ .render('#%02X%02X%02X' % self.background_color) self.slider_surface = self.get_colored_font_by_color(self.slider_color) \ .render('#%02X%02X%02X' % self.slider_color) self.text_surface = self.get_colored_font_by_color(self.text_color) \ .render('#%02X%02X%02X' % self.text_color) self.background_pos = (int(self.x + self.radius) - self.background_surface.get_width() / 2, int(self.y + self.radius) - self.background_surface.get_height() / 2) self.slider_pos = (int(self.x + self.radius * 3.5) - self.slider_surface.get_width() / 2, int(self.y + self.radius) - self.slider_surface.get_height() / 2) self.text_pos = (int(self.x + self.radius * 6) - self.text_surface.get_width() / 2, int(self.y + self.radius) - self.text_surface.get_height() / 2)
def setProps(self, props={}, **kwprops): """ If font is given as a string or a dict, convert it into a Font object. If rotation is a string representing a number, convert it. Then call Artist.setProps. """ # A property might be defined in both props and kwprops, # so do all of this twice for d in (props, kwprops): if 'font' in d.keys(): currentFont = Font() if 'font' in self.props().keys(): currentFont = self.props('font') if isinstance(d['font'], str): currentFont.setFamily(d['font']) d['font'] = currentFont elif isinstance(d['font'], dict): currentFont.setProps(d['font']) d['font'] = currentFont if 'rotation' in d.keys(): try: d['rotation'] = float(d['rotation']) except ValueError: pass Artist.setProps(self, props, **kwprops)
class Color(State): SAMPLE_PALETTES = ( ((31, 33, 37), (253, 222, 89), (222, 222, 222)), ((62, 62, 50), (217, 37, 52), (239, 223, 187)), ((13, 13, 13), (166, 131, 88), (215, 215, 217)) ) def __init__(self): super().__init__() self.radius = 50 center_x = center(display.size[0], ColorSample.get_width_by_radius(self.radius)) y_offset = center(display.size[1], self.radius * 9.6) self.font = Font(constants.NANUMSQUARE_BOLD_FONT, self.radius // 3 * 2, constants.TEXT_COLOR) for i in range(len(Color.SAMPLE_PALETTES)): x, y = center_x, i * self.radius * 4 + y_offset self.objects.append(ColorSample(x, y, self.radius, *Color.SAMPLE_PALETTES[i])) self.objects.append(Text(x + self.font.size // 3, y - self.font.size * 1.5, chr(i + ord('G')), self.font)) def window_resize(self, width: int, height: int): center_x = center(display.size[0], ColorSample.get_width_by_radius(self.radius)) y_offset = center(display.size[1], self.radius * 9.6) self.objects = [] for i in range(len(Color.SAMPLE_PALETTES)): x, y = center_x, i * self.radius * 4 + y_offset self.objects.append(ColorSample(x, y, self.radius, *Color.SAMPLE_PALETTES[i])) self.objects.append(Text(x + self.font.size // 3, y - self.font.size * 1.5, chr(i + ord('G')), self.font)) def recolor(self): self.font.set_color(constants.TEXT_COLOR)
def __init__(self, config, matrix): self.showDuration = config["screens"]["clockScreen"].get( "showDuration") self.matrix = matrix self.font_small = Font(file="CGpixel3x5.ttf", size=5) self.font_big = Font(file="mini_pixel-7.ttf", size=30)
class ResizeAlert(RootObject): def __init__(self, width, height, root_object_manager: RootObjectManager, timeout=1): self.width = width self.height = height self.root_object_manager = root_object_manager self.timeout = timeout self.start_time = time() self.background = Surface((300, 200)) self.background.fill(BACKGROUND_COLOR) self.background.set_alpha(127) self.background_x = center(self.width, self.background.get_width()) self.background_y = center(self.height, self.background.get_height()) self.surface = Font(NANUMSQUARE_BOLD_FONT, 36, TEXT_COLOR).render(f'{width}x{height}') self.x = center(self.width, self.surface.get_width()) self.y = center(self.height, self.surface.get_height()) self.root_object_manager.remove_by_class(ResizeAlert) def tick(self): if time() - self.timeout > self.start_time: self.destroy() def render(self, surface: Surface): surface.blit(self.background, (self.background_x, self.background_y)) surface.blit(self.surface, (self.x, self.y)) def destroy(self): self.root_object_manager.remove(self)
def load_font(self, name, path=None): """ Add a new font to this manager. Parameters ---------- name : :obj:`str` The name of the font. The font's metafile and texture filename's should also be this value with the appropriate file extensions. path : :obj:`str`, optional File path the font files. If not supplied will use the default `res/fonts/` path. """ if path is None: path = self._font_path # Load in the font texture atlas tex_file = path + name + ".png" image = self._app.tex_mgr.load_image(name, tex_file) builder = TextureBuilder().set_filtered(True).set_wrapped( GL_CLAMP_TO_EDGE) texture = self._app.tex_mgr.load_texture(name, image, builder) # Create the font object which automatically loades the font metadata font_file = path + name + ".fnt" font = Font(name, font_file, texture) # Add font to local caches and create loader obj self._fonts[font.name] = font self._loaders[font] = loader = TextLoader(font) self._texts[font] = [] font._loader = loader # Attempting to not expose a set option return font
def __init__(self, podcast): super(PodcastRow, self).__init__() self.remove_img = get_gtk_image_from_file('./icons/delete.png', 12, 12) self.refresh_img = get_gtk_image_from_file('./icons/update.png', 12, 12) self.refresh = Gtk.Button() self.refresh.set_image(self.refresh_img) self.refresh.set_relief(Gtk.ReliefStyle.NONE) self.remove = Gtk.Button() self.remove.set_image(self.remove_img) self.remove.set_relief(Gtk.ReliefStyle.NONE) hbox1 = Gtk.HBox() hbox1.pack_start(self.refresh, False, True, 0) hbox1.pack_start(self.remove , False, True, 0) self.box_revealer = Gtk.Revealer() self.box_revealer.add(hbox1) self.box_revealer.set_transition_type(Gtk.RevealerTransitionType.NONE) hbox2 = Gtk.HBox(spacing=6) hbox2.pack_start(Gtk.Label(podcast.date, xalign=0), True, True, 0) hbox2.pack_start(self.box_revealer, True, True, 0) self.spinner = Gtk.Spinner() self.load_revealer = Gtk.Revealer.new() self.load_revealer.add(self.spinner) self.load_revealer.set_transition_type(Gtk.RevealerTransitionType.SLIDE_LEFT) font = Font() font.set_weight(FontWeight.BOLD) name = Gtk.Label(podcast.name, xalign=0, yalign=0) name.modify_font(font.to_pango_desc()) revbox = Gtk.HBox(spacing=0) revbox.pack_start(self.load_revealer, False, True, 0) revbox.pack_start(name, True, True, 0) pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(podcast.image, 75, 75, True) image = Gtk.Image.new_from_pixbuf(pixbuf) image.set_alignment(0,0) summary = Gtk.Label(podcast.summary, xalign=0, yalign=0) summary.set_max_width_chars(60) summary.set_lines(4) summary.set_ellipsize(Pango.EllipsizeMode.END) expander = Gtk.Expander.new('Description') expander.add(summary) grid = Gtk.Grid() grid.set_column_spacing(6) grid.attach(image , 0, 0, 1, 3) grid.attach(revbox , 1, 0, 1, 1) grid.attach(expander, 1, 1, 1, 1) grid.attach(hbox2, 1, 2, 1, 1) self.add(grid) self.podcast = podcast self.buttonsConnected = False
def set_font(self, font_file): # get the font f = Font() font = f.load_font(font_file) self.font_width = len(font['i'][Font.CHARACTER_BY_ROWS][Font.ROW]) self.font_height = len(font['i'][Font.CHARACTER_BY_ROWS]) return font
def test_ufo_metrics(self): f = Font('bdf/jiskan24-2003-1.bdf') info = defcon.Info() f.set_ufo_metrics(info) self.assertEqual(info.unitsPerEm, 256) self.assertEqual(info.ascender, 228) self.assertEqual(info.descender, -28) self.assertEqual(info.capHeight, 200) self.assertEqual(info.xHeight, 140)
def __init__(self, program, i, iname): py.sprite.Sprite.__init__(self) self.image = py.Surface([140, 40]) self.rect = self.image.get_rect() self.index = i self.program = program self.iname = iname self.namefont = Font(13) self.predraw()
def __init__(self, y): self.y = y self.time = Text( 0, self.y, '', Font(constants.NANUMSQUARE_BOLD_FONT, 72, constants.TEXT_COLOR)) self.millisecond = Text( 0, self.time.y + self.time.font.size, '', Font(constants.NANUMSQUARE_REGULAR_FONT, 32, constants.TEXT_COLOR))
def __init__(self, x, y, w, h, font, text='', fontSize='medium', resizable=True, startActiveText=False, characterLimit=1000, inputType=None): if getattr(sys, 'frozen', False): # In a bundle self.exeDir = os.path.dirname(sys.executable) else: # In normal python self.exeDir = "" Font.__init__(self, directory=os.path.join(self.exeDir, "..", "fonts")) self.colour_inactive = pygame.Color('lightskyblue3') self.colour_active = pygame.Color('dodgerblue2') self.x = x self.y = y self.width = w self.height = h self.font = font self.rect = pygame.Rect(x, y, w, h) self.rectOld = self.rect.copy() self.color = self.colour_inactive self.text = text self.resizable = resizable self.characterLimit = characterLimit self.inputType = inputType if fontSize == None: self.font = self.font.tinyFont elif fontSize == 'tiny': self.font = self.font.tinyFont elif fontSize == 'small': self.font = self.font.smallFont elif fontSize == 'medium': self.font = self.font.mediumFont elif fontSize == 'large': self.font = self.font.largeFont if startActiveText: self.txt_surface = self.font.render(text, True, self.colour_active) else: self.txt_surface = self.font.render(text, True, self.color) self.active = False self.updated = True self.characterWidth = self.font.size("W")[0] self.text_width = self.txt_surface.get_width()
class HUD(RootObject): def __init__(self, state_manager: StateManager, root_object_manager: RootObjectManager, keyboard_manager: KeyboardManager, handler_manager: HandlerManager, font_path: str = constants.CONSOLAS_FONT, size: int = 15): self.state_manager = state_manager self.root_object_manager = root_object_manager self.keyboard_manager = keyboard_manager self.handler_manager = handler_manager self.font = Font(font_path, size, constants.TEXT_COLOR) self.surfaces = [] self.last_call = time() self.fps_time = 0 self.real_fps = 0 def recolor_background(self): self.font = Font(self.font.font_path, self.font.size, constants.TEXT_COLOR) def tick(self): call = time() self.fps_time += 1 if int(self.last_call) < int(call): self.real_fps = self.fps_time self.fps_time = 0 try: fps = 1 / (call - self.last_call) except ZeroDivisionError: fps = None try: string = f'{constants.PROJECT_NAME} {constants.PROJECT_VERSION}\n\n' \ f'Display_ {display.size[0]}x{display.size[1]}@{fps:f}\nReal-Fps {self.real_fps} fps\n' \ f'Full-Screen_ {display.full_screen}\n\n' \ f'State_ {self.state_manager.state.__class__.__name__} ({self.state_manager.state})\n' \ f'Object_ {len(self.root_object_manager.objects)} Handler_ {len(self.handler_manager.handlers)}\n' \ f'Play-Sound_ {Timer.PLAY_SOUND}\n\n' \ f'Keyboard_ {self.keyboard_manager.keys.count(True)}\n\n' \ f'Global-Progress_ {constants.progress:.030f}\n\n' \ f'Color -\nResponsible-Color_ {constants.responsible_color}\n' \ f'Background_ {constants.BACKGROUND_COLOR}\n' \ f'Circle_ {constants.CIRCLE_COLOR}\nText_ {constants.TEXT_COLOR}' except TypeError: pass else: self.font.set_color(constants.TEXT_COLOR) self.surfaces = [self.font.render(line) if line else None for line in string.split('\n')] self.last_call = call def render(self, surface: Surface): for i in range(len(self.surfaces)): if self.surfaces[i]: surface.blit(self.surfaces[i], (0, i * self.font.size))
def _render_fonts(text, font=None, show=False, color='WHITE'): if not font: font = random.choice(Font.get_all_fonts()) if not text: text = 'xart' renderer = Renderer(Font(font)) data = renderer.render(text) sys.stdout.write(Color.dyeing(data, Color.get_color(color))) if show: sys.stdout.write('Font name : {}\n'.format(font))
def __init__(self, spi, scs, extcomin, disp): self.spi = spi self.scs = scs self.extcomin = extcomin self.disp = disp self.data = bytearray(12482) self.font = Font() self.data_reset() self.initialize() self.disp.on()
def __init__(self): super().__init__() self.radius = 50 center_x = center(display.size[0], ColorSample.get_width_by_radius(self.radius)) y_offset = center(display.size[1], self.radius * 9.6) self.font = Font(constants.NANUMSQUARE_BOLD_FONT, self.radius // 3 * 2, constants.TEXT_COLOR) for i in range(len(Color.SAMPLE_PALETTES)): x, y = center_x, i * self.radius * 4 + y_offset self.objects.append(ColorSample(x, y, self.radius, *Color.SAMPLE_PALETTES[i])) self.objects.append(Text(x + self.font.size // 3, y - self.font.size * 1.5, chr(i + ord('G')), self.font))
def __init__(self, state_manager: StateManager, root_object_manager: RootObjectManager, keyboard_manager: KeyboardManager, handler_manager: HandlerManager, font_path: str = constants.CONSOLAS_FONT, size: int = 15): self.state_manager = state_manager self.root_object_manager = root_object_manager self.keyboard_manager = keyboard_manager self.handler_manager = handler_manager self.font = Font(font_path, size, constants.TEXT_COLOR) self.surfaces = [] self.last_call = time() self.fps_time = 0 self.real_fps = 0
def _render_fonts(text, font=None, show=False, color='WHITE', outfile=''): if not font: font = random.choice(Font.get_all_fonts()) if not text: text = 'xart' renderer = Renderer(Font(font)) data = renderer.render(text) if outfile: with open(outfile, 'w') as fp: fp.write(data) else: sys.stdout.write(Color.dyeing(data, Color.get_color(color))) if show: sys.stdout.write('Font name : {}\n'.format(font))
def test_v2x_name_table(self): expected = [ # (langID, nameID, string) (0x409, 0, u'Public domain'), (0x409, 1, u'Wapuro Mincho TateBaikaku'), (0x409, 2, u'Regular'), (0x409, 3, u'1.002;NONE;WapuroMincho-TateBaikaku'), (0x409, 4, u'Wapuro Mincho TateBaikaku'), (0x409, 5, u'Version 1.002'), (0x409, 6, u'WapuroMincho-TateBaikaku'), (0x409, 11, u'https://irori.github.io/wapuro-mincho/'), (0x409, 16, u'Wapuro Mincho'), (0x409, 17, u'TateBaikaku'), (0x411, 1, u'ワープロ明朝 縦倍角'), (0x411, 4, u'ワープロ明朝 縦倍角'), (0x411, 16, u'ワープロ明朝'), (0x411, 17, u'縦倍角'), ] font = Font('bdf/jiskan24-2003-1.bdf') ufo = convert.create_ufo(font, limit=1) convert.v2x(ufo) otf = convert.compile(ufo, 'out.ttf') actual = [] for name in sorted(otf['name'].names): self.assertEqual(name.platformID, 3) self.assertEqual(name.platEncID, 1) actual.append((name.langID, name.nameID, name.toUnicode())) self.assertEqual(expected, actual)
def __init__(self, config, matrix): self.showDuration = config["screens"]["scrollScreen"].get( "showDuration") self.matrix = matrix self.font_big = Font(file="mini_pixel-7.ttf", size=40) self.setText("Hello Matrix :)")
def init(): global keyboard_manager, root_object_manager, state_manager, handler_manager pygame.init() pygame.display.set_caption( f'{constants.PROJECT_NAME} {constants.PROJECT_VERSION}') pygame.display.set_icon(pygame.image.load(constants.PROJECT_ICON)) display.window = pygame.display.set_mode(display.size, pygame.RESIZABLE) keyboard_manager = KeyboardManager() root_object_manager = RootObjectManager() state_manager = StateManager(Clock()) handler_manager = HandlerManager() handler_manager.add(Quit(keyboard_manager, shutdown)) handler_manager.add(RenderStop(keyboard_manager)) handler_manager.add(ResponsiveColor(state_manager)) root_object_manager.add( Terminal( constants.TEXT_COLOR, Font(constants.NANUMSQUARE_REGULAR_FONT, 32, constants.BACKGROUND_COLOR), keyboard_manager, state_manager, root_object_manager, handler_manager, shutdown))
def make_flame(args): """ Use the arguments to make a flame file. """ # Select the padding style pad_char = '█' if args.block_padding else ' ' text = Text(args.text, pad_char) # Read in the font and sanitize the text font = Font() text.sanitize(font.alphabet) print("Making fractal for the following text:") print(text) # The Layout handles positioning each character of text layout = Layout(font, text) # The AffineFinder calculates the necessary transformation # matricies. It returns XForm Objects finder = AffineFinder(layout.bounding_box) xforms = list(finder.find_xforms(layout.geometry)) print("This fractal will use {} xforms + final xform".format(len(xforms))) writer = FlameWriter() writer.write(args.fname, args.flame_name, xforms)
def _print_all_fonts(): output = ['xart : generate art ascii texts.\n'] fonts = Font.get_all_fonts() for idx, font_name in enumerate(fonts): output.append(' {}. {}'.format(idx, font_name)) output.append('\nAll {} fonts.\n'.format(len(fonts))) sys.stdout.write('\n'.join(output))
def textCheck(self): for r in self.checkM: for m in r: m.setChecked(False) text_to_render = self.type.text() font = Font(os.path.join('Fonts', self.fonts.currentText()), 8) try: text = repr(font.render_text(text_to_render, 52, 7)) text_by_weekday = text.split('\n') for i in range(7): for j in range(51): if text_by_weekday[i][j] == '#': self.checkM[i][j].setChecked(True) except: self.err.setText('You typed too long :(') self.err.exec()
def __init__(self, pos=[0,0], font=None, message="", image=None, wrap_text=False, align=["left","top"], visible=True, image_mode=None): self.pos=pos self.kind="Label" self.font=font if not font: self.font=Font() self.message=message self.lines=[] self.message_image=None self.image=image self.image_mode=image_mode self.wrap_text=wrap_text self.align=align self.visible=visible self.refactor()
def fonts(self): if not hasattr(self, "__fonts"): from font import Font self.__fonts = {} for row in self.sql.getFontInfos(): self.__fonts[row[0]] = Font(row[0]) return self.__fonts
def __init__(self, **kw): super(DotMatrix, self).__init__(**kw) self.background = kw['background'] if 'background' in kw \ else (.1, .1, .1, 1) self.dot_on = kw['dot_on'] if 'dot_on' in kw else (.1, .9, .1, 1) self.dot_off = kw['dot_off'] if 'dot_off' in kw else (.1, .3, .1, 1) self.dot_style = kw['dot_style'] if 'dot_style' in kw else 'circle' self.rows = kw['rows'] if 'rows' in kw else 2 self.cols = kw['cols'] if 'cols' in kw else 16 curr_dir = os.path.dirname(os.path.realpath(__file__)) if 'font' in kw: self.font = Font(dirname=os.path.join(curr_dir, kw['font'])) else: self.font = Font(dirname=os.path.join(curr_dir, 'font_5x7')) self.spacing = kw['spacing'] if 'spacing' in kw else 1 self.bind(pos=self.draw) self.bind(size=self.draw) self.bind(text=self.draw)
def __init__(self): super(Player, self).__init__() self.adjustment = Gtk.Adjustment.new(0.0, 0.0, 100.0, 0.5, 10.0, 0.0) self.adjustment.connect('value-changed', self.on_adjustment_changed) self.progress = Gtk.Scale.new(Gtk.Orientation.HORIZONTAL, self.adjustment) self.progress.set_hexpand(True) self.progress.set_sensitive(False) self.progress.set_draw_value(False) self.progress.connect('button-press-event', self.on_mouse_press) self.progress.connect('button-release-event', self.on_mouse_release) font = Font() font.set_size(8) self.current_time = Gtk.Label('00:00:00.00', xalign=0, xpad=6) self.current_time.modify_font(font.to_pango_desc()) self.changing_time = Gtk.Label(' ', xpad=6) self.changing_time.modify_font(font.to_pango_desc()) self.total_time = Gtk.Label('00:00:00.00', xalign=1, xpad=6) self.total_time.modify_font(font.to_pango_desc()) self.track_label = Gtk.Label(' ') self.play_pause_button = Gtk.Button() self.play_pause_button.set_image(self.play_img) self.play_pause_button.connect('clicked', self.play_pause_action) self.stop_button = Gtk.Button() self.stop_button.set_image(self.stop_img) self.stop_button.connect('clicked', self.stop_action) self.set_column_spacing(6) self.set_row_spacing(3) self.attach(self.track_label, 0, 0, 3, 1) self.attach(self.current_time, 0, 1, 1, 1) self.attach(self.changing_time, 1, 1, 1, 1) self.attach(self.total_time, 2, 1, 1, 1) self.attach(self.progress, 0, 2, 3, 1) self.attach(self.play_pause_button, 3, 2, 1, 1) self.attach(self.stop_button, 4, 2, 1, 1) self.duration = 360000000 self.duration_str = '0' self.player_state = PlayerState.STOPPED self.player = AudioStreamer() self.timeout_id = GObject.timeout_add(1000, self.on_timeout, None) self.mouse_moving = False
def value(self, default=False): if default: return self._defaultValue settings = QtCore.QSettings() defaultValue = self._defaultValue if self.type == "font": defaultValue = self._defaultValue.toStorableString() value = settings.value(self._key, defaultValue) if self.type == "font": f = Font() f.fromStorableString(value.toString()) return f elif self.type == "bool": return value.toBool() elif self.type == "int": return value.toInt()[0] return value.toPyObject()
def __init__(self, start_time=None): super().__init__() self.start_time = start_time if self.start_time is None: self.start_time = datetime.now() self.circle = Circle(0, 0, 190, 20, constants.CIRCLE_COLOR, constants.progress) font = Font(constants.NANUMSQUARE_REGULAR_FONT, 72, constants.TEXT_COLOR) self.elapsed_time = Text(0, 0, '', font) font2 = Font(constants.NANUMSQUARE_LIGHT_FONT, 32, constants.TEXT_COLOR) self.elapsed_microsecond = Text(0, 0, '', font2) self.elapsed_days = Text(0, 0, '', font2) self.days = 0 self.time = Time(0) self.start_text: Text = Text(0, 0, str(self.start_time).split('.')[0], Font(constants.NANUMSQUARE_LIGHT_FONT, 32, constants.TEXT_COLOR)) self.window_resize(*display.size)
def __init__(self, target: datetime, state_manager: StateManager): super().__init__() self.target = target self.state_manager = state_manager self.start_time = datetime.now() self.circle = ProgressCircle(0, 0, 190, 20, constants.CIRCLE_COLOR, constants.progress) self.last_time = Text( 0, 0, '', Font(constants.NANUMSQUARE_REGULAR_FONT, 16, constants.TEXT_COLOR)) self.time = Time(0) self.target_time: Text = Text( 0, 0, str(self.target).split('.')[0], Font(constants.NANUMSQUARE_LIGHT_FONT, 32, constants.TEXT_COLOR)) self.window_resize(*display.size)
def fontDialog(parent, aFont=None): if aFont is not None: aFont = aFont._getFont() result = dialogs.fontDialog(parent, font=aFont) if result.accepted: fontData = result.fontData result.color = result.fontData.GetColour().Get() fontWx = result.fontData.GetChosenFont() result.fontDescription = fontDescription(fontWx) fontWx = None result.font = Font(result.fontDescription) return result
def __init__(self, main): from font import Font global g_fVBOObjects g_fVBOObjects = [] self.main = main self.g_nFrames = 0 self.fps = 0 init_opengl(main) self.font = Font()
def setup(self): """Setup game.""" pygame.init() image = pkg_resources.resource_filename(__name__, 'data/icon.gif') pygame.display.set_icon(pygame.image.load(image)) pygame.display.set_caption("tris") self.tileset = Tileset('data/blocks.gif', 16, 16) image = pkg_resources.resource_filename(__name__, 'data/splash.gif') self.splash_image = pygame.image.load(image) self.font = Font() self.hiscores = Persistor.load() if not self.hiscores: self.hiscores = HiScores.get_default_hiscore_list()
def __init__(self, pos=[0,0], font=None, area=[50,50], align=["left","top"], visible=True, image=None, image_mode=None, messages=[], max_lines=None, wrap=False, text_padding=[0,0]): self.kind="MessageBox" self.pos=pos self.font=font if not self.font:self.font=Font() self.text_padding=text_padding self.area=area self.align=align self.visible=visible self.image=image self.image_mode=image_mode if self.image: if isinstance(self.image, pygame.Surface): pass else: self.image=self.image.resize(self.area, self.image_mode) self.area=[self.image.get_width(), self.image.get_height()] self.messages=[] self.max_lines=max_lines self.max_width=0 self.wrap=wrap for i in messages: self.add_message(i) self.vscroll=0 self.hscroll=0
image.save(fname) # time.sleep(3) print "Saved image to " + fname def clear(self): self._scene.clear() self.tview.setPlainText("") self.gview.update() if __name__ == "__main__": import json, sys, os from font import Font from run import Run app = QtGui.QApplication(sys.argv) # print app.desktop().logicalDpiY() tpath = os.path.join(os.path.dirname(sys.argv[0]), "../../tests") jf = file(os.path.join(tpath, "padauk3.json")) jinfo = json.load(jf) font = Font() font.loadFont(os.path.join(tpath, "fonts/Padauk/Padauk.ttf")) font.makebitmaps(40) rinfo = jinfo["passes"][0]["slots"] run = Run(font, False) run.addSlots(rinfo) view = RunView(run, font).gview print "Padauk RunView?" ### view.show() sys.exit(app.exec_())
def __init__(self): self.font = Font() self.user_sprite = self.get_sprite('pokemon_back_tiled.bmp') self.enemy_sprite = self.get_sprite('pokemon.bmp')
class BattleUI(object): def __init__(self): self.font = Font() self.user_sprite = self.get_sprite('pokemon_back_tiled.bmp') self.enemy_sprite = self.get_sprite('pokemon.bmp') @staticmethod def get_sprite(filename): if filename == 'pokemon_back_tiled.bmp': sprite = Sprite( filename, width=back_size, height=back_size, cols=7, rows=36, offset=(6, 6), period=(54, 57), ) sprite.set_pokenum = lambda i: sprite.set_index(i - 1) elif filename == 'pokemon.bmp': sprite = Sprite( filename, width=front_size, height=front_size, cols=10, rows=26, offset=(8, 24), period=(64, 64), ) sprite.set_pokenum = lambda i: sprite.set_index(get_front_index(i)) else: assert(False), 'Unexpected image name: %s' % (filename,) return sprite def draw(self, surface, battle): surface.fill(white) display = battle.get_display() self.draw_pc_pokemon(surface, battle.all_pcs(), display) self.draw_npc_pokemon(surface, battle.all_npcs(), display) self.draw_menu(surface, display['menu']) def draw_pc_pokemon(self, surface, pc_pokemon, display): top = screen_size[1] - ui_height - self.user_sprite.height - status_height self.draw_pokemon_row(surface, pc_pokemon, top, 'pc', display) def draw_npc_pokemon(self, surface, npc_pokemon, display): self.draw_pokemon_row(surface, npc_pokemon, top_row_space, 'npc', display) def draw_pokemon_row(self, surface, pokemon_list, top, side, display): num = len(pokemon_list) total = screen_size[0] + name_size sprite = self.user_sprite if side == 'pc' else self.enemy_sprite for (i, pokemon) in enumerate(pokemon_list): left = int((i + 1)*total/(num + 1)) - name_size self.draw_pokemon(surface, sprite, pokemon, left, top, (side, i), display) def draw_pokemon(self, surface, sprite, pokemon, far_left, top, index, display): # Draw the Pokemon's (back or front) sprite. left = far_left + (name_size - sprite.width)/2 sprite.set_position(left, top) sprite.set_pokenum(pokemon.num) if draw_sprites and index not in display.get('hidden_indices', ()): with self.apply_sprite_offsets(sprite, index, display): sprite.draw(surface) if pokemon.status: char = Status.MARKS[pokemon.status] self.font.draw(surface, char, left - font_size - 3, top + font_size/2) # Draw the Pokemon's name. name = pokemon.name left = far_left + (name_size - font_size*len(name))/2 top += (sprite.height + font_size/2)/(1 if draw_sprites else 2) self.font.draw(surface, name, left, top) # Draw the Pokemon's level. offset = (pokemon.level < 10)*font_size/2 top += 3*font_size/2 self.font.draw(surface, 'L%d' % (pokemon.level,), far_left + offset, top) # Draw the Pokemon's health bar. left = far_left + 7*font_size/2 - offset top += font_size/2 health = float(pokemon.cur_hp)/pokemon.max_hp self.draw_health_bar(surface, health, left, top) @contextmanager def apply_sprite_offsets(self, sprite, index, display): height_offset = display.get('height_offsets', {}).get(index, 0) absolute_offset = int(math.ceil(height_offset*sprite.height)) sprite.rect.top += absolute_offset sprite.source_rect.height -= absolute_offset yield sprite.rect.top -= absolute_offset sprite.source_rect.height += absolute_offset def draw_health_bar(self, surface, health, left, top): # Draw the left and right borders of the health bar. pygame.draw.rect(surface, black, ( left, top - health_border[1]/2, health_border[0], health_border[1], )) pygame.draw.rect(surface, black, ( left + health_border[0] + health_bar[0], top - health_border[1]/2, health_border[0], health_border[1], )) # Draw a line underneath the bar. This code may be incorrect... pygame.draw.line(surface, black, ( left + health_border[0], top + health_border[1]/2 - health_bar[1]/2 + 1, ), ( left + health_border[0] + health_bar[0], top + health_border[1]/2 - health_bar[1]/2 + 1, )) # Draw the actual health bar in the correct color. color = green if health > 0.5 else yellow if health > 0.25 else red width = int(math.ceil(health*health_bar[0])) if width: pygame.draw.rect(surface, color, ( left + health_border[0], top - health_bar[1]/2, width, health_bar[1], )) def draw_menu(self, surface, menu): self.draw_menu_block(surface, menu, 0, screen_size[0]) def draw_menu_block(self, surface, lines, left, width): pygame.draw.rect(surface, black, ( left, screen_size[1] - ui_height, width, ui_height, ), 1) top = screen_size[1] - ui_height + font_size for line in self.resize_lines(lines, width): self.font.draw(surface, line, left + font_size, top) top += 3*font_size/2 def resize_lines(self, lines, width): num_chars = width/font_size - 2 new_lines = [''] for line in lines: for word in line.split(' '): if len(new_lines[-1]) + len(word) > num_chars: new_lines.append('') new_lines[-1] += word + ' ' new_lines.append('') return [line.rstrip() for line in new_lines]
class MessageBox(object): def __init__(self, pos=[0,0], font=None, area=[50,50], align=["left","top"], visible=True, image=None, image_mode=None, messages=[], max_lines=None, wrap=False, text_padding=[0,0]): self.kind="MessageBox" self.pos=pos self.font=font if not self.font:self.font=Font() self.text_padding=text_padding self.area=area self.align=align self.visible=visible self.image=image self.image_mode=image_mode if self.image: if isinstance(self.image, pygame.Surface): pass else: self.image=self.image.resize(self.area, self.image_mode) self.area=[self.image.get_width(), self.image.get_height()] self.messages=[] self.max_lines=max_lines self.max_width=0 self.wrap=wrap for i in messages: self.add_message(i) self.vscroll=0 self.hscroll=0 def add_message(self, mess): if self.wrap: for x in gui_util.wrap_text(self.font, mess, self.wrap)[0]: self.messages.append(x) else: self.messages.append(mess) if self.max_lines: while len(self.messages)>self.max_lines: del self.messages[0] self.max_width=0 for i in self.messages: w=self.font.size(i)[0] if w>self.max_width: self.max_width=w def update(self, event): pass def scroll(self, v=0, h=0): self.vscroll+=v if self.vscroll<0: self.vscroll=0 if (len(self.messages)+1)*(self.font.fsize-(self.font.fsize/3))>self.area[1]: max=(self.font.fsize-(self.font.fsize/3))*(len(self.messages)+1) max-=self.area[1] if self.vscroll>max: self.vscroll=max else: self.vscroll=0 self.hscroll+=h if self.hscroll<0: self.hscroll=0 if self.max_width > self.area[0]: if self.hscroll>self.max_width-self.area[1]: self.hscroll=self.max_width-self.area[1] else: self.hscroll=0 def render(self, surface): if self.visible: ret_clip=surface.get_clip() new_clip=pygame.Rect((self.pos[0]+self.text_padding[0], self.pos[1]+self.text_padding[1]), (self.area[0]-self.text_padding[0]*2, self.area[1]-self.text_padding[1]*2)) new_clip.clip(ret_clip) if self.image: if isinstance(self.image, pygame.Surface): surface.blit(self.image, self.pos) else: self.image.render(surface, self.pos) surface.set_clip(new_clip) lines=[self.font.render(i) for i in self.messages] fs=self.font.fsize-(self.font.fsize/3) for l in xrange(len(lines)): line=lines[l] r=line.get_rect() y=self.pos[1]+self.text_padding[1]+\ (fs*l)+\ self.vscroll-(fs*(len(self.messages)+1)-self.area[1]) x=self.pos[0]+self.text_padding[0]-self.hscroll if self.align[0]=="left": r.left=x elif self.align[0]=="center": r.centerx=x+self.area[0]/2-self.text_padding[0] else: r.right=x+self.area[0]-self.text_padding[0]*2 if self.align[1]=="top": r.top=y elif self.align[1]=="center": r.centery=y else: r.bottom=y surface.blit(line, r.topleft) surface.set_clip(ret_clip)
gl.glClear(gl.GL_COLOR_BUFFER_BIT) program.draw(gl.GL_TRIANGLE_STRIP) @window.event def on_resize(width, height): gl.glViewport(0, 0, width, height) @window.event def on_mouse_scroll(x, y, dx, dy): scale = program["scale"][0] program["scale"] = min(max(0.1, scale + .01 * dy * scale), 1) program = gloo.Program("sdf.vert", ["spatial-filters.frag", "sdf-2.frag"], count=4) program['position'] = [(-1,-1), (-1,+1), (+1,-1), (+1,+1)] font = Font("Vera.ttf") font.load("abcdefghijklmnopqrstuvwxyz") font.load("ABCDEFGHIJKLMNOPQRSTUVWXYZ") program['texcoord'] = [( 0, 1), ( 0, 0), ( 1, 1), ( 1, 0)] program['u_kernel'] = np.load("spatial-filters.npy") program['tex_data'] = font.atlas program['tex_data'].interpolation = gl.GL_LINEAR program['tex_shape'] = font.atlas.shape[1],font.atlas.shape[0] program['color'] = 0,0,0,1 program['scale'] = 1.0 gl.glClearColor(1.0, 1.0, 1.0, 1.0) gl.glDisable(gl.GL_DEPTH_TEST) gl.glEnable(gl.GL_BLEND)
class Menu(Screen): def __init__(self): self.font = Font(config.menufontpath, config.menufontsize) # init menu display self.selected = 0 self.col_offset = 0 def resize_view(self): """Resize the view, redraw the background, reinit the font.""" # find the largest rectangle with the same ratio as basesize, # and a maximum of maxsize on either axis. ww, wh = self.window_view.get_size() bw, bh = config.menuratio mx, my = config.menumargin mult = min(ww * (1 - mx * 2) / bw, wh * (1 - my * 2) / bh) width, height = bw * mult, bh * mult left, top = (ww - width) / 2, (wh - height) / 2 self.view = self.window_view.subsurface((left, top, width, height)) # redraw the background self.background = pygame.Surface(self.view.get_size()) self.background.fill(config.menubackcolor) # create text area tmx, tmy = config.menumargin tleft, ttop = tmx * width, tmy * height twidth, theight = width - tleft * 2, height - ttop * 2 self.textarea = self.view.subsurface((tleft, ttop, twidth, theight)) # find biggest font size that will fit the max number of rows # with the given leading, without going under the min size for size in range(config.maxfontsize, config.minfontsize - 1, -config.sizestep): rowtotal = size * config.maxrows leadtotal = int(size * config.leadpct) * (config.maxrows - 1) if rowtotal + leadtotal <= self.textarea.get_height(): rows = config.maxrows break # if no size in range fits, start reducing number of rows if size == config.minfontsize: for rows in range(config.maxrows - 1, 0, -1): rowtotal = size * rows if rowtotal + leadtotal <= self.textarea.get_height(): break self.fsize = size self.rows = rows self.leading = int(size * config.leadpct) # draw marker msize = self.fsize / 2 self.marker = pygame.Surface((msize, msize)) self.marker.fill((255, 0, 0)) self.redraw = True def draw_frame(self): """Draw the visible columns of options on the screen, and the marker.""" if self.redraw: # blit the background, text and marker onto the view self.view.blit(self.background, (0, 0)) columns = config.columns colwidth = self.textarea.get_width() / columns srow = self.selected % self.rows scol = self.selected / self.rows # adjust offset to within (columns) of col self.col_offset = min(scol, max(self.col_offset, scol - columns + 1)) # render and blit each line of text in each column that is showing options = self.options[self.rows * self.col_offset : self.rows * (self.col_offset + columns)] optfonts = self.font.render([option[0] for option in options], self.fsize, color=config.menufontcolor) for i, optfont in enumerate(optfonts): pos = (i / self.rows * colwidth + self.fsize, i % self.rows * (self.fsize + self.leading)) self.textarea.blit(optfont, pos) # blit marker mmargin = self.fsize / 4 self.textarea.blit( self.marker, ((scol - self.col_offset) * colwidth + mmargin, srow * (self.fsize + self.leading) + mmargin), ) self.redraw = False def run_frame(self, elapsed, keys): """Scan for keystrokes and either switch menus or take actions.""" for key, keydown in keys: # arrow keys: change selection if keydown and key in (pygame.K_UP, pygame.K_RIGHT, pygame.K_DOWN, pygame.K_LEFT): col = self.selected / self.rows totalcols = (len(self.options) + self.rows - 1) / self.rows old_selected = self.selected if key in (pygame.K_UP, pygame.K_DOWN): # move marker up or down mod = 1 if key == pygame.K_DOWN else -1 self.selected = max(0, min(self.selected + mod, len(self.options) - 1)) elif key == pygame.K_LEFT and col > 0: # move marker left self.selected -= self.rows elif key == pygame.K_RIGHT and col < totalcols - 1: # move marker right self.selected = min(self.selected + self.rows, len(self.options) - 1) if self.selected != old_selected: self.redraw = True # enter key: open selected screen or quit this menu elif keydown and key == pygame.K_RETURN: screen, args = self.options[self.selected][1:] if not screen: return False self.selected = 0 self.redraw = True return screen(*args) # escape key: quit menu elif keydown and key == pygame.K_ESCAPE: return False
class Graphics: wireframe = False vertices = [] reDraw = False toggleDrawAxes = False spectator = False numberOfVertices = 0 def __init__(self, main): from font import Font global g_fVBOObjects g_fVBOObjects = [] self.main = main self.g_nFrames = 0 self.fps = 0 init_opengl(main) self.font = Font() def addSurface(self, Mesh, Obj, Texture): g_pMesh = CMesh() vertices, vnormals, f, self.vertexCount = \ loadObj(Obj) g_pMesh.textureId, textureWidthRatio, textureHeightRatio = \ loadTexture(Texture) xMax = xMin = vertices[0][0] zMax = zMin = vertices[0][2] for i in vertices: if i[0] < xMin: xMin = i[0] elif i[0] > xMax: xMax = i[0] if i[2] < zMin: zMin = i[2] elif i[2] > zMax: zMax = i[2] sizeX = xMax - xMin sizeY = zMax - zMin texCoords = Numeric.zeros ((self.vertexCount, 2), 'f') nIndex = 0 for i in vertices: self.vertices.append( CVector3(i[0], i[1], i[2]) ) self.numberOfVertices += 1 texCoords[nIndex, 0] = (i[0]-xMin) / sizeX * textureWidthRatio texCoords[nIndex, 1] = (i[2]-zMin) / sizeY * textureHeightRatio nIndex += 1 self.verticesId, self.vnormalsId, self.texCoordsId = \ createVBO(Obj, vertices, vnormals, texCoords) g_pMesh.verticesId = self.verticesId g_pMesh.vnormalsId = self.vnormalsId g_pMesh.texCoordsId = self.texCoordsId g_pMesh.vertexCount = self.vertexCount g_fVBOObjects.append(g_pMesh) def loadStaticObject(self, x, y, z, model, texture): g_pMesh = CMesh() vertices, vnormals, f, vertexCount = \ loadObj(model) for v in vertices: # transform v[0] += x v[1] += y v[2] += z g_pMesh.textureId, textureWidthRatio, textureHeightRatio = \ loadTexture(texture) xMax = xMin = vertices[0][0] zMax = zMin = vertices[0][2] for i in vertices: if i[0] < xMin: xMin = i[0] elif i[0] > xMax: xMax = i[0] if i[2] < zMin: zMin = i[2] elif i[2] > zMax: zMax = i[2] sizeX = xMax - xMin sizeY = zMax - zMin texCoords = Numeric.zeros ((vertexCount, 2), 'f') nIndex = 0 for i in vertices: self.vertices.append( CVector3(i[0], i[1], i[2]) ) self.numberOfVertices += 1 texCoords[nIndex, 0] = (i[0]-xMin) / sizeX * textureWidthRatio texCoords[nIndex, 1] = (i[2]-zMin) / sizeY * textureHeightRatio nIndex += 1 verticesId, vnormalsId, texCoordsId = \ createVBO(model, vertices, vnormals, texCoords) g_pMesh.verticesId = verticesId g_pMesh.vnormalsId = vnormalsId g_pMesh.texCoordsId = texCoordsId g_pMesh.vertexCount = vertexCount g_fVBOObjects.append(g_pMesh) def initGL(self): from skydome import Skydome if not glInitVertexBufferObjectARB(): sys.stderr.write("ERROR: Vertex buffer objects is not supported\n") #Global.quit = 1 return glClearColor( 0.0, 0.0, 0.0, 0.0) glClearDepth(1.0) glDepthFunc(GL_LEQUAL) glEnable(GL_DEPTH_TEST) glShadeModel(GL_SMOOTH) glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) glViewport(0, 0, self.main.config.getint('Resolution', 'Width'), self.main.config.getint('Resolution', 'Height')) glMatrixMode(GL_PROJECTION) #glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0) glLoadIdentity() gluPerspective(60.0, self.main.config.getfloat('Resolution','Width') / self.main.config.getfloat('Resolution', 'Height'), 0.1, 5000.0) glMatrixMode(GL_MODELVIEW) #Lighting diffuseMaterial = (0.5, 0.5, 0.0, 1.0) mat_specular = (1.0, 1.0, 1.0, 1.0) light_position = (150.0, 0.0, 75.0, 1.0) glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, diffuseMaterial) glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterial) glLightfv(GL_LIGHT1, GL_POSITION, light_position) glEnable(GL_LIGHTING) glDisable(GL_LIGHT0) glEnable(GL_LIGHT1) ########### glEnable(GL_NORMALIZE) self.skydome = Skydome() if not self.main.args['disableWater']: self.water = Water() def printFPS(self): self.fps = self.g_nFrames pygame.display.set_caption("FarornasGrotta - %d FPS" % (self.fps)) self.g_nFrames = 0 def drawAxes(self): """ Draws x, y and z axes """ light = glIsEnabled(GL_LIGHTING) if light: glDisable(GL_LIGHTING) glColor3f(1.0, 0.0, 0.0) glBegin(GL_LINES) glVertex3f(-1000.0, 0.0, 0.0) glVertex3f( 1000.0, 0.0, 0.0) glEnd() glColor3f(0.0, 1.0, 0.0) glBegin(GL_LINES) glVertex3f(0.0, -1000.0, 0.0) glVertex3f(0.0, 1000.0, 0.0) glEnd() glColor3f(0.0, 0.0, 1.0) glBegin(GL_LINES) glVertex3f(0.0, 0.0, -1000.0) glVertex3f(0.0, 0.0, 1000.0) glEnd() if light: glEnable(GL_LIGHTING) def drawPlayerList(self): glPushMatrix() glDisable(GL_LIGHTING) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glLoadIdentity() glTranslated(-320.0, -240.0, -410.0) glColor3f(1.0, 1.0, 1.0) row = 3 self.font.glPrint(80.0, 480 - 30.0 * row, "Name") self.font.glPrint(420.0, 480 - 30.0 * row, "Frags") self.font.glPrint(500.0, 480 - 30.0 * row, "Deaths") row += 1 i = 0 for obj in self.main.physics.objects: if obj.data.type != "player1": continue if obj.data.id == self.main.player.data.id: glColor3f(0.0, 1.0, 0.0) else: glColor3f(1.0, 1.0, 1.0) self.font.glPrint(80.0, 480.0 - 30.0*row, "%s" % obj.data.name) self.font.glPrint(420.0, 480.0 - 30.0*row, "%5d" % obj.data.frags) self.font.glPrint(500.0, 480.0 - 30.0*row, "%6d" % obj.data.deaths) i += 1 row += 1 glEnable(GL_LIGHTING) glPopMatrix() def drawFPS(self): glPushMatrix() glDisable(GL_LIGHTING) glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glLoadIdentity() glTranslated(-320.0, -240.0, -410.0) glColor3f(1.0, 1.0, 1.0) self.font.glPrint(540.0, 440.0, "FPS: %d" % (self.fps)) glEnable(GL_LIGHTING) glPopMatrix() def draw(self, objects): global g_fVBOObjects #if self.reDraw: #self.main.octree.g_EndNodeCount = 0 #self.main.octree.debug.Clear() #self.main.octree.DestroyOctree() #self.main.octree.GetSceneDimensions(self.vertices, self.numberOfVertices) #self.main.octree.CreateNode(self.vertices, self.numberOfVertices, # self.main.octree.GetCenter(), self.main.octree.GetWidth()) #self.reDraw = False glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ) glLoadIdentity() if self.toggleDrawAxes: self.drawAxes() glClearColor(0.4, 0.4, 0.4, 0.0) if self.wireframe: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE) else: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) glLoadIdentity() glRotatef(self.main.input.xrot, 1.0, 0.0, 0.0) glRotatef(self.main.input.yrot, 0.0, 1.0, 0.0) # SkyDome self.skydome.draw() if self.spectator: glTranslated(-self.main.input.xpos, -self.main.input.ypos, -self.main.input.zpos) else: glTranslated( -self.main.player.data.position[0]-0.2*math.sin( math.radians(self.main.player.data.orientation[1]) ), -self.main.player.data.position[1]-2.2, -self.main.player.data.position[2]+0.2*math.cos( math.radians(self.main.player.data.orientation[1]-180) ) ) self.g_nFrames += 1 if self.toggleDrawAxes: self.drawAxes() # Water if not self.main.args['disableWater']: self.water.draw() glColor3f(1.0, 1.0, 1.0) #glClearColor(0.0, 0.0, 0.6, 0.5) glFogi(GL_FOG_MODE, GL_LINEAR) glFogfv(GL_FOG_COLOR, (0.4, 0.4, 0.4, 0.0)) glFogf(GL_FOG_DENSITY, 0.1) glHint(GL_FOG_HINT, GL_DONT_CARE) glFogf(GL_FOG_START, 1.0) glFogf(GL_FOG_END, 110.0) #glEnable(GL_FOG) glEnableClientState(GL_VERTEX_ARRAY) glEnableClientState(GL_TEXTURE_COORD_ARRAY) glEnableClientState(GL_NORMAL_ARRAY) glPushMatrix() glColor3f(1.0, 1.0, 1.0) #glScalef(10.0, 10.0, 10.0) for VBOobject in g_fVBOObjects: #glEnable(GL_BLEND) #glBlendFunc(GL_ONE, GL_ONE) glBindTexture(GL_TEXTURE_2D, VBOobject.textureId) glEnable(GL_TEXTURE_2D) drawVBO(VBOobject.verticesId, VBOobject.vnormalsId, VBOobject.vertexCount, VBOobject.texCoordsId) glDisable(GL_TEXTURE_2D) #glDisable(GL_BLEND) glPopMatrix() glDisableClientState(GL_VERTEX_ARRAY) glDisableClientState(GL_TEXTURE_COORD_ARRAY) glDisableClientState(GL_NORMAL_ARRAY) glDisable(GL_FOG) if self.main.physics.octree.debugLines: # Turn OFF lighting so the debug lines are bright yellow glDisable(GL_LIGHTING) # Start rendering lines glBegin(GL_LINES) # Turn the lines yellow glColor3ub(255, 255, 0) self.main.physics.octree.debug.debugLines = [] for obj in objects: self.main.physics.octree.debug.addDebugRectangle( obj.data.position, obj.data.width, obj.data.height, obj.data.depth) # Go through the whole list of lines stored in the vector debugLines for line in self.main.physics.octree.debug.debugLines: # Pass in the current point to be rendered as part of a line glVertex3f(line[0], line[1], line[2]) # Stop rendering lines glEnd() # If we have lighting turned on, turn the lights back on glEnable(GL_LIGHTING) for obj in objects: obj.draw() if self.main.input.keys["KEY_TAB"] == 1: self.drawPlayerList() self.drawFPS() glFlush() pygame.display.flip() err = glGetError() if err: print "OpenGL Error:",err,"(",gluErrorString(err),")"
def __init__(self, pos=[0,0], font=None, prompt="", width=250, start_text="", visible=True, image_normal=None, image_hover=None, image_click=None, image_mode=None, cache_on_KEY=None, ignore_active=False, align=["left","top"], text_padding=[0,0], ignore_events=[]): self.kind="InputBox" #TODO: allow area, istead of width, and allow multiple lines of input self.pos=pos self.image_mode=image_mode self.align=align self.text_padding=text_padding self.ignore_active=ignore_active self.width=width self.ignore_events=ignore_events self.font=font if not self.font: self.font=Font() self.rect=pygame.Rect(self.pos, [width, self.font.fsize]) self.prompt=prompt self.message=start_text self.cached_messages=[] self.text_pos=len(self.message) self.cache_on_KEY=cache_on_KEY self.blink_speed=0.5 self.blink_last=time.time() self.image_normal=image_normal self.image_hover=image_hover self.image_click=image_click if self.image_normal: if isinstance(self.image_normal, pygame.Surface): pass else: self.image_normal=self.image_normal.resize(self.rect.size, self.image_mode) self.rect=self.image_normal.get_rect() self.rect.topleft=self.pos self.width=self.rect.width-self.text_padding[0]*2 if self.image_hover: if isinstance(self.image_hover, pygame.Surface): pass else: self.image_hover=self.image_hover.resize(self.rect.size, self.image_mode) if self.image_click: if isinstance(self.image_click, pygame.Surface): pass else: self.image_click=self.image_click.resize(self.rect.size, self.image_mode) self.hovering=False self.mouse_button_down=False self.am_clicked=False self.active=False self.visible=visible
class MenuScreen(Screen): def __init__(self): self.font = Font(config.menufontpath, config.menufontsize) # init menu display self.selected = 0 self.col_offset = 0 def resize_view(self): """Resize the menu view, redraw the background, and reinit the font.""" # find the largest rectangle with the configured menu ratio, # that fits within the configured menu margins. ww, wh = self.window.view.get_size() bw, bh = config.menuratio mx, my = config.menumargin mult = min(ww * (1 - mx * 2) / bw, wh * (1 - my * 2) / bh) width, height = bw * mult, bh * mult left, top = (ww - width) / 2, (wh - height) / 2 self.menuview = self.window.view.subsurface((left, top, width, height)) # create a text rectangle that fits within configured text margins tmx, tmy = config.textmargin tleft, ttop = tmx * width, tmy * height twidth, theight = width - tleft * 2, height - ttop * 2 self.textarea = self.menuview.subsurface((tleft, ttop, twidth, theight)) # find biggest font size that will fit the max number of rows # with the given rheight, without going under the min size for size in range(config.maxfontsize, config.minfontsize - 1, -config.sizestep): totalheight = int(size * config.lineheight) * (config.maxrows - 1) + size if totalheight <= self.textarea.get_height(): rows = config.maxrows break # only if no size in range fits: start reducing number of rows if size == config.minfontsize: for rows in range(config.maxrows - 1, 0, -1): totalheight = int(size * config.lineheight) * (rows - 1) + size if totalheight <= self.textarea.get_height(): break self.cheight = size self.rows = rows self.rheight = int(size * config.lineheight) # draw marker msize = self.cheight / 2 self.marker = pygame.Surface((msize, msize)) self.marker.fill(config.menumarkercolor) self.redraw = True def draw_frame(self): """Draw the visible columns of options on the screen, and the marker.""" if self.redraw: self.window.view.fill((0, 0, 0)) self.menuview.fill(config.menubackcolor) columns = config.columns colwidth = self.textarea.get_width() / columns srow = self.selected % self.rows scol = self.selected / self.rows # adjust offset to within (columns) of col self.col_offset = min(scol, max(self.col_offset, scol - columns + 1)) # render and blit each column of options that is showing # TODO: render all columns at init, and rerender only if font size or row count changes for c, col in enumerate(range(self.col_offset, columns)): opts = self.options[self.rows * col:self.rows * (col + 1)] opttext = self.font.render('\n'.join(opt[0] for opt in opts), charheight=self.cheight, lineheight=self.rheight, tracking=1, color=config.menufontcolor) self.textarea.blit(opttext, (c * colwidth + self.cheight, 0)) # blit marker mmargin = self.cheight / 4 self.textarea.blit(self.marker, ((scol - self.col_offset) * colwidth + mmargin, srow * self.rheight + mmargin)) self.redraw = False def run_frame(self, elapsed, events): """Scan for keystrokes and either switch menus or take actions.""" for event in events: # arrow keypresses if event.type == pygame.KEYDOWN and event.key in self.movekeys: movedir = self.movekeys.index(event.key) self._move_marker(((0, 1), (1, 0), (0, -1), (-1, 0))[movedir]) # joystick hat motion elif event.type == pygame.JOYHATMOTION and event.joy == 0 and event.value != (0, 0): self._move_marker(event.value) # enter key or joystick button (currently any button from 0-3) elif ((event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN) or (event.type == pygame.JOYBUTTONDOWN and event.button <= 3)): func = self.options[self.selected][1] args = self.options[self.selected][2:] # run the selected option, exiting afterward if it returns false result = getattr(self, func)(*args) if result is False: return False # reset menu self.resize_view() self.selected = 0 # escape key elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: return False def _move_marker(self, (dx, dy)): """Move the menu marker up, down, left or right.""" col = self.selected / self.rows totalcols = (len(self.options) + self.rows - 1) / self.rows old_selected = self.selected if dy: # move marker up or down self.selected = max(0, min(self.selected - dy, len(self.options) - 1)) elif dx: # move marker left or right if 0 <= col + dx < totalcols: # move up to last item in the column if we're below it self.selected = min(self.selected + (self.rows * dx), len(self.options) - 1) if self.selected != old_selected: self.redraw = True
def __init__(self): self.font = Font(config.menufontpath, config.menufontsize) # init menu display self.selected = 0 self.col_offset = 0
class InputBox(object): def __init__(self, pos=[0,0], font=None, prompt="", width=250, start_text="", visible=True, image_normal=None, image_hover=None, image_click=None, image_mode=None, cache_on_KEY=None, ignore_active=False, align=["left","top"], text_padding=[0,0], ignore_events=[]): self.kind="InputBox" #TODO: allow area, istead of width, and allow multiple lines of input self.pos=pos self.image_mode=image_mode self.align=align self.text_padding=text_padding self.ignore_active=ignore_active self.width=width self.ignore_events=ignore_events self.font=font if not self.font: self.font=Font() self.rect=pygame.Rect(self.pos, [width, self.font.fsize]) self.prompt=prompt self.message=start_text self.cached_messages=[] self.text_pos=len(self.message) self.cache_on_KEY=cache_on_KEY self.blink_speed=0.5 self.blink_last=time.time() self.image_normal=image_normal self.image_hover=image_hover self.image_click=image_click if self.image_normal: if isinstance(self.image_normal, pygame.Surface): pass else: self.image_normal=self.image_normal.resize(self.rect.size, self.image_mode) self.rect=self.image_normal.get_rect() self.rect.topleft=self.pos self.width=self.rect.width-self.text_padding[0]*2 if self.image_hover: if isinstance(self.image_hover, pygame.Surface): pass else: self.image_hover=self.image_hover.resize(self.rect.size, self.image_mode) if self.image_click: if isinstance(self.image_click, pygame.Surface): pass else: self.image_click=self.image_click.resize(self.rect.size, self.image_mode) self.hovering=False self.mouse_button_down=False self.am_clicked=False self.active=False self.visible=visible def update(self, event): mouse_pos=pygame.mouse.get_pos() if self.visible: if event.type==MOUSEBUTTONDOWN: if event.button==1: if self.rect.collidepoint(mouse_pos): self.mouse_button_down=True else: self.mouse_button_down=False elif event.type==MOUSEBUTTONUP: self.mouse_button_down=False if event.button==1: if self.rect.collidepoint(mouse_pos): self.was_clicked=True self.active=True self.am_clicked=True else: self.was_clicked=False self.active=False self.am_clicked=False elif event.type==KEYDOWN: if self.active or self.ignore_active: a=gui_util.convert_event_to_key(event) if not a: return if a in self.ignore_events: return if self.cache_on_KEY: if a==self.cache_on_KEY: self.cached_messages.append(self.message) self.message="" self.text_pos=0 return if event.type==KEYDOWN: if event.key==self.cache_on_KEY: self.cached_messages.append(self.message) self.message="" self.text_pos=0 return if a=="BACK": if self.text_pos: self.message=self.message[:len(self.message)-1] self.text_pos-=1 elif a=="DEL": if len(self.message) > self.text_pos: self.message=self.message[:self.text_pos]+\ self.message[self.text_pos+1:] elif a=="HOME": self.text_pos=0 elif a=="END": self.text_pos=len(self.message) elif a=="LEFT": if self.text_pos>0: self.text_pos-=1 elif a=="RIGHT": if self.text_pos<len(self.message): self.text_pos+=1 elif a=="RETURN": b=self.message[:self.text_pos]+"\n"+self.message[self.text_pos+1:] if self.font.size(self.prompt+b)[0]<self.width: self.message=b self.text_pos+=1 elif a=="TAB": b=self.message[:self.text_pos]+" "+self.message[self.text_pos+1:] if self.font.size(self.prompt+b)[0]<self.width: self.message=b self.text_pos+=4 else: b=self.message[:self.text_pos]+a+self.message[self.text_pos+1:] if self.font.size(self.prompt+b)[0]<self.width: self.message=b self.text_pos+=1 if self.rect.collidepoint(mouse_pos): self.hovering=True if self.mouse_button_down: self.am_clicked=True else: self.am_clicked=False else: self.hovering=False def empty_cache(self): a=self.cached_messages[::] self.cached_messages=[] return a def render(self, surface): if self.visible: if self.am_clicked: image=self.image_click elif self.hovering: image=self.image_hover else: image=self.image_normal if image: if isinstance(image, pygame.Surface): surface.blit(image, self.rect.topleft) else: image.render(surface, self.rect.topleft) text=self.font.render(self.prompt+self.message) r=text.get_rect() if self.align[0]=="left": r.left=self.rect.left elif self.align[0]=="center": r.centerx=self.rect.centerx else: r.right=self.rect.right if self.align[1]=="top": r.top=self.rect.top elif self.align[1]=="center": r.centery=self.rect.centery else: r.bottom=self.rect.bottom r.left+=self.text_padding[0] r.top+=self.text_padding[1] surface.blit(text, r.topleft) if time.time()>=self.blink_last+self.blink_speed: r.left=r.right r.left-=self.font.size(self.message[self.text_pos::])[0] r.left-=self.font.fsize/15 if self.active or self.ignore_active: surface.blit(self.font.render("|"), r) if time.time()>=self.blink_last+self.blink_speed*2: self.blink_last=time.time()
BMA = bunchMarker(PINS["BMASRCLK"], PINS["BMARCLK"], PINS["SRA"], GPIO) BMB = bunchMarker(PINS["BMBSRCLK"], PINS["BMBRCLK"], PINS["SRB"], GPIO) BMA.reset() BMB.reset() BMA.bunchMarker(user.bunchMarkerA) BMB.bunchMarker(user.bunchMarkerB) show = True print "SHOW DISPLAY: (0: No or 1: Yes)" show = bool(int(raw_input())) # Initialize Fonts font14h = Font("font14h") font14h.init_bitmap("font14h.csv") font14hL = Font("font14hL.csv") font14hL.init_bitmap("font14hL.csv") # Initialize Display # Set Label Strings bmaTitle = "BMA:" bmbTitle = "BMB:" testCircuit = "TEST CIRCUIT:" pll = "PLL:" schrod = "SCROD:" # Set Label Values bmaValue = str(user.bunchMarkerA)
class Label(object): ''' Text Label Object init args: pos - list[x,y], font, message, image - image, wrap_text - bool, align ["left"/"right","top"/"bottom"], visible - bool, image_mode - scale,split,enlarge,multiply''' def __init__(self, pos=[0,0], font=None, message="", image=None, wrap_text=False, align=["left","top"], visible=True, image_mode=None): self.pos=pos self.kind="Label" self.font=font if not font: self.font=Font() self.message=message self.lines=[] self.message_image=None self.image=image self.image_mode=image_mode self.wrap_text=wrap_text self.align=align self.visible=visible self.refactor() def refactor(self): self.lines, area=gui_util.wrap_text(self.font, self.message, self.wrap_text) self.area=list(area) if self.image: if isinstance(self.image, pygame.Surface): pass else: self.image=self.image.resize(self.area, self.image_mode) if self.image.get_width() > self.area[0]: self.area[0]=self.image.get_width() if self.image.get_height() > self.area[1]: self.area[1]=self.image.get_height() self.message_image=pygame.Surface(self.area).convert_alpha() self.message_image.fill([0,0,0,0]) l=[self.font.render(i) for i in self.lines] for i in range(len(l)): line=l[i] r=line.get_rect() if self.align[0]=="left": r.left=0 elif self.align[0]=="center": r.centerx=self.area[0]/2 else: r.right=self.area[0] if self.align[1]=="top": r.top=0 elif self.align[1]=="center": r.centery=self.area[1]/2 else: r.right=self.area[1] r.top+=i*(self.font.fsize-(self.font.fsize/3)) self.message_image.blit(line, r.topleft) self.rect=pygame.Rect(self.pos, self.area) def update(self, event): pass def render(self, surface): if self.visible: if self.image: if isinstance(self.image, pygame.Surface): surface.blit(self.image, self.rect) else: self.image.render(surface, self.rect) surface.blit(self.message_image, self.rect.topleft)
class Tris(object): INFO_TEXT = ["CONTROLS", "--------", "", "MOVE -- ARROW KEYS", "ROTATE -- J/K ", "HARD DROP -- SPACE", "QUIT -- ESCAPE "] HISCORES_TEXT = ["HISCORES", "--------", ""] CREDITS_TEXT = ["CREDITS", "-------", "", "ORIGNAL CONCEPT AND", "DESIGN BY ", "ALEXEY PAJITNOV ", "", "FEVER CODE AND ", "ART BY ", "SRAL ", "", "", "", "WWW.GITHUB.COM/SRAL"] GAME_OVER_TEXT = ["GAME OVER !!!"] ENTER_HISCORE_TEXT = ["HISCORE", "-------", "ENTER INITIALS:", ""] def __init__(self): """Initialize instance.""" self.level = 0 self.lines = 0 self.player = None self.font = None self.splash_image = None self.tileset = None self.hiscores = None def setup(self): """Setup game.""" pygame.init() image = pkg_resources.resource_filename(__name__, 'data/icon.gif') pygame.display.set_icon(pygame.image.load(image)) pygame.display.set_caption("tris") self.tileset = Tileset('data/blocks.gif', 16, 16) image = pkg_resources.resource_filename(__name__, 'data/splash.gif') self.splash_image = pygame.image.load(image) self.font = Font() self.hiscores = Persistor.load() if not self.hiscores: self.hiscores = HiScores.get_default_hiscore_list() @staticmethod def smoothstep(n): """Smoothstep interpolation. Keyword arguments: n -- Value to smooth """ # TODO: Sprinkle this on scrollers return n * n * (3 - 2 * n) @staticmethod def lerp(start, stop, steps): """Linear interpolation between two values. Keyword arguments: start -- Start from stop -- Stop at steps -- Number of discreet steps """ i = 0.0 while i <= steps: v = i / steps yield (stop * v) + (start * (1 - v)) i += 1 @staticmethod def get_ordinal(n): """Returns ordinal (1st, 2nd, 3th, 4th, ...) Keyword arguments: n -- Number """ if not 0 <= n < 1000: raise ValueError("Domain error") ordinal_suffix = {1: "ST", 2: "ND", 3: "RD"} unit_digit = n % 10 tens_digit = (n / 10) % 10 if tens_digit == 1: return "{0}TH".format(n) else: return "{0}{1}".format( n, ordinal_suffix.get(unit_digit, "TH")) def fade(self, fade_surface, start_alpha=MIN_ALPHA, stop_alpha=MAX_ALPHA): """Fade surface. Keyword arguments: fade_surface -- Surface to fade in/out start_alpha -- Value to start fade from stop_alpha -- Value to stop fade at """ surface = pygame.display.get_surface() for alpha in self.lerp(start_alpha, stop_alpha, 50): surface.fill((0, 0, 0)) fade_surface.set_alpha(alpha) surface.blit(fade_surface, (0, 0)) pygame.display.flip() pygame.time.delay(5) def new_game(self): """Initialize new game.""" self.player = Player() self.lines = 0 self.level = 0 def exit_game(self): """Exit game.""" Persistor.save(self.hiscores) fade_surface = pygame.display.get_surface().copy() self.fade(fade_surface, MAX_ALPHA, MIN_ALPHA) sys.exit(0) def splash_screen(self): """Display splash screen.""" pygame.time.set_timer(pygame.USEREVENT, 5000) surface = pygame.display.set_mode((SPLASH_WIDTH, SPLASH_HEIGHT)) fade_surface = pygame.Surface((SPLASH_WIDTH, SPLASH_HEIGHT)) fade_surface.blit(self.splash_image, (0, 0)) self.fade(fade_surface, MIN_ALPHA, MAX_ALPHA) hiscore_list = list(self.HISCORES_TEXT) for n, hiscore in enumerate(self.hiscores): hiscore_list.append( "{0:>4} {1.name:>5} {1.score:>10}".format( self.get_ordinal(n + 1), hiscore) ) texts = (self.INFO_TEXT, hiscore_list, self.CREDITS_TEXT) text_index = 0 while True: event = pygame.event.poll() if event.type == pygame.QUIT: self.exit_game() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.exit_game() if event.key == pygame.K_RETURN: break elif event.type == pygame.USEREVENT: if text_index < len(texts) - 1: text_index += 1 else: text_index = 0 surface.blit(self.splash_image, (0, 0)) self.font.write_lines(100, texts[text_index]) pygame.display.flip() def game_over(self): """Display Game Over screen.""" surface = pygame.display.get_surface() fade_surface = surface.copy() self.fade(fade_surface, MAX_ALPHA, MAX_ALPHA / 4) width = surface.get_width() clear_surface = pygame.Surface((width, 8)) clear_surface.blit(surface, (0, 0), area=(0, 160, width, 8)) is_hiscore = self.hiscores.is_hiscore(self.player.score) initials = [] while True: event = pygame.event.poll() if event.type == pygame.QUIT: self.exit_game() elif event.type == pygame.KEYDOWN: if event.key in (pygame.K_ESCAPE, pygame.K_RETURN): break elif is_hiscore and event.type == pygame.KEYUP: if (pygame.K_a <= event.key <= pygame.K_z and len(initials) < 3): initials.append(pygame.key.name(event.key)) elif initials and event.key in (pygame.K_BACKSPACE, pygame.K_DELETE): initials.pop() self.font.write_lines(100, self.GAME_OVER_TEXT) if is_hiscore: self.font.write_lines(120, self.ENTER_HISCORE_TEXT) surface.blit(clear_surface, (0, 160)) self.font.write( 56, 160, " ".join([n.upper() for n in initials])) pygame.display.flip() if is_hiscore: self.hiscores.add("".join(initials).upper(), self.player.score) fade_surface = pygame.display.get_surface().copy() self.fade(fade_surface, MAX_ALPHA, MIN_ALPHA) def update_level(self): """Update game level i.e. falling speed.""" self.level = int(self.lines / 10) speed = START_SPEED - self.level * 70 if speed <= 0: speed = 10 pygame.time.set_timer(pygame.USEREVENT, speed) def process_lines(self, playfield): """Process playfield lines. Keyword arguments: playfield -- Playfield """ lines = playfield.find_lines() if lines: self.player.score += 2 ** (lines - 1) * 100 self.lines += lines self.update_level() @staticmethod def legal_move(playfield, trimino): """Returns True if move is legal, False otherwise. Keyword arguments: playfield -- Current playfield trimino -- Trimino that is being moved """ for x, y in trimino.keys(): x += trimino.x y += trimino.y if (x < 0 or x >= PLAYFIELD_WIDTH or y >= PLAYFIELD_HEIGHT or playfield[(x, y)]): return False return True def spawn_trimino(self): """Returns new trimino.""" trimino = Trimino.get_random(int(PLAYFIELD_WIDTH / 2), 0, self.tileset) trimino.y = -trimino.get_height() - 1 return trimino def game_loop(self): """Game loop.""" surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) surface.fill(0xC4CFA1) # Same colour as splash screen playfield = Playfield(PLAYFIELD_WIDTH, PLAYFIELD_HEIGHT, self.tileset) pygame.time.set_timer(pygame.USEREVENT, START_SPEED) clock = pygame.time.Clock() trimino = self.spawn_trimino() game_over = False while not game_over: event = pygame.event.poll() if event.type == pygame.QUIT: self.exit_game() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: break if event.key == pygame.K_j: if not self.legal_move(playfield, trimino.rotate_left()): trimino.rotate_right() # Revert rotation if event.key == pygame.K_k: if not self.legal_move(playfield, trimino.rotate_right()): trimino.rotate_left() # Revert rotation if event.key == pygame.K_SPACE: # Hard drop while self.legal_move(playfield, trimino.move_down()): pass if playfield.place_trimino(trimino.move_up()): trimino = self.spawn_trimino() self.process_lines(playfield) else: game_over = True elif event.type == pygame.USEREVENT: if not self.legal_move(playfield, trimino.move_down()): if playfield.place_trimino(trimino.move_up()): trimino = self.spawn_trimino() self.process_lines(playfield) else: game_over = True pressed = pygame.key.get_pressed() if pressed[pygame.K_LEFT]: if not self.legal_move(playfield, trimino.move_left()): trimino.move_right() # Revert move if pressed[pygame.K_RIGHT]: if not self.legal_move(playfield, trimino.move_right()): trimino.move_left() # Revert move if pressed[pygame.K_DOWN]: if not self.legal_move(playfield, trimino.move_down()): trimino.move_up() # Revert move playfield.draw() trimino.draw() self.font.write(0, 1, "SCORE: %d" % self.player.score) self.font.write(0, 10, "LEVEL: %d" % self.level) pygame.display.flip() clock.tick(30) pygame.time.set_timer(pygame.USEREVENT, 0) # Disable timer def run(self): """Main loop.""" self.setup() while True: self.splash_screen() self.new_game() self.game_loop() self.game_over()
def setup_font(self, char, char_data): send = self._connector.send_byte send(0x40 + (char << 3), DISP_CMD) for x in Font.bit_array(char_data): send(x, DISP_CHR)