def __init__(self, filename, **kwargs): kwargs.update({ 'width': 500, 'height': 500, 'vsync': True, 'resizable': True, }) super(BoxWorldWindow, self).__init__(**kwargs) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) graphics.InitWithPyglet(self) graphics.text_color(name='BLACK') glClearColor(0.9, 0.9, 0.9, 1.0) # Grey self.world = BoxWorld.FromFile(filename, self.get_size()) self.world.reset_navgraph() # prep the fps display and some labels self.fps_display = None colour_black = (0, 0, 0, 255) self.labels = { 'mouse': Label('', x=5, y=self.height - 20, color=colour_black), 'search': Label('', x=120, y=self.height - 20, color=colour_black), 'status': Label('', x=300, y=self.height - 20, color=colour_black), } self._update_label() self.add_handlers() self.limit = 0 # Unlimited
def update_data(self, refresh_label: bool = True, refresh_background: bool = True, **items): for k, v in items: if k in self._label_data or k in self._background_box_data: if k in self._label_data: self._log( INFO, f"changed Button with id value {self._id} label data value {k}: {self._label_data[k]} -> {v}; Forcing a refresh of label data", ) self._label_data[k] = v refresh_label = True if k in self._background_box_data: self._log( INFO, f"changed Button with id value {self._id} background data value {k}: {self._background_box_data[k]} -> {v}; Forcing a refresh of background data", ) self._background_box_data[k] = v refresh_background = True else: res = super().update_data((k, v)) if res.is_err(): errormsg = f"Failed to update item {k} to {v} on Button with id {self.id} -> {res.err}" self._log(ERROR, errormsg) raise KeyError(errormsg) if refresh_label: self._log(INFO, f"Refreshing label data") self._label = Label(**self._label_data) if refresh_background: self._log(INFO, f"Refreshing background data") self._background_box = Rect(**self._background_box_data)
class Label(Control): def __init__(self, text=u'Label', font_size=30, color=(0, 0, 0, 255), x=0, y=0, bold=False, italic=False, *a, **k): self.rawlabel = RawLabel(text=text, font_size=font_size, color=color, x=0, y=0, anchor_x='left', anchor_y='bottom', bold=bold, italic=italic) w, h = self.rawlabel.content_width, self.rawlabel.content_height Control.__init__(self, x=x, y=y, width=w, height=h, *a, **k) def draw(self): self.rawlabel.draw()
class QuitScreen(MenuClass): """docstring for QuitScreen""" def __init__(self, *args, **kwargs): super(QuitScreen, self).__init__(*args, **kwargs) self.buttons['quit'] = btn([300, 300], 'yes') self.buttons['dont_quit'] = btn([680, 300], 'no') self.text = 'do you really want to quit?' self.Label = Label(self.text, font_name=font, font_size=36, bold=False, x=640, y=500, anchor_x='center', anchor_y='center') self.Box = Box([340, 200], [600, 400], 2) def handle_clicks(self, key): if key == 'quit': self.send_message('kill_self') if key == 'dont_quit': self.send_message('menu_transition_-') def draw(self): self.Box.draw() for key_, panel in self.buttons.iteritems(): panel.draw() self.Label.draw()
def __init__(self, overlay): self.overlay = overlay self.batch = self.overlay.batch self.sizeX, self.sizeY, = self.overlay.width // 4, self.overlay.height // 4, self.shown = True self.text = 'YOU DIED\n\npress [space] to close' self.endscreen = self.batch.add(4, GL_QUADS, None, ('v2i/static', (0, ) * len(self.getCoords())), ('c4B/static', ( 100, 100, 100, 150, ) * 4)) self.endscreenLabel = Label('', font_name='Consolas', font_size=50, width=self.sizeX * 2, color=( 200, 0, 0, 255, ), batch=self.batch, anchor_x='center', anchor_y='center', x=self.overlay.centerX, y=self.overlay.centerY + 30, align='center', multiline=True)
class GameOver(): def __init__(self, a_scale, backgroundX, backgroundY): self.game_over = Label('Game Over', font_name='Cracked Johnnie', font_size=56 * a_scale, x=backgroundX + (500 * a_scale), y=backgroundY + (500 * a_scale), color=(140, 0, 0, 0), anchor_x='center', anchor_y='center', align='center') self.restart = Label('Press W To Menu', font_name='Times New Roman', font_size=24 * a_scale, x=backgroundX + (500 * a_scale), y=backgroundY + (440 * a_scale), color=(50, 50, 50, 0), anchor_x='center', anchor_y='center', align='center') def draw(self): self.game_over.draw() self.restart.draw() def make_visible(self): self.game_over.color = (140, 0, 0, 255) self.restart.color = (50, 50, 50, 255)
class Button(Rectangle): def __init__(self, x, y, width, height, image=None, caption=None, batch=None, group=None): super(Button, self).__init__(x, y, width, height) self.batch = batch self.group = group self.sprite = None self.label = None if image: self.sprite = Sprite(image.get_region(0, 0, self.width, self.height), batch=self.batch, group=self.group) if caption: self.label = Label(caption, font_name='Arial', font_size=12, anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.batch, group=self.group) self.set_position(x, y) def set_position(self, x, y): super(Button, self).set_position(x, y) if self.sprite: self.sprite.x, self.sprite.y = x, y if self.label: self.label.x, self.label.y = self.get_center() def draw(self): if self.sprite: self.sprite.draw() if self.label: self.label.draw()
def __init__(self, assets: Assets, window: Window, audio_manager: AudioManager): Scene.__init__(self, assets, window, audio_manager) self.logger = logging.getLogger(__name__) self.batch = Batch() self.background = OrderedGroup(0) self.foreground = OrderedGroup(1) # Logo image and sprite self.logo_image = None self.logo_sprite = None # Version and info labels self.version_label = Label(f"Version: { divineoasis.__version__ }", x=10, y=30, group=self.foreground, batch=self.batch, font_size=16, font_name="Hydrophilia Iced") self.author_label = Label(f"by { divineoasis.__author__ }", x=10, y=10, group=self.foreground, batch=self.batch, font_size=16, font_name="Hydrophilia Iced")
def __init__(self, perception=None, atraction=None, debug=False): ''' Initiates the survivor. If perception and atraction are not given then a random vector is generated. ''' self.pos = np.random.randint(low=0, high=1000, size=2).astype('float32') self.vel = np.random.rand(2)*10 self.acc = np.array([0., 0.]) # self.size = 15 self.health = 10. self.debug = debug self.count = 0 if perception is None: self.perception = np.random.randint(low=15, high=120, size=2) else: self.perception = perception if random() < 0.1: self.perception += np.random.randint(-10, 10, size=2) if atraction is None: self.atraction = 6 * np.random.rand(2) - 3 else: self.atraction = atraction if random() < 0.1: self.atraction += 0.6 * np.random.rand(2) - 0.3 self.label = Label(text='0', font_size=12, x=self.pos[0]+self.size, y=self.pos[1]++self.size, color=(0,0,0,255))
def __init__(self, game_scale, backX, backY, the_player): self.array = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] self.a_scale = game_scale self.title = Label("Inventory", font_name='Times New Roman', font_size=56 * game_scale, x=backX + (500 * game_scale), y=backY + (750 * game_scale), color=(135, 135, 135, 128), align='center', anchor_x='center', anchor_y='center') self.quit = Label("(Press Esc to save and quit)", font_name='Times New Roman', font_size=16 * game_scale, x=backX + (500 * game_scale), y=backY + (690 * game_scale), color=(135, 135, 135, 128), align='center', anchor_x='center', anchor_y='center') self.startX = backX self.startY = backY self.this_player = the_player self.fill_with_slots() self.highlighted_x = 0 self.highlighted_y = 0 self.array[self.highlighted_y][self.highlighted_x].toggle_highlight()
class Scroll(object): def __init__(self, text, pos, batch): self.text = text x, y = self.pos = pos group = OrderedGroup(1) self.label = Label(text, font_name=FONT_NAME, font_size=28, color=COLOUR, x=x + 20, y=y + 15, group=group, batch=batch) w = self.label.content_width + 40 self.bg = ScrollBG(x, x + w, y, batch=batch, group=OrderedGroup(0)) self.left = Sprite(scroll_left, x=x, y=y, group=group, batch=batch) self.right = Sprite(scroll_right, x=x + w, y=y, group=group, batch=batch) def delete(self): self.label.delete() self.left.delete() self.right.delete() self.bg.delete()
def __init__(self, *, player: Player, space: pymunk.Space, ui_batch=None, background_batch=None): super().__init__() self.player = player self.space = space self.background_batch = background_batch self.danger_sprite = Sprite(img=resources.danger_image, batch=background_batch, x=128, y=128) self.danger_sprite.visible = False # Internal score modified by the property below self._score = 0 # Show the score self.score_label = Label('', font_name='m5x7', font_size=48, x=WIDTH - 10, y=HEIGHT, anchor_x='right', anchor_y='top', batch=ui_batch) # "call" the property setter below self.score = self._score
def __init__(self, trans, *a, **k): self.trans = trans cards = trans.cards self.inputlet = None w = 20 + (91 + 10) * 4 + 20 h = 20 + 125 + 20 + 125 + 20 + 20 self.lbl = Label( text=u"等待其他玩家操作", x=w//2, y=300, font_size=12, color=(255, 255, 160, 255), shadow=(2, 0, 0, 0, 230), anchor_x='center', anchor_y='bottom' ) Panel.__init__(self, width=1, height=1, zindex=5, *a, **k) parent = self.parent self.x, self.y = (parent.width - w)//2, (parent.height - h)//2 + 20 self.width, self.height = w, h self.update() self.mapping = mapping = {} for i, c in enumerate(cards): y, x = divmod(i, 4) x, y = 20 + (91 + 10) * x, 20 + (125 + 20) * (1 - y) cs = CardSprite(c, parent=self, x=x, y=y) cs.associated_card = c mapping[id(c)] = cs @cs.event def on_mouse_dblclick(x, y, button, modifier, cs=cs): if cs.gray: return ilet = self.inputlet if not ilet: return ilet.set_card(cs.associated_card) ilet.done()
class Button(object): """docstring for Button""" def __init__(self, text, x, y, width, height, batch, color=(50, 50, 50), scale=unity, **kwargs): super(Button, self).__init__() self.pos = vec2(x, y) * scale self.width = width * scale.x self.height = height * scale.y self.bsize = 2 * scale.x self.color = color self.hcolor = hcolor self.text = Label(text, x=(self.pos.x + self.width / 2), y=(self.pos.y + self.height / 2), anchor_x='center', anchor_y='center', batch=batch, **kwargs) self.bound = Rect(self.pos.x - self.bsize, self.pos.y - self.bsize, self.width+2*self.bsize, self.height+2*self.bsize, color=toplinecolor, batch=batch) self.rect = Rect(self.pos.x, self.pos.y, self.width, self.height, color=self.color, batch=batch) def highlight(self): self.rect.update_color(self.hcolor) def restore(self): if not self.rect.color == self.color: self.rect.update_color(self.color) def over_button(self, x, y): return (0 < x - self.pos.x < self.width and 0 < y - self.pos.y < self.height) def delete(self): self.text.delete() self.rect.delete()
def draw_text(text, x, y, position, font_size): score = Label( text, font_name='League Gothic', font_size=font_size, x=x, y=y, anchor_x=position) score.draw()
def __init__(self, window, text, position, color=(255, 255, 255, 255), font_size=24, fixed_bottom=True, fixed_left=True): from pyglet.text import Label self.position = position self.window = window self.fixed_bottom = fixed_bottom self.fixed_left = fixed_left self.color = color if self.fixed_bottom: pos_y = self.position[1] else: pos_y = self.window.height - self.position[1] if self.fixed_left: pos_x = self.position[0] else: pos_x = self.window.width - self.position[0] self.label = Label(text, x=pos_x, y=pos_y, font_size=font_size, bold=True, color=self.color)
def __init__(self, model: ShipPartModel, mesh=None): super().__init__(model, mesh) step = 36 r_step = radians(step) ten_radians = [radians(d) for d in range(0, 360, step)] circle = [(cos(d), sin(d), cos(d + r_step), sin(d + r_step)) for d in ten_radians] circle = [x for x in chain(*circle)] self.circle_v2f = ('v2f', circle) self.circle_n_points = int(len(circle) / 2) self.circle_c4B = ('c4B', [100, 150, 200, 128] * self.circle_n_points) self.circle_c4B_lowlight = ('c4B', [100, 150, 200, 128] * self.circle_n_points) self.circle_c4B_highlight = ('c4B', [200, 220, 255, 128] * self.circle_n_points) self.bbox_v2f = ('v2f', list( chain( *[(l.x1, l.y1, l.x2, l.y2) for l in self._model.bounding_box.lines]))) self.bbox_n_points = len(self._model.bounding_box.lines) * 2 self.bbox_c4f = ('c4f', [1., 1., 1., 1.] * self.bbox_n_points) self._show_circle = False self.font_size = 60 half_font_size = int(self.font_size / 2) self.infobox = Label("", font_name='Courier New', font_size=self.font_size, y=-half_font_size) self.model.observe(self.update_infobox, "working")
def _generate_text(self): real_cord = lambda x, y: (x + self.camera.offset_x, y + self.camera. offset_y) pause_x, pause_y = real_cord(10, 10) Label('Paused', font_name='Times New Roman', font_size=56, x=pause_x, y=pause_y, batch=self.text_batch) menu_texts = reversed(self.menu_items.keys()) for i, text in enumerate(menu_texts): text_x, text_y = real_cord(400, 500 - 40 * i) Label(text, font_name='Times New Roman', font_size=36, x=text_x, y=text_y, batch=self.text_batch) hint_x, hint_y = real_cord(400, 30) Label("Use Up and Down Arrows to navigate", font_name='Times New Roman', font_size=18, x=hint_x, y=hint_y, batch=self.text_batch) Label("Use Enter to choose", font_name='Times New Roman', font_size=18, x=hint_x, y=hint_y - 20, batch=self.text_batch)
def _generate_text(self): real_cord = lambda x, y: (x + self.camera.offset_x, y + self.camera. offset_y) menu_texts = reversed(self.menu_items.keys()) for i, text in enumerate(menu_texts): text_x, text_y = real_cord(300, 200 - 40 * i) Label(text, font_name='Times New Roman', font_size=36, x=text_x, y=text_y, batch=self.text_batch) hint_x, hint_y = real_cord(400, 30) Label("Use Up and Down Arrows to navigate", font_name='Times New Roman', font_size=18, x=hint_x, y=hint_y, batch=self.text_batch) Label("Use Enter to choose", font_name='Times New Roman', font_size=18, x=hint_x, y=hint_y - 20, batch=self.text_batch) Label("Player %s Won!" % self.winner, font_name='Times New Roman', font_size=48, x=hint_x - 150, y=hint_y + 370, batch=self.text_batch)
class GameOverInterface(Interface): game_over_label: Label = None game_over_menu: menus.menu.Menu = None def __init__(self): self.game_over_label = Label('GAME OVER', font_name=press_start_2p, font_size=48) self.game_over_label.anchor_x = 'center' self.game_over_label.anchor_y = 'center' self.game_over_menu = menus.game_over_menu.GameOverMenu() self.resize() window = system.get_window() window.on_key_press = self.game_over_menu.on_key_press self.game_over_menu.focused = True explosion.play() def on_draw(self): self.game_over_label.draw() self.game_over_menu.draw() def resize(self): window = system.get_window() self.game_over_menu.move(window.width / 2, 100) self.game_over_label.x = window.width / 2 self.game_over_label.y = window.height / 2
class SavingLabelHandler: def __init__(self, overlay): self.overlay = overlay self.batch = self.overlay.batch self.counter = 0 self.dots = '' self.saving_lbl = Label('', font_name='Consolas', font_size=20, color=( 0, 0, 0, 255, ), batch=self.batch, anchor_x='center', anchor_y='center', x=self.overlay.centerX, y=self.overlay.height - 30) def __call__(self): self.saving_lbl.begin_update() if self.overlay.game.savingstate.saving: self.counter += 1 if self.counter % 5 == 0: if len(self.dots) == 3: self.dots = '' self.dots += '.' self.saving_lbl.text = 'speichert' + self.dots else: self.saving_lbl.text = '' self.saving_lbl.end_update()
class InstructionsInterface(Interface): title_label: Label = None main_container: LinearLayout = LinearLayout() def __init__(self): self.title_label = Label('HOW TO PLAY', font_name=press_start_2p, font_size=48) # self.title_label.anchor_x = 'center' # self.title_label.anchor_y = 'center' self.step1_label = Label('Dodge Projectiles', font_name=press_start_2p, font_size=48) # self.step1_label.anchor_x = 'center' # self.step1_label.anchor_y = 'center' self.step2_label = Label('Charge Your Energy', font_name=press_start_2p, font_size=48) # self.step2_label.anchor_x = 'center' # self.step2_label.anchor_y = 'center' self.step3_label = Label('Defeat Enemies', font_name=press_start_2p, font_size=48) # self.step3_label.anchor_x = 'center' # self.step3_label.anchor_y = 'center' projectiles = [ ('Homing Projectiles', image.load(join(getcwd(), 'images', 'candy_cane.png'))), ('Staryu', image.load(join(getcwd(), 'images', 'staryu.png'))), ('Meteor', image.load(join(getcwd(), 'images', 'meteor_1.png'))), ] powerups = [ # ('Cookie (Heal)', image.load(join(getcwd(), 'images', 'cookie.png'))) ] self.main_container.append(self.step1_label) self.main_container.append(self.step2_label) self.main_container.append(self.step3_label) def on_draw(self): self.title_label.draw() self.main_container.draw() def on_bind(self): self.resize() def resize(self): window = system.get_window() self.title_label.x = window.width / 2 self.title_label.y = window.height - self.title_label.content_height / 2 self.main_container.width = window.width self.main_container.height = window.height - self.title_label.height self.main_container.x = window.width / 2 self.main_container.y = window.height - self.title_label.content_height self.main_container.render()
def _vertical_display(viewer, leftx, stripx, value, title): dy = HUD.VERTICAL_POINTER_HEIGHT # Display a tapered strip in the middle for highlighting current value stripw = HUD.VERTICAL_BOX_WIDTH + dy x1, y1 = stripx, 0+HUD.H/2 x2, y2 = stripx+dy, dy+HUD.H/2 x3, y3 = stripx+stripw-dy, dy+HUD.H/2 x4, y4 = stripx+stripw, 0+HUD.H/2 x5, y5 = stripx+stripw-dy, -dy+HUD.H/2 x6, y6 = stripx+dy, -dy+HUD.H/2 viewer.draw_polygon([(x1, y1), (x2, y2), (x3, y3), (x4, y4), (x5, y5), (x6, y6)], color=HUD.HIGHLIGHT_COLOR) # Display a box for the gauge lx = leftx rx = lx + HUD.VERTICAL_BOX_WIDTH b = HUD.H/2 - HUD.VERTICAL_BOX_HEIGHT/2 t = HUD.H/2 + HUD.VERTICAL_BOX_HEIGHT/2 viewer.draw_polygon([(lx, t), (rx, t), (rx, b), (lx, b)], color=HUD.LINE_COLOR, linewidth=2, filled=False) # Display the current values in the box closest = value // HUD.VERTICAL_STEP_METERS * HUD.VERTICAL_STEP_METERS for k in range(-3, 4): tickval = closest+k*HUD.VERTICAL_STEP_METERS diff = tickval - value dy = diff*HUD.VERTICAL_STEP_PIXELS # Use a linear fade-in/out for numbers at top, bottom alpha = int(255 * (HUD.VERTICAL_BOX_HEIGHT/2 - abs(dy)) / (HUD.VERTICAL_BOX_HEIGHT/2.)) # Avoid putting tick label below bottom of box if dy > -HUD.VERTICAL_BOX_HEIGHT/2+20: label = Label(('%3d' % tickval).center(3), x=lx+HUD.VERTICAL_LABEL_OFFSET, y=HUD.H/2+dy, font_size=HUD.FONT_SIZE, color=(*HUD.FONT_COLOR, alpha), anchor_x='center', anchor_y='center') viewer.add_onetime(_DrawText(label)) # Add a title at the bottom HUD._add_label(viewer, Label(title, x=lx+HUD.VERTICAL_TITLE_X_OFFSET, y=(HUD.H/2-HUD.VERTICAL_BOX_HEIGHT/2 - HUD.VERTICAL_TITLE_Y_OFFSET), font_size=HUD.FONT_SIZE, color=(*HUD.FONT_COLOR, 255), anchor_x='center', anchor_y='center'))
def load_label(self): self._label = Label(self._text, font_size=33, font_name="Hydrophilia Iced", x=self._label_x, y=self._label_y, anchor_x="center", anchor_y="center")
def __init__(self, heading: str, buttons: List[BaseButton], x, y): self.heading = heading font_size = 50 self.heading_label = Label(heading, font_name='Courier New', font_size=font_size, x=x, y=y + int(font_size / 2)) self.buttons = buttons self.highlightables = list(buttons) self.x = x self.y = y
class UIHarvestChoose(Panel, InputHandler): def __init__(self, trans, *a, **k): self.trans = trans cards = trans.cards self.inputlet = None w = 20 + (91 + 10) * 4 + 20 h = 20 + 125 + 20 + 125 + 20 + 20 self.lbl = Label( text=u"等待其他玩家操作", x=w//2, y=300, font_size=12, color=(255, 255, 160, 255), shadow=(2, 0, 0, 0, 230), anchor_x='center', anchor_y='bottom' ) Panel.__init__(self, width=1, height=1, zindex=5, *a, **k) parent = self.parent self.x, self.y = (parent.width - w)//2, (parent.height - h)//2 + 20 self.width, self.height = w, h self.update() self.mapping = mapping = {} for i, c in enumerate(cards): y, x = divmod(i, 4) x, y = 20 + (91 + 10) * x, 20 + (125 + 20) * (1 - y) cs = CardSprite(c, parent=self, x=x, y=y) cs.associated_card = c mapping[id(c)] = cs @cs.event def on_mouse_dblclick(x, y, button, modifier, cs=cs): if cs.gray: return ilet = self.inputlet if not ilet: return ilet.set_card(cs.associated_card) ilet.done() def draw(self): Panel.draw(self) self.lbl.draw() def process_user_input_start(self, ilet): self.lbl.text = u'等待%s选择卡牌' % (ilet.actor.ui_meta.name) self.lbl.color = (255, 255, 160, 255) def process_user_input(self, ilet): assert ilet.actor is Game.getgame().me self.inputlet = ilet self.lbl.text = u'请你选择一张卡牌' self.lbl.color = (160, 251, 255, 255) def process_user_input_finish(self, ilet, rst): self.lbl.text = u'等待其他玩家操作' self.lbl.color = (255, 255, 160, 255) self.inputlet = None def on_harvest_choose(self, card): self.mapping[id(card)].gray = True
def created(self, data): self.savedPlayers = [0 for _ in xrange(4)] self.scoreCount = data.readShort(True) self.nameLength = data.readShort(True) self.flags = HIGHSCORE_FLAGS.copy() self.flags.setFlags(data.readShort(True)) if self.flags['HideOnStart']: self.parent.visible = False self.hideScores = self.flags['HideScores'] self.nameFirst = self.flags['NameFirst'] or self.hideScores self.font = LogFont(data, old = True) self.color = data.readColor() data.skipBytes(40) name_list = [] score_list = [] for _ in xrange(20): name_list.append(data.readString(41)) for _ in xrange(20): score_list.append(data.readInt()) self.originalScores = [(name_list[i], score_list[i]) for i in xrange(self.scoreCount)] self.scores = self.originalScores[:] self.width = data.readShort(True) self.height = data.readShort(True) self.name = data.readString(260) self.enable_mouse() self.pendingScores = [] self.set_file(self.name or 'Game.ini') if self.flags['CheckOnStart']: for index, item in enumerate(self.player.players.items): if item.score > self.scores[-1][1]: self.pendingScores.insert(0, (item.score, index + 1)) self.nameLabel = Label('Enter your name', color = (0, 0, 0, 255), bold = True, anchor_x = 'center', anchor_y = 'center', y = 25) self.currentName = Label('', color = (0, 0, 0, 255), anchor_x = 'center', anchor_y = 'center', width = BOX_WIDTH - 20) self.labels = labels = [] height = self.height / self.scoreCount y = 0 for name, score in self.scores: label1 = self.create_label(self.font, '', self.color, self.width, self.height) label2 = self.create_label(self.font, '', self.color, self.width, self.height) label2.set_style('align', 'right') for label in (label1, label2): label.y = y labels.append((label1, label2)) y -= height self.update_labels() self.updateEnabled = True self.player.window.push_handlers( on_text_motion = self.on_text_motion, on_text = self.on_text, on_key_press = self.on_key_press )
def calculate(self): if self.name is None: return from pyglet.text import Label label = Label(self.text, self.name, self.size, self.bold, self.italic, width = self.width) self.calculatedWidth = label.content_width self.calculatedHeight = label.content_height label.delete()
def __init__(self): window = system.get_window() self.title_label = Label('Headshot', font_name=press_start_2p, font_size=36) self.title_label.anchor_x = 'center' self.title_label.anchor_y = 'center' self.main_menu = MainMenu() self.resize() window.on_key_press = self.main_menu.on_key_press self.main_menu.focused = True
def build(self): if not self.hidden and self.window.debug: batch = self.fg_batch self.stat_labels_l = [] self.stat_labels_r = [] y = self.y yo = 0 x = self.x mainstat = self.owner.mainstat if mainstat == "str": c = lookup_color("darkred") elif mainstat == "agi": c = lookup_color("darkgreen") elif mainstat == "int": c = lookup_color("darkblue") else: c = lookup_color("yellow") label_l = Label( text="Main stat:", font_name=None, font_size=10, x=x, y=y-yo, anchor_x="left", anchor_y="top", color=lookup_color("black"), batch=batch ) label_r = Label( text=mainstat, font_name=None, font_size=10, x=x+self.width, y=y-yo, anchor_x="right", anchor_y="top", color=c, batch=batch ) self.stat_labels_l.append(label_l) self.stat_labels_l.append(label_r) yo += 16 for stat, value in self.owner.base_stats.items(): modvalue = self.owner.stats.get(stat) label_l = Label( text=str(stat), font_name=None, font_size=8, x=x, y=y-yo, anchor_x="left", anchor_y="top", color=lookup_color("black", opacity=255), batch=batch ) label_r = Label( text=str(modvalue), font_name=None, font_size=8, x=x+self.width, y=y-yo, anchor_x="right", anchor_y="top", color=lookup_color("darkblue", opacity=255), batch=batch ) label_r.identifier = str(stat) self.stat_labels_l.append(label_l) self.stat_labels_r.append(label_r) yo += 12 self.height = yo self.rectangle = create_rectangle( self.x, self.y, self.width, self.height, centered=False )
class MainWindow: def __init__(self, fullscreen): self.fullscreen = fullscreen self.config = Config() self.Instance = vlc.Instance() self.player = self.Instance.media_player_new() media = self.Instance.media_new(self.config.configs['playlist'][1]) self.player.set_media(media) #self.player = media.Player() #track = media.load(self.config.configs['playlist'][1]) #self.player.queue(track) self.texts = ['Movies', 'TV', 'Music', 'Options'] self.index = 0 self.maxIndex = 3 self.mainWindow = Window(fullscreen=self.fullscreen) self.label = Label(self.config.ui['greeting'], font_name='Monospace', font_size=24, x=self.mainWindow.width // 2, y=self.mainWindow.height // 2, anchor_x='center', anchor_y='center') @self.mainWindow.event def on_draw(): self.mainWindow.clear() self.label.draw() # if self.player.get_texture(): # self.player.get_texture().blit(0, 0) @self.mainWindow.event def on_key_press(symbol, modifiers): if symbol == key.UP: if self.index == self.maxIndex: self.index = 0 else: self.index += 1 elif symbol == key.DOWN: if self.index == 0: self.index = self.maxIndex else: self.index -= 1 elif symbol == key.SPACE: #self.player = vlc.MediaPlayer(self.config.configs['playlist'][1]) #self.player.play() self.player.set_xwindow(self.GetHandle()) self.player.play() elif symbol == key.RETURN: self.player.pause() self.label.text = self.texts[self.index] def Run(self): app.run()
class _OneTimeLabel: ''' https://stackoverflow.com/questions/56744840 ''' def __init__(self, viewer, text, **kwargs): self.label = Label(text, **kwargs) viewer.add_onetime(self) def render(self): self.label.draw()
def _create_score_label(self): self._score_label = Label('0', x=self._score_label_x_coordinate(), y=self._win.height, font_size=30, bold=True, batch=self._batch, anchor_x='center', anchor_y='top') self._score_label.set_style('color', self._text_color)
def display(self, label: Label, show: bool = True): """Display or hide a label. +label+ Label to be hidden or displayed. +show+ True to display, False to hide. """ if show: label.batch = self.batch else: label.batch = None
def __init__(self, model: ShipPartModel, mesh=None): self._mode = "keyboard" self.font_size = 60 half_font_size = int(self.font_size / 2) self.infobox = Label("", font_name='Courier New', font_size=self.font_size, y=-half_font_size) super().__init__(model, mesh=mesh) self.update()
class FloatingCombatText: def __init__( self, ui, text, x, y, duration=1., scale=1., second_scale=0.5, growth=0.2, velocity=75, color="darkred", batch=None ): self.start_scale = scale self.second_scale = second_scale self.growth = growth self.x, self.y = x, y self.ui = ui wx, wy = self.ui.window.get_windowpos(x, y) self.color = lookup_color(color) self.label = Label( text=str(text), font_name=None, font_size=12 * scale, x=wx, y=wy, anchor_x="center", anchor_y="center", color=self.color, batch=batch, ) self.velocity = velocity self.timer = duration self.duration = duration self.done = False def on_end(self): self.label.delete() self.done = True def update(self, dt): if self.timer <= 0: self.on_end() else: self.timer -= dt perc = self.timer / self.duration scale = ( self.second_scale + ( (self.start_scale - self.second_scale) * perc ) ) self.y += self.velocity * dt self.label.font_size = 9 * scale self.label.x, self.label.y = self.ui.window.get_windowpos( self.x, self.y, precise=True ) opacity = int(255 * perc) if opacity < 0: opacity = 0 self.color = self.color[0], self.color[1], self.color[2], opacity self.label.color = self.color
class Label(Control): def __init__(self, text=u'Label', font_size=30, color=(0,0,0,255), x=0, y=0, bold=False, italic=False, *a, **k): self.rawlabel = RawLabel( text=text, font_size=font_size, color=color,x=0,y=0, anchor_x='left', anchor_y='bottom', bold=bold, italic=italic ) w, h = self.rawlabel.content_width, self.rawlabel.content_height Control.__init__(self, x=x, y=y, width=w, height=h, *a, **k) def draw(self): self.rawlabel.draw()
def __init__(self, world, width, length, name, segments): # River self.world = world self.width = width self.name = name self.length = length self.segments = segments if (segments[0][0] > segments[-1][0]): self.segments.reverse() # Neighborhoods self.chood = None self.rhood = None # Label self.ltuple = None self.oldltuple = None self.candidates = None self.label = Label(name, font_name=FONTNAME, font_size=RIVER_LABEL_HEIGHT, italic=True, color=(76,76,128,255)) # Glyph data self.glyphs = fontload(FONTNAME, RIVER_LABEL_HEIGHT, italic=True).get_glyphs(self.name) self.label_hiline = map((lambda x: x.vertices[3]), self.glyphs) self.label_loline = map((lambda x: x.vertices[1]), self.glyphs) self.label_swathwidth = int(1.2 * self.label.content_width) self.label_ascent = max(self.label_hiline) self.label_idealdist = self.label_ascent/4.0 + self.width/2.0 # Visualization self.lines = [] for s in self.segments: self.lines.extend([s[0], s[1]]) # Debug self.debugpointsA = [] self.debugpointsB = [] self.debugpointsC = [] # Cache self.rlcf = None self.rlrf = None
def __init__(self, parent, x, y, width, height, sb_width, sb_height, style=0, background_image=None, scrollbar_image=None, caption=None, font_size=12, font_name=G.DEFAULT_FONT, batch=None, group=None, label_group=None, pos=0, on_pos_change=None, *args, **kwargs): super(ScrollbarWidget, self).__init__(parent, *args, **kwargs) parent.push_handlers(self) self.batch = pyglet.graphics.Batch() if not batch else batch self.group = group self.label_group = label_group self.x, self.y, self.width, self.height = x, y, width, height self.sb_width, self.sb_height = sb_width, sb_height self.style = style if self.style == 0: self.sb_width = self.width else: self.sb_height = self.height self.background = image_sprite(background_image, self.batch, self.group) self.background.scale = max(float(self.width) / float(background_image.width), float(self.height) / float(background_image.height)) self.scrollbar = image_sprite(scrollbar_image, self.batch, self.group) self.scrollbar.scale = max(float(self.sb_width) / float(scrollbar_image.width), float(self.sb_height) / float(scrollbar_image.height)) self.pos = pos self.on_pos_change = on_pos_change self.caption = caption self.label = Label(str(caption) + ":" + str(pos) + "%", font_name, 12, anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.batch, group=self.label_group) if caption else None self.move_to(x, y)
def add_to_batch(self, batch, groups): self.titleLabel = Label( 'Sinister Ducks', font_size=36, x=self.game.width / 2, y=self.game.height / 2 + 30, anchor_x='center', anchor_y='center', batch=batch, group=groups[self.render_layer] ) self.pressAnyKeyLabel = Label( 'Press any key', font_size=18, x=self.game.width / 2, y=self.game.height / 2 - 20, anchor_x='center', anchor_y='center', batch=batch, group=groups[self.render_layer] ) self.blink(None)
class HudTitle(GameItem): render_layer = 3 def __init__(self): GameItem.__init__(self) self.titleLabel = None self.pressAnyKeyLabel = None def add_to_batch(self, batch, groups): self.titleLabel = Label( 'Sinister Ducks', font_size=36, x=self.game.width / 2, y=self.game.height / 2 + 30, anchor_x='center', anchor_y='center', batch=batch, group=groups[self.render_layer] ) self.pressAnyKeyLabel = Label( 'Press any key', font_size=18, x=self.game.width / 2, y=self.game.height / 2 - 20, anchor_x='center', anchor_y='center', batch=batch, group=groups[self.render_layer] ) self.blink(None) def remove_from_batch(self, batch): self.titleLabel.delete() self.titleLabel = None self.pressAnyKeyLabel.delete() self.pressAnyKeyLabel = None clock.unschedule(self.blink) def blink(self, _): blink = self.pressAnyKeyLabel.color == colors[0] self.pressAnyKeyLabel.color = colors[blink] clock.schedule_once(self.blink, 0.4 + 0.2 * blink) def on_key_press(self, _, __): clock.schedule_once(lambda _: self.game.start(), 1) self.remove_from_game = True
class Button(pyglet.event.EventDispatcher, Rectangle): def __init__(self, parent, x, y, width, height, image=None, image_highlighted=None, caption=None, batch=None, group=None, label_group=None, font_name=G.DEFAULT_FONT): super(Button, self).__init__(x, y, width, height) parent.push_handlers(self) self.batch, self.group, self.label_group = batch, group, label_group self.sprite = image_sprite(image, self.batch, self.group) self.sprite_highlighted = hidden_image_sprite(image_highlighted, self.batch, self.group) self.highlighted = False self.label = Label(str(caption), font_name, 12, anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.batch, group=self.label_group) if caption else None self.position = x, y @property def position(self): return self.x, self.y @position.setter def position(self, position): self.x, self.y = position if hasattr(self, 'sprite') and self.sprite: self.sprite.x, self.sprite.y = position if hasattr(self, 'sprite_highlighted') and self.sprite_highlighted: self.sprite_highlighted.x, self.sprite_highlighted.y = position if hasattr(self, 'label') and self.label: self.label.x, self.label.y = self.center def draw(self): self.draw_sprite() self.draw_label() def draw_sprite(self): if self.sprite and not (self.sprite_highlighted and self.highlighted): self.sprite_highlighted.visible, self.sprite.visible = False, True self.sprite.draw() elif self.sprite_highlighted and self.highlighted: self.sprite_highlighted.visible, self.sprite.visible = True, False self.sprite_highlighted.draw() def draw_label(self): if self.label: self.label.draw() def on_mouse_click(self, x, y, button, modifiers): if self.hit_test(x, y): self.dispatch_event('on_click')
def display_turn_notice(self, current_turn): if hasattr(self, 'turn_notice'): self.turn_notice.delete() self.turn_notice = Label( "Player %s's Turn" % (current_turn + 1), font_name='Times New Roman', font_size=36, x= 500 + self.camera.offset_x, y= 560 + self.camera.offset_y) self.turn_notice.color = 255 - (100 * current_turn), 255 - (100 * ((current_turn + 1) % 2)), 255, 255
def drawLabel(text, pos=(0,0), **kwargs): kwargs.setdefault('font_size', 16) kwargs.setdefault('center', False) if kwargs.get('center'): kwargs.setdefault('anchor_x', 'center') kwargs.setdefault('anchor_y', 'center') else: kwargs.setdefault('anchor_x', 'left') kwargs.setdefault('anchor_y', 'bottom') del kwargs['center'] temp_label = Label(text, **kwargs) #temp_label.x, temp_label.y = pos glPushMatrix() #glTranslated(-pos[0]-8.5,-pos[1]-8,0) glScaled(0.02,0.02,0.02) temp_label.draw() glPopMatrix() return temp_label.content_width
def drawLabel(text, pos=(0,0),center=True,alpha = 75,scale=0.3,red=255,green=255,blue=255): _standard_label = Label(text='standard Label', font_size=200,bold=True, color=(red,green,blue,alpha)) _standard_label.anchor_x = 'left' _standard_label.anchor_y = 'bottom' _standard_label.x = 0 _standard_label.y = 0 _standard_label.text = text glPushMatrix() glTranslated(pos[0], pos[1], 0.0) glScaled(scale,scale,1) _standard_label.draw() glPopMatrix()
def drawLabel(text, pos=(0, 0), center=True, textcolor=(255, 255, 255, 75)): _standard_label = Label(text="standard Label", font_size=200, bold=True, color=textcolor) _standard_label.anchor_x = "center" _standard_label.anchor_y = "center" _standard_label.x = 0 _standard_label.y = 0 _standard_label.text = text glPushMatrix() glTranslated(pos[0], pos[1], 0.0) glScaled(0.3, 0.3, 1) _standard_label.draw() glPopMatrix()
def __init__(self, parent, x, y, width, height, image=None, image_highlighted=None, caption=None, batch=None, group=None, label_group=None, font_name=G.DEFAULT_FONT): super(Button, self).__init__(x, y, width, height) parent.push_handlers(self) self.batch, self.group, self.label_group = batch, group, label_group self.sprite = image_sprite(image, self.batch, self.group) self.sprite_highlighted = hidden_image_sprite(image_highlighted, self.batch, self.group) self.highlighted = False self.label = Label(str(caption), font_name, 12, anchor_x='center', anchor_y='center', color=(255, 255, 255, 255), batch=self.batch, group=self.label_group) if caption else None self.position = x, y
def drawLabel(text, pos=(0,0),center=True): _standard_label = Label(text='standard Label', font_size=200,bold=True, color=(255,255,255,75)) _standard_label.anchor_x = 'left' _standard_label.anchor_y = 'bottom' _standard_label.x = 0 _standard_label.y = 0 _standard_label.text = text glPushMatrix() glTranslated(pos[0], pos[1], 0.0) glScaled(0.3,0.3,1) _standard_label.draw() glPopMatrix()
def setup(self): self.group = pyglet.graphics.OrderedGroup(3) self.labels_group = pyglet.graphics.OrderedGroup(4) image = frame_image self.layout = VerticalLayout(0, 0) # Custom background self.background = None self.frame_rect = Rectangle(0, 0, self.controller.window.get_size()[0], image.height) self.frame = Rectangle(0, 0, self.controller.window.get_size()[0], image.height) width, height = self.controller.window.width, self.controller.window.height self.label = Label(G.APP_NAME, font_name='ChunkFive Roman', font_size=50, x=width//2, y=self.frame.y + self.frame.height, anchor_x='center', anchor_y='top', color=(255, 255, 255, 255), batch=self.batch, group=self.labels_group) self.label.width = self.label.content_width self.label.height = self.label.content_height self.layout.add(self.label) button = self.Button(caption=G._("Singleplayer"),on_click=self.controller.start_singleplayer_game) self.layout.add(button) self.buttons.append(button) button = self.Button(caption=G._("Multiplayer"),on_click=self.controller.multiplayer) self.layout.add(button) self.buttons.append(button) button = self.Button(caption=G._("Options..."),on_click=self.controller.game_options) self.layout.add(button) self.buttons.append(button) button = self.Button(caption=G._("Exit game"),on_click=self.controller.exit_game) self.layout.add(button) self.buttons.append(button) # Splash text self.splash_text = 'Hello!' now = datetime.datetime.now() if now.month == 1 and now.day == 1: self.splash_text = 'Happy new year!' self.splash_text_label = Label(self.splash_text, font_name='Arial', font_size=30, x=self.label.x, y=self.label.y, anchor_x='center', anchor_y='top', color=(255, 255, 0, 255), group=self.labels_group) self.on_resize(width, height) # Panorama self.panorama = [G.texture_pack_list.selected_texture_pack.load_texture(['title', 'bg', 'panorama' + str(x) + '.png']) for x in range(6)] self.panorama_timer = 0 pyglet.clock.schedule_interval(self.update_panorama_timer, .05) self.blur_texture = pyglet.image.Texture.create(256, 256) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
def __init__(self, pmap): # World self.bounds = pmap['bounds'] # Area self.area = Area(self, pmap['areaname'], pmap['bounds']) # Cities self.citycount = pmap['citycount'] self.cities = [] for i in range(self.citycount): rawcity = pmap['cities'][i] c = City(self, rawcity['size'], rawcity['name'], rawcity['pos']) self.cities.append(c) # Rivers self.rivercount = pmap['rivercount'] self.rivers = [] for i in range(self.rivercount): rawriver = pmap['rivers'][i] r = River(self, rawriver['width'], rawriver['length'], rawriver['name'], rawriver['segs']) self.rivers.append(r) # ObjectGrid self.og = ObjectGrid(self) # UI self.ui_current = Label("NULL", font_name=FONTNAME, font_size=UI_LABEL_HEIGHT, color=(150,150,150,255), x=self.bounds[2] - 82, y=5) self.ui_best = Label("NULL", font_name=FONTNAME, font_size=UI_LABEL_HEIGHT, color=(150,150,150,255), x=self.bounds[2] - 82, y=7 + UI_LABEL_HEIGHT) # Execution self.finished = False self.pause = False self.annealing = Annealing(self) self.current_object = None # Visuals self.showgrid = False self.showarea = True self.showcities = True self.showcitylabels = True self.showrivers = True self.showriverlabels = True self.showdebug = True self.showvisuals = True self.showUI = True
def __init__(self, *args, **kwargs): super(QuitScreen, self).__init__(*args, **kwargs) self.buttons['quit'] = btn([300, 300], 'yes') self.buttons['dont_quit'] = btn([680, 300], 'no') self.text = 'do you really want to quit?' self.Label = Label(self.text, font_name=font, font_size=36, bold=False, x=640, y=500, anchor_x='center', anchor_y='center') self.Box = Box([340, 200], [600, 400], 2)
class LoadScreen(MenuClass): """docstring for LoadScreen""" def __init__(self, *args, **kwargs): super(LoadScreen, self).__init__(*args, **kwargs) self.label = Label('connecting to server', font_name=font, font_size=36, bold=False, x=200, y=550, anchor_x='left', anchor_y='baseline') def draw(self): self.label.draw() def on_connect(self): self.send_message('menu_transition_-') def add_update(self, dt): try: if self.keys[key.ESCAPE] and not self.keys_old[key.ESCAPE]: self.send_message('to_main') except: pass
class FridgeLetterAtomic(MTDragable): def __init__(self, **kwargs): kwargs.setdefault("letter", "A") kwargs.setdefault("color", (1, 0, 0, 1)) super(FridgeLetterAtomic, self).__init__(**kwargs) self.letter = Label( font_name="AlphaFridgeMagnets.ttf", font_size=48, bold=True, anchor_x="left", anchor_y="bottom", multiline=False, halign="top", color=map(lambda x: int(x * 255), kwargs.get("color")), text=kwargs.get("letter"), ) self.size = self.letter.content_width, self.letter.content_height def draw(self): self.letter.x, self.letter.y = self.pos self.letter.draw()
def __init__(self, client, gameblock): self.gameblock = gameblock self.client = client # You know when you right click on a block how it places a flag? That's # what this is. We have it here and not in the GameBlock because it # only effects the client (weather or not it can be clicked/discovered). self.flagged = False # Here are all the sprites we use for our block. This COULD be optimized # to run faster... but quite frankly, we don't need to (and it's more # complicated). If we had 5000 blocks on the screen we would probably # consider it. self.sprite = rabbyt.Sprite("data/block_hidden.png") self.sprite.x = self.gameblock.x*20 self.sprite.y = self.gameblock.y*20 # I'm not going to go into detail about rabbyt sprites (you can read # the documentation for that) but just so you aren't clueless is tells # the sprite that the anchor point for x and y is on the bottom left # of the sprite and not the center (default). self.sprite.shape.left = 0 self.sprite.shape.bottom = 0 self.sprite2 = rabbyt.Sprite("data/block_discovered.png") self.sprite2.xy = self.sprite.xy self.sprite2.shape = self.sprite.shape if self.gameblock.is_mine: self.minesprite = rabbyt.Sprite("data/mine.png") self.minesprite.xy = self.sprite.xy self.minesprite.shape = self.sprite.shape self.flag_sprite = rabbyt.Sprite("data/flag.png") self.flag_sprite.xy = self.sprite.xy self.flag_sprite.shape = self.sprite.shape # Here we create the number that will be shown on the block when it is # descovered (if it is supposed to have one). # NOTE: Drawing pyglet Text is really slow - it would be better to # render the text onto a rabbyt sprite (which would go really fast) but # we'll just do this for now as that would make this tutorial more # complicated than it needs to be. if not gameblock.is_mine and gameblock.number_adjacent_mines > 0: self.text = Label(str(self.gameblock.number_adjacent_mines), x = self.sprite.x + 5, y = self.sprite.y + 5, color = COLORS[self.gameblock.number_adjacent_mines])
def __init__(self, **kwargs): # rip out the game settings we want players = kwargs.pop('players') gamestate = kwargs.pop('gamestate') self.game = PlanetWars(gamestate) for p in players: self.game.add_player(p) self.max_tick = kwargs.pop('max_game_length') # set and use pyglet window settings kwargs.update({ 'width': 500, 'height': 500, 'vsync': True, 'resizable': False, }) super(PlanetWarsWindow, self).__init__(**kwargs) # create a pyglet window and set glOptions glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glClearColor(0., 0., 0., 1.0) # Grey # current "pen" colour of lines self.pen_color = (1, 0, 0, 1.) self.stroke = 1.0 # - thickness default self.qobj = gluNewQuadric() # gluQuadricDrawStyle(self.qobj, GLU_FILL) #GLU_SILHOUETTE) # prep the fps display and some labels self.fps_display = clock.ClockDisplay() clWhite = (255, 255, 255, 255) self.step_label = Label('STEP', x=5, y=self.height - 20, color=clWhite) self.fps = 0 self.set_fps(20) self.paused = True self.view_id = 0 self.label_type = 'num_ships' # create adaptor to help with drawing self.adaptor = PlanetWarsScreenAdapter(self.game, self.circle) # prep the game (space!) self.reset_space() # add extra event handlers we need self.add_handlers()
def __init__(self, world, name, bounds): self.world = world self.name = name self.lpos = None self.oldlpos = None self.label = Label(name, font_name=FONTNAME, font_size=AREA_LABEL_HEIGHT, italic=True, color=(76,76,128,255), x=0, y=0) self.center = Vec2d((bounds[0] + bounds[2])/2, (bounds[1] + bounds[3])/2) self.cbounds = (bounds[0] + self.label.content_width, bounds[1] + AREA_LABEL_HEIGHT, bounds[2] - self.label.content_width, bounds[3] - AREA_LABEL_HEIGHT) self.candidates = None self.neighbors = None # Cache self.alcf = None self.alrf = None self.ap = None