예제 #1
0
    def __init__(self):
        super().__init__()

        self.current_level = 0
        self.seed = random.randint(1000000000000000,9000000000000000)
        print('using seed', str(self.seed))
        self.current_room_x = 2
        self.current_room_y = 2
        self.current_room = None
        self.dungeon = dict()
        self.dungeon[self.current_level] = DungeonLevel(self.current_level)
        self.player = Player()
        # setup player according to chosen starting weapon and stats

        # find the current room the player is in
        for room in self.dungeon[self.current_level].rooms:
            if room.x == self.current_room_x:
                if room.y == self.current_room_y:
                    self.current_room = room

        # insert our custom Background into an OrderedGroup
        self.insert(CustomBackground(), 0)

        # init and fill mapgrids.
        self.bg_map_grid = glooey.Grid(0, 0, 0, 0)
        for tile in self.current_room.tiles:
            # draw bg of current room
            self.bg_map_grid[tile.x, tile.y] = glooey.Image(tile.bg)

        self.fg_map_grid = glooey.Grid(0, 0, 0, 0)
        for tile in self.current_room.tiles:
            # draw fg of current room
            self.fg_map_grid[tile.x, tile.y] = glooey.Image(tile.fg)

        # insert mapgrids into our ordered groups.
        self.insert(self.bg_map_grid, 1)
        self.insert(self.fg_map_grid, 2)

        # draw monsters and player on a grid
        self.creature_map_grid = glooey.Grid(0, 0, 0, 0)
        for creature in self.current_room.characters:
            self.creature_map_grid[creature.x, creature.y] = creature.image
        
        self.insert(self.creature_map_grid, 3)

        # draw player stats
        self.stats_box = StatsBox()
        self.insert(self.stats_box, 4)
예제 #2
0
def main():
    np.random.seed(0)

    window = pyglet.window.Window(width=1295, height=975)
    gui = glooey.Gui(window)

    grid = glooey.Grid(2, 2)
    grid.set_padding(5)

    scene = create_scene1()
    widget = SceneWidget(scene)
    grid[0, 0] = widget
    scene = create_scene2()
    widget = SceneWidget(scene)
    grid[0, 1] = widget

    image = pyglet.image.load('images/beach.jpg')
    widget = glooey.Image(image)
    grid[1, 0] = widget

    hbox = glooey.HBox()
    widget = glooey.Button(text='yes')
    widget.push_handlers(on_click=lambda w: print(f'[{w.text}] clicked!'))
    hbox.add(widget)
    widget = glooey.Button(text='no')
    widget.push_handlers(on_click=lambda w: print(f'[{w.text}] clicked!'))
    hbox.add(widget)
    grid[1, 1] = hbox

    gui.add(grid)

    pyglet.app.run()
예제 #3
0
    def __init__(self, skill1, skill2):
        super().__init__()
        self.grid = glooey.Grid(0,0,0,0)
        self.grid[0,0] = skill1.image
        self.grid[0,1] = skill2.image

        self.add(self.grid)
예제 #4
0
    def __init__(self, localmap, character_name):
        super().__init__()
        self.localmap = self.convert_chunks_to_localmap(localmap)
        self.character_name = character_name
        self.chunk_size = (13, 13)  # the only tuple you'll see I swear.

        # chunk_size + tilemap size
        self.map_grid = glooey.Grid(self.chunk_size[0], self.chunk_size[1], 32,
                                    32)
        self.map_grid.set_left_padding(16)  # for the border.
        self.map_grid.set_top_padding(16)

        self.TileManager = TileManager()
        self.ItemManager = ItemManager()
        self.RecipeManager = RecipeManager()

        # glooey uses x,y for grids from the top left.
        for i in range(self.chunk_size[0]):
            for j in range(self.chunk_size[1]):
                # init the MapTile(s)
                self.map_grid.add(i, j, MapTile(None))

        # insert the background into our ordered groups.
        self.insert(CustomBackground(), 0)

        # insert the map_grid into our ordered group.
        self.insert(self.map_grid, 1)
        # self.insert(self.weather_board, 2)
        self.update_map_for_position(
            self.find_character_in_localmap().position)
예제 #5
0
 def __init__(self):
     super().__init__()
     self.grid = glooey.Grid(0,0,0,0)
     self.grid[0,0] = glooey.dialogs.Label('hp')
     self.grid[1,0] = glooey.dialogs.Label('str')
     self.grid[2,0] = glooey.dialogs.Label('spd')
     self.grid[3,0] = glooey.dialogs.Label('int')
     self.grid[4,0] = glooey.dialogs.Label('res')
     self.grid[5,0] = glooey.dialogs.Label('tgt')
     self.add(self.grid)
예제 #6
0
    def __init__(self):
        super().__init__()

        self.username = InputBox()
        self.password = InputBox()

        self.password.push_handlers(
            on_unfocus=lambda w: print(f"password: ***************"))

        self.serverIP = InputBox()
        self.serverPort = InputBox()
        self.serverIP.push_handlers(
            on_unfocus=lambda w: print(f"serverIP: '{w.text}'"))
        self.serverPort.push_handlers(
            on_unfocus=lambda w: print(f"serverPort: '{w.text}'"))

        self.grid = glooey.Grid(0, 0, 0, 0)
        self.padding = 16

        self.titleLabel = glooey.Label("Cataclysm: Looming Darkness")

        self.grid[0, 1] = self.titleLabel

        self.grid[1, 0] = glooey.Label("Username:"******"password:"******"Server IP:")
        self.grid[4, 1] = self.serverIP
        self.grid[5, 0] = glooey.Label("Server Port:")
        self.grid[5, 1] = self.serverPort

        with open("client.json") as f:
            client_data = json.load(f)

        self.username.text = client_data["username"]
        self.password.text = client_data["password"]
        self.serverList = client_data["serverList"]

        connectButton = ConnectButton("Connect")
        self.grid[6, 1] = connectButton

        serverListScrollBox = CustomScrollBox()
        serverListScrollBox.size_hint = 100, 100
        vbox_for_serverlist = glooey.VBox(0)
        for server in self.serverList:
            _button = ServerListButton(server)
            # sets the active server to the one you press.
            _button.push_handlers(on_click=self.set_host_and_port_InputBoxes)
            vbox_for_serverlist.add(_button)
        serverListScrollBox.add(vbox_for_serverlist)
        self.grid[6, 0] = serverListScrollBox

        self.add(self.grid)
예제 #7
0
    def __init__(self, name):
        MastermindClientTCP.__init__(self)
        pyglet.resource.path = [
            'tiles', 'tiles/background', 'tiles/monsters', 'tiles/terrain'
        ]
        pyglet.resource.reindex()
        ######################################################################################
        ## when we get an update from the server we update these values from the parsed chunk.
        self.name = name
        self.chunk_size = (51, 27)
        self.player = None
        self.chunk = None
        self.map = None
        self.creatures = None
        self.objects = None
        self.map_grid = glooey.Grid(self.chunk_size[1], self.chunk_size[0], 16,
                                    16)  # chunk_size + tilemap size
        self.map_grid.set_left_padding(16)  # for the border.
        self.map_grid.set_top_padding(16)

        for i in range(self.chunk_size[1]
                       ):  # glooey uses y,x for grids from the top left.
            for j in range(self.chunk_size[0]):
                self.map_grid.add(
                    i, j,
                    glooey.images.Image(pyglet.resource.texture('t_grass.png'))
                )  # before we get an update we need to init the map with grass.

        ######################################################################################

        window = pyglet.window.Window(854, 480)
        gui = glooey.Gui(window)

        bg = glooey.Background()
        bg.set_appearance(
            center=pyglet.resource.texture('center.png'),
            top=pyglet.resource.texture('top.png'),
            bottom=pyglet.resource.texture('bottom.png'),
            left=pyglet.resource.texture('left.png'),
            right=pyglet.resource.texture('right.png'),
            top_left=pyglet.resource.texture('top_left.png'),
            top_right=pyglet.resource.texture('top_right.png'),
            bottom_left=pyglet.resource.texture('bottom_left.png'),
            bottom_right=pyglet.resource.texture('bottom_right.png'))
        gui.add(bg)
        gui.add(self.map_grid)

        @window.event
        def on_key_press(symbol, modifiers):
            if symbol == KEY.RETURN:
                print('return')
            if symbol == KEY.W:
                command = Command(args.name, 'move', ['north'])
                client.send(command)
예제 #8
0
    def __init__(self, list_of_characters):
        super().__init__()

        self.grid = glooey.Grid(0, 0, 0, 0)
        self.grid.padding = 16

        self.titleLabel = glooey.Label("Please Select or Create a Character.")

        self.grid[0, 1] = self.titleLabel

        self.add(self.grid)

        self.fill_character_list(list_of_characters)
예제 #9
0
    def __init__(self, position, name=None):
        super().__init__()

        self.x = position[0]
        self.y = position[1]
        if name != None:
            self.name = checkNameAvailability(name)
            self.name_label = Text(self.name)
        else:
            self.name = checkNameAvailability("Names")
            self.name_label = Text(self.name)

        self.add_back(Slot())

        self.grid = glooey.Grid(5, 5)
        self.grid.set_cell_alignment('center')
        self.board = glooey.Board()
        self.remove_button = DelButton(position)
        self.options_button = OptionsButton(position)

        self.grid.set_row_height(1, 20)
        self.grid.set_row_height(2, 5)
        self.grid.set_row_height(3, 20)

        self.grid.set_col_width(1, 200)
        self.grid.set_col_width(3, 200)

        self.grid[1, 1] = self.player_one_input = TextInput()
        self.grid[1, 3] = self.player_two_input = TextInput()
        self.grid[3, 1] = Text("Player 1 Name")
        self.grid[3, 2] = glooey.Image(
            pyglet.resource.texture(
                "Widgets/Textures/SelectWidgetDialog/PlayerName.png"))
        self.grid[3, 3] = Text("Player 2 Name")

        self.board.add(self.remove_button, bottom=50, left_percent=.8)
        self.board.add(self.options_button, bottom=50, left_percent=.7)
        self.board.add(self.name_label, bottom_percent=.9, center_x_percent=.5)

        self.add_front(self.grid)
        self.add_front(self.board)
예제 #10
0
def displayGUI():
    # Open a Window
    window = pyglet.window.Window(width=800, height=480)  # fullscreen=True
    gui = glooey.Gui(window)

    class StatusLabel(glooey.Label):
        custom_font_name = "Calibri"
        custom_font_size = 12
        custom_color = "0080ff"

    class ArmButton(glooey.Button):
        if alarm.system_armed:

            class Base(glooey.Image):
                custom_image = pyglet.resource.image('Button2.png')

        elif not alarm.system_armed:

            class Base(glooey.Image):
                custom_image = pyglet.resource.image('Button3.png')

    class DoorStatusLabel(glooey.Label):
        custom_font_name = "Calibri"
        custom_font_size = 9
        custom_color = "0080ff"

    class TemperatureData(glooey.Label):
        custom_font_name = "Calibri"
        custom_font_size = 9
        custom_color = "0080ff"

    class Clock(glooey.Label):
        custom_font_name = "Calibri"
        custom_font_size = 9
        custom_color = "0080ff"

    SensorStatusVbox = glooey.VBox()

    self.grid = glooey.Grid()
    gui.add(self.grid)
예제 #11
0
def control_panel():

    WIDTH = 800
    HEIGHT = 1000

    window = pyglet.window.Window(WIDTH, HEIGHT)
    gui = glooey.Gui(window)
    grid = glooey.Grid(2, 2)

    G_WIDTH = 1280 / 4
    G_HEIGHT = 780 / 4
    window2 = pyglet.window.Window(G_WIDTH + 100, G_HEIGHT)
    gui2 = glooey.Gui(window2)

    def make_initial_circles():
        c0 = Circle(0, main=True)
        c1 = Circle(1)
        c2 = Circle(2)
        c3 = Circle(3)
        c4 = Circle(4)
        circles = [c0, c1, c2, c3, c4]
        for circle in circles:
            gui2.add(circle)
        c0.reposition(G_WIDTH, G_HEIGHT / 2)
        c1.reposition(G_WIDTH / 4, G_HEIGHT / 4)
        c2.reposition(G_WIDTH / 4 + G_WIDTH / 2, G_HEIGHT / 4)
        c3.reposition(G_WIDTH / 4, G_HEIGHT / 4 + G_HEIGHT / 2)
        c4.reposition(G_WIDTH / 4 + G_WIDTH / 2, G_HEIGHT / 4 + G_HEIGHT / 2)
        return circles

    circles = make_initial_circles()
    change_performer = TogglePerformer("Change Selected to Performer",
                                       circles=circles)
    save_locations = SaveLocations("change location", circles=circles)
    grid.add(0, 0, change_performer)
    grid.add(0, 1, save_locations)
    gui.add(grid)
    return (window, window2, gui)
예제 #12
0
    def __init__(self):
        self.window = pyglet.window.Window()
        self.window.set_visible(True)
        self.window.set_size(*world.World.field_size)
        self.batch = pyglet.graphics.Batch()

        self.bg_color = glooey.drawing.white

        # Load all the sprite images from resource files.

        self.images = {}
        for code in world.World.codes:
            for suite in world.World.suites:
                key = world.get_card_key(suite, code)
                filename = suite[0] + code + '.png'
                self.images[key] = pyglet.resource.image(filename)

        self.border_images = {}
        for border_name in "border", "border-over", "border-down", "border-selected":
            filename = border_name + '.png'
            self.border_images[border_name] = pyglet.resource.image(filename)

        # Center all the images, which we will want to rotate around it's
        # leftmost edge.

        for image in self.images.values():
            image.anchor_x = image.width / 2
            image.anchor_y = image.height / 2

        # Create the viewing grid
        rows = world.World.rows
        cols = world.World.cols
        padding = world.World.padding
        self.root = glooey.Gui(self.window, batch=self.batch)
        self.grid = glooey.Grid(rows, cols, padding=padding)
        for row, col in self.grid.yield_cells():
            self.grid[row, col] = CardButton(self)
        self.root.add(self.grid)
예제 #13
0
    def __init__(self):
        super().__init__()

        self.chunk_size = (13, 13)  # the only tuple you'll see I swear.

        self.map_grid = glooey.Grid(self.chunk_size[0], self.chunk_size[1], 32,
                                    32)  # chunk_size + tilemap size
        self.map_grid.set_left_padding(32)  # for the border.
        self.map_grid.set_top_padding(32)

        for i in range(self.chunk_size[0]
                       ):  # glooey uses x,y for grids from the top left.
            for j in range(self.chunk_size[1]):
                self.map_grid.add(
                    i, j,
                    glooey.images.Image(pyglet.resource.texture("t_grass.png"))
                )  # before we get an update we need to init the map with grass.

        # insert the background into our ordered groups.
        self.insert(CustomBackground(), 0)

        # insert the map_grid into our ordered group.
        self.insert(self.map_grid, 1)
예제 #14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--host")
    parser.add_argument("--port", type=int)
    args = parser.parse_args()
    zmq_client = HoldingsClient(host=args.host, port=args.port)

    window = HoldingsManagerWindow()
    gui = glooey.Gui(window)
    grid = glooey.Grid()
    grid.padding = 10

    # First create the forms where the user enters the inputs...
    form_dep_amt = HMForm()
    form_buy_qty = HMForm()
    form_buy_price = HMForm()
    form_sell_qty = HMForm()
    form_sell_price = HMForm()
    # then create a "tab cycle", i.e. a list of these widgets in the tab order
    # we want...
    tab_cycle = [form_dep_amt.get_label(),
                 form_buy_qty.get_label(), form_buy_price.get_label(),
                 form_sell_qty.get_label(), form_sell_price.get_label()]
    # then set this tab cycle as an attribute of the Labels in these forms...
    form_dep_amt.get_label().tab_cycle = tab_cycle
    form_buy_qty.get_label().tab_cycle = tab_cycle
    form_buy_price.get_label().tab_cycle = tab_cycle
    form_sell_qty.get_label().tab_cycle = tab_cycle
    form_sell_price.get_label().tab_cycle = tab_cycle
    # then create the non-editable labels...
    shares = (zmq_client.send_command("get_share_balance")).replace("[OK]","")
    cash = (zmq_client.send_command("get_cash_balance")).replace("[OK]","")
    share_balance = HMHighLabel(shares)
    cash_balance = HMHighLabel(cash)
    # ...then create the buttons which send the user's inputs to the server.
    btn_buy = HMActionButton('Buy Shares', zmq_client, server_cmd='buy',
                             widgets={'root_gui':      gui,
                                      'qty_form':      form_buy_qty,
                                      'price_form':    form_buy_price,
                                      'share_blc_lbl': share_balance,
                                      'cash_blc_lbl':  cash_balance})
    btn_sell = HMActionButton('Sell Shares', zmq_client, server_cmd='sell',
                              widgets={'root_gui':      gui,
                                       'qty_form':      form_sell_qty,
                                       'price_form':    form_sell_price,
                                       'share_blc_lbl': share_balance,
                                       'cash_blc_lbl':  cash_balance})
    btn_dep = HMActionButton('Deposit Cash', zmq_client,
                             server_cmd='deposit_cash',
                             widgets={'root_gui':      gui,
                                      'qty_form':      form_dep_amt,
                                      'price_form':    None,
                                      'share_blc_lbl': None,
                                      'cash_blc_lbl':  cash_balance})
    btn_shut_down_svr = HMShutdownButton('Close Server & Quit', zmq_client)

    row_num = 0
    grid.add(row_num, 1, HMLowLabel('Shares'))
    grid.add(row_num, 2, HMLowLabel('Cash'))
    row_num += 1
    grid.add(row_num, 0, HMHighLabel('Balances:'))
    grid.add(row_num, 1, share_balance)
    grid.add(row_num, 2, cash_balance)
    row_num += 1
    grid.add(row_num, 1, HMLowLabel('Amount'))
    row_num += 1
    grid.add(row_num, 0, btn_dep)
    grid.add(row_num, 1, form_dep_amt)
    row_num += 1
    grid.add(row_num, 1, HMLowLabel('Quantity'))
    grid.add(row_num, 2, HMLowLabel('Price per Share'))
    row_num += 1
    grid.add(row_num, 0, btn_buy)
    grid.add(row_num, 1, form_buy_qty)
    grid.add(row_num, 2, form_buy_price)
    row_num += 1
    grid.add(row_num, 1, HMLowLabel('Quantity'))
    grid.add(row_num, 2, HMLowLabel('Price per Share'))
    row_num += 1
    grid.add(row_num, 0, btn_sell)
    grid.add(row_num, 1, form_sell_qty)
    grid.add(row_num, 2, form_sell_price)
    row_num += 2
    grid.add(row_num, 1, btn_shut_down_svr)

    gui.add(grid)

    # Handle the possibility we are connecting to a server with an existing
    # cash or share balance.
    # - GET THE CURRENT SHARE BALANCE, AND DISPLAY IT IN THE GUI
    # - GET THE CURRENT CASH BALANCE, AND DISPLAY IT IN THE GUI
    # <YOUR CODE HERE>
    # Placing the initial focus on the deposit amount form seems to cause
    # intermittent stability problems on startup, so comment this out:
    # form_dep_amt.focus()

    # Last but not least, enter the main loop!
    pyglet.app.run()
예제 #15
0
def display_scenes(data, height=480, width=640, tile=None, caption=None):
    import glooey

    scenes = None
    scenes_group = None
    scenes_ggroup = None
    if isinstance(data, types.GeneratorType):
        next_data = next(data)
        if isinstance(next_data, types.GeneratorType):
            scenes = next(next_data)
            scenes_group = next_data
            scenes_ggroup = data
        else:
            scenes = next_data
            scenes_group = data
    else:
        scenes = data

    if tile is None:
        nrow, ncol = _get_tile_shape(len(scenes), hw_ratio=height / width)
    else:
        nrow, ncol = tile

    configs = [
        pyglet.gl.Config(sample_buffers=1,
                         samples=4,
                         depth_size=24,
                         double_buffer=True),
        pyglet.gl.Config(double_buffer=True),
    ]
    for config in configs:
        try:
            window = pyglet.window.Window(
                height=height * nrow,
                width=width * ncol,
                caption=caption,
                config=config,
            )
            break
        except pyglet.window.NoSuchConfigException:
            pass
    window.rotate = 0

    if scenes_group:
        window.play = False
        window.next = False
    window.scenes_group = scenes_group
    window.scenes_ggroup = scenes_ggroup

    @window.event
    def on_key_press(symbol, modifiers):
        if modifiers == 0:
            if symbol == pyglet.window.key.Q:
                window.on_close()
            elif window.scenes_group and symbol == pyglet.window.key.S:
                window.play = not window.play
            elif symbol == pyglet.window.key.Z:
                for name in scenes:
                    if isinstance(widgets[name], trimesh.viewer.SceneWidget):
                        widgets[name].reset_view()
        if symbol == pyglet.window.key.N:
            if modifiers == 0:
                window.next = True
            elif window.scenes_ggroup and \
                    modifiers == pyglet.window.key.MOD_SHIFT:
                try:
                    window.scenes_group = next(window.scenes_ggroup)
                    window.next = True
                except StopIteration:
                    return
        if symbol == pyglet.window.key.R:
            # rotate camera
            window.rotate = not window.rotate  # 0/1
            if modifiers == pyglet.window.key.MOD_SHIFT:
                window.rotate *= -1

    def callback(dt):
        if window.rotate:
            for widget in widgets.values():
                if isinstance(widget, trimesh.viewer.SceneWidget):
                    scene = widget.scene
                    camera = scene.camera
                    axis = tf.transform_points([[0, 1, 0]],
                                               camera.transform,
                                               translate=False)[0]
                    camera.transform = tf.rotation_matrix(
                        np.deg2rad(window.rotate),
                        axis,
                        point=scene.centroid,
                    ) @ camera.transform
                    widget.view['ball']._n_pose = camera.transform
            return

        if window.scenes_group and (window.next or window.play):
            try:
                scenes = next(window.scenes_group)
                for key, widget in widgets.items():
                    if isinstance(widget, trimesh.viewer.SceneWidget):
                        widget.scene.geometry.update(scenes[key].geometry)
                        widget.scene.graph.load(
                            scenes[key].graph.to_edgelist())
                        widget._draw()
                    elif isinstance(widget, glooey.Image):
                        widget.set_image(numpy_to_image(scenes[key]))
            except StopIteration:
                window.play = False
            window.next = False

    gui = glooey.Gui(window)
    grid = glooey.Grid()
    grid.set_padding(5)

    widgets = {}
    trackball = None
    for i, (name, scene) in enumerate(scenes.items()):
        vbox = glooey.VBox()
        vbox.add(glooey.Label(text=name, color=(255, ) * 3), size=0)
        if isinstance(scene, trimesh.Scene):
            widgets[name] = trimesh.viewer.SceneWidget(scene)
            if trackball is None:
                trackball = widgets[name].view['ball']
            else:
                widgets[name].view['ball'] = trackball
        elif isinstance(scene, np.ndarray):
            widgets[name] = glooey.Image(numpy_to_image(scene),
                                         responsive=True)
        else:
            raise TypeError(f'unsupported type of scene: {scene}')
        vbox.add(widgets[name])
        grid[i // ncol, i % ncol] = vbox

    gui.add(grid)

    pyglet.clock.schedule_interval(callback, 1 / 30)
    pyglet.app.run()
    pyglet.clock.unschedule(callback)
예제 #16
0
 def __init__(self, interface):
     super().__init__()
     self.interface = interface
     self.vbox = glooey.Grid()
     self._attach_child(self.vbox)
예제 #17
0
frame = glooey.Frame()
frame.decoration.outline = 'green'

pane = glooey.ScrollPane()
pane.size_hint = 300, 300
pane.horz_scrolling = True
pane.vert_scrolling = True

# Test widgets that are both bigger and smaller than the pane: See #32.  Note
# however that the pane is really only meant to be used with widgets larger
# than itself.  When scrolling and jumping the smaller widget, the widget seems
# to move in the wrong direction, but this is how the *visible part* of the
# widget *would* move correctly if the widget was larger than the pane.

big_content = glooey.Grid(2, 2)  # 450×450
big_content.padding = 50
for i in range(2):
    for j in range(2):
        big_content.add(i, j, glooey.EventLogger(150, 150, 'orange'))

small_content = glooey.Grid(2, 2)  # 90x90
small_content.padding = 10
for i in range(2):
    for j in range(2):
        small_content.add(i, j, glooey.EventLogger(30, 30, 'purple'))

frame.add(pane)
gui.add(frame)

예제 #18
0
    def __init__(self):
        super().__init__()
        self.grid = glooey.Grid(0, 0, 0, 0)
        self.grid.cell_alignment = 'right'
        # create selected tile window
        # - bg image, fg image
        # - creature - None or One
        # - items - empty list or list with items.
        # - lumens - integer of brightness 0-15000 (15,000 is full daylight)
        # - exit - None or Exit()
        # - flags - dict of flag:value pairs.
        bg_label = MapEditorLabel('Tile Background')
        self.grid[0, 0] = bg_label

        self.bg_button = MapEditorButton('',
                                         pyglet.resource.image('blank.png'))
        self.grid[0, 1] = self.bg_button

        fg_label = MapEditorLabel('Tile Foreground')
        self.grid[1, 0] = fg_label

        self.fg_button = MapEditorButton('',
                                         pyglet.resource.image('blank.png'))
        self.grid[1, 1] = self.fg_button

        creature_label = MapEditorLabel('Creature')
        self.grid[2, 0] = creature_label

        self.creature_button = CreatureButton(
            '', pyglet.resource.image('blank.png'))
        self.grid[2, 1] = self.creature_button

        lumens_label = MapEditorLabel('Lumens')
        self.grid[3, 0] = lumens_label

        self.lumens_button = LumensButton('',
                                          pyglet.resource.image('blank.png'))
        self.grid[3, 1] = self.lumens_button

        exit_label = MapEditorLabel('Exit')
        self.grid[4, 0] = exit_label

        self.exit_button = MapEditorButton('',
                                           pyglet.resource.image('blank.png'))
        self.grid[4, 1] = self.exit_button

        items_label = MapEditorLabel('Items')
        self.grid[5, 0] = items_label

        flags_label = MapEditorLabel('Flags')
        self.grid[5, 1] = flags_label

        self.items_list = CustomScrollBox()
        _button = ScrollBoxListButton('Add')
        self.items_list.add(_button)
        self.grid[6, 0] = self.items_list

        self.flags_list = CustomScrollBox()
        _button = ScrollBoxListButton('Add')
        self.flags_list.add(_button)
        # add a button to add a item to this list.
        self.grid[6, 1] = self.flags_list

        self.add(self.grid)
예제 #19
0
#!/usr/bin/env python3

import glooey
import pyglet

window = pyglet.window.Window()
gui = glooey.Gui(window)

grid = glooey.Grid(2, 2)
grid.padding = 10

grid.add(0, 0, glooey.Placeholder())
grid.add(0, 1, glooey.Placeholder())
grid.add(1, 0, glooey.Placeholder())
grid.add(1, 1, glooey.Placeholder())

gui.add(grid)

pyglet.app.run()
예제 #20
0
#!/usr/bin/env python3

import pyglet
import glooey
import run_demos

window = pyglet.window.Window()
gui = glooey.Gui(window)
grid = glooey.Grid()
widgets = { #
        (0,0): glooey.EventLogger(50, 50),
        (0,1): glooey.EventLogger(50, 50),
        (1,0): glooey.EventLogger(50, 50),
        (1,1): glooey.EventLogger(50, 50),
}
gui.add(grid)


@run_demos.on_space(gui)  #
def test_grid():
    # Test adding and removing cells.
    for row, col in widgets:
        grid.add(row, col, widgets[row, col])
    assert grid.num_rows == 2
    assert grid.num_cols == 2
    yield "Make a 2x2 grid."

    grid.remove(1, 1)
    assert grid.num_rows == 2
    assert grid.num_cols == 2
    yield "Remove the bottom right cell."
예제 #21
0
def display_scenes(
    data,
    height=480,
    width=640,
    tile=None,
    caption=None,
    rotate=False,
    rotation_scaling=1,
):
    import glooey

    scenes = None
    scenes_group = None
    scenes_ggroup = None
    if isinstance(data, types.GeneratorType):
        next_data = next(data)
        if isinstance(next_data, types.GeneratorType):
            scenes_ggroup = data
            scenes_group = next_data
            scenes = next(next_data)
        else:
            scenes_group = data
            scenes = next_data
    else:
        scenes = data

    scenes.pop("__clear__", False)

    if tile is None:
        nrow, ncol = _get_tile_shape(len(scenes), hw_ratio=height / width)
    else:
        nrow, ncol = tile

    configs = [
        pyglet.gl.Config(sample_buffers=1,
                         samples=4,
                         depth_size=24,
                         double_buffer=True),
        pyglet.gl.Config(double_buffer=True),
    ]
    HEIGHT_LABEL_WIDGET = 19
    PADDING_GRID = 1
    for config in configs:
        try:
            window = pyglet.window.Window(
                height=(height + HEIGHT_LABEL_WIDGET) * nrow,
                width=(width + PADDING_GRID * 2) * ncol,
                caption=caption,
                config=config,
            )
            break
        except pyglet.window.NoSuchConfigException:
            pass
    window.rotate = rotate

    window._clear = False
    if scenes_group:
        window.play = False
        window.next = False
    window.scenes_group = scenes_group
    window.scenes_ggroup = scenes_ggroup

    def usage():
        return """\
Usage:
  q: quit
  s: play / pause
  z: reset view
  n: next
  r: rotate view (clockwise)
  R: rotate view (anti-clockwise)\
"""

    @window.event
    def on_key_press(symbol, modifiers):
        if symbol == pyglet.window.key.Q:
            window.on_close()
        elif window.scenes_group and symbol == pyglet.window.key.S:
            window.play = not window.play
        elif symbol == pyglet.window.key.Z:
            for name in scenes:
                if isinstance(widgets[name], trimesh.viewer.SceneWidget):
                    widgets[name].reset_view()
        elif symbol == pyglet.window.key.N:
            if (window.scenes_ggroup
                    and modifiers == pyglet.window.key.MOD_SHIFT):
                try:
                    window.scenes_group = next(window.scenes_ggroup)
                    window.next = True
                    window._clear = True
                except StopIteration:
                    return
            else:
                window.next = True
        elif symbol == pyglet.window.key.C:
            camera_transform_ids = set()
            for key, widget in widgets.items():
                if isinstance(widget, trimesh.viewer.SceneWidget):
                    camera_transform_id = id(widget.scene.camera_transform)
                    if camera_transform_id in camera_transform_ids:
                        continue
                    camera_transform_ids.add(camera_transform_id)
                    print(f"{key}:")
                    camera_transform = widget.scene.camera_transform
                    print(repr(from_opengl_transform(camera_transform)))
        elif symbol == pyglet.window.key.R:
            # rotate camera
            window.rotate = not window.rotate  # 0/1
            if modifiers == pyglet.window.key.MOD_SHIFT:
                window.rotate *= -1
        elif symbol == pyglet.window.key.H:
            print(usage())

    def callback(dt):
        if window.rotate:
            for widget in widgets.values():
                if isinstance(widget, trimesh.viewer.SceneWidget):
                    axis = tf.transform_points(
                        [[0, 1, 0]],
                        widget.scene.camera_transform,
                        translate=False,
                    )[0]
                    widget.scene.camera_transform[...] = (tf.rotation_matrix(
                        np.deg2rad(window.rotate * rotation_scaling),
                        axis,
                        point=widget.scene.centroid,
                    ) @ widget.scene.camera_transform)
                    widget.view["ball"]._n_pose = widget.scene.camera_transform
            return

        if window.scenes_group and (window.next or window.play):
            try:
                scenes = next(window.scenes_group)
                clear = scenes.get("__clear__", False) or window._clear
                window._clear = False
                for key, widget in widgets.items():
                    scene = scenes[key]
                    if isinstance(widget, trimesh.viewer.SceneWidget):
                        assert isinstance(scene, trimesh.Scene)
                        if clear:
                            widget.clear()
                            widget.scene = scene
                        else:
                            widget.scene.geometry.update(scene.geometry)
                            widget.scene.graph.load(scene.graph.to_edgelist())
                        widget.scene.camera_transform[
                            ...] = scene.camera_transform
                        widget.view[
                            "ball"]._n_pose = widget.scene.camera_transform
                        widget._draw()
                    elif isinstance(widget, glooey.Image):
                        widget.set_image(numpy_to_image(scene))
            except StopIteration:
                print("Reached the end of the scenes")
                window.play = False
            window.next = False

    gui = glooey.Gui(window)
    grid = glooey.Grid()
    grid.set_padding(PADDING_GRID)

    widgets = {}
    trackball = None
    for i, (name, scene) in enumerate(scenes.items()):
        vbox = glooey.VBox()
        vbox.add(glooey.Label(text=name, color=(255, ) * 3), size=0)
        if isinstance(scene, trimesh.Scene):
            widgets[name] = trimesh.viewer.SceneWidget(scene)
            if trackball is None:
                trackball = widgets[name].view["ball"]
            else:
                widgets[name].view["ball"] = trackball
        elif isinstance(scene, np.ndarray):
            widgets[name] = glooey.Image(numpy_to_image(scene),
                                         responsive=True)
        else:
            raise TypeError(f"unsupported type of scene: {scene}")
        vbox.add(widgets[name])
        grid[i // ncol, i % ncol] = vbox

    gui.add(grid)

    pyglet.clock.schedule_interval(callback, 1 / 30)
    pyglet.app.run()
    pyglet.clock.unschedule(callback)