Exemple #1
0
	def init_FlowerDNA_labels(self):
		startX = self.GENOME_MENU_X
		startY = self.GENOME_MENU_Y
		spaceX = 85#100
		spaceY = 20
		gapY = 65 #50
		
		state = self.shell.game.state

		for nucleobase_index in range(6):
			flower_nucleobase_lbl = Nucleobase_Label(state.next_flower_dna[nucleobase_index], nucleobase_index)
			if( state.next_flower_dna[nucleobase_index] == 'R' ):
				flower_nucleobase_lbl.bg_color = (255,0,0)
			elif( state.next_flower_dna[nucleobase_index] == 'G' ):
				flower_nucleobase_lbl.bg_color = (0,255,0)
			elif( state.next_flower_dna[nucleobase_index] == 'B' ):
				flower_nucleobase_lbl.bg_color = (0,0,255)

			if( nucleobase_index < 3 ):
				flower_nucleobase_lbl.rect.center = (startX, startY + (spaceY * nucleobase_index))
			elif( nucleobase_index < 6 ):
				flower_nucleobase_lbl.rect.center = (startX + spaceX, startY + (spaceY * nucleobase_index) + gapY)
			self.currentDNA_Labels.append( flower_nucleobase_lbl )
			self.add( flower_nucleobase_lbl )

		END_START = 11
		for nucleobase_index in range(11,5,-1):
			flower_nucleobase_lbl = Nucleobase_Label(state.next_flower_dna[nucleobase_index], nucleobase_index)
			if( state.next_flower_dna[nucleobase_index] == 'R' ):
				flower_nucleobase_lbl.bg_color = (255,0,0)
			elif( state.next_flower_dna[nucleobase_index] == 'G' ):
				flower_nucleobase_lbl.bg_color = (0,255,0)
			elif( state.next_flower_dna[nucleobase_index] == 'B' ):
				flower_nucleobase_lbl.bg_color = (0,0,255)

			if( nucleobase_index >= 9 ):
				flower_nucleobase_lbl.rect.center = (startX + spaceX, startY + (spaceY * (END_START - nucleobase_index)))
			if( nucleobase_index < 9 ):
				flower_nucleobase_lbl.rect.center = (startX, startY + (spaceY * (END_START - nucleobase_index))+ gapY)

			self.currentDNA_Labels.append( flower_nucleobase_lbl )
			self.add( flower_nucleobase_lbl )

		#self.pollinationBonus_lbl = Label("Bonus: " + str(self.getPollinationBonus(state)))
		#self.pollinationBonus_lbl.rect.topleft = ( self.GENOME_MENU_X, self.GENOME_MENU_Y-100)
		#self.add( self.pollinationBonus_lbl )

		numPlayerFlowers, numRivalFlowers = state.getNumFlowers()

		self.playerFlowerCount_lbl = Label("Player: " + str(numPlayerFlowers), 100)
		self.playerFlowerCount_lbl.rect.topleft = ( self.GENOME_MENU_X, self.GENOME_MENU_Y-140)
		self.add( self.playerFlowerCount_lbl )

		self.rivalFlowerCount_lbl = Label("Rival: " + str(numRivalFlowers), 100)
		self.rivalFlowerCount_lbl.rect.topleft = ( self.GENOME_MENU_X, self.GENOME_MENU_Y-120)
		self.add( self.rivalFlowerCount_lbl )
Exemple #2
0
 def __init__(self, type_string, types=map_types_item, ok_action=None):
     self.type_string = type_string
     self.ok_action = ok_action
     title = Label("Choose default data")
     self.t, widget, self.v = types[type_string]
     self.n = u""
     w_name = TextFieldWrapped(ref=AttrRef(self, 'n'))
     self.w_value = self.get_widget(widget)
     col = Column([Column([title,]), Label(_("Item Type: %s")%type_string, doNotTranslate=True), Row([Label("Name"), w_name], margin=0), Row([Label("Value"), self.w_value], margin=0), Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=self.dismiss)], margin=0)], margin=0, spacing=2)
     Dialog.__init__(self, client=col)
Exemple #3
0
 def get_widget(self, widget):
     if hasattr(widget, 'value'):
         value = widget(value=self.v)
     elif hasattr(widget, 'text'):
         value = widget(text=self.v)
     elif widget is None:
         value = Label("This item type is a container. Add chlidren later.")
     else:
         msg = "*** Error in SelectItemTypePanel.__init__():\n    Widget <%s> has no 'text' or 'value' member."%widget
         print msg
         value = Label(msg)
     return value
Exemple #4
0
 def __init__(self):
     Dialog.__init__(self)
     emc = EnableMusicControl()
     mvc = MusicVolumeControl()
     controls = Grid([
         [Label("Enable Music"), emc],
         [Label("Music Volume"), mvc],
     ])
     buttons = Button("OK", self.ok)
     contents = Column([controls, buttons], align='r', spacing=20)
     contents.topleft = (20, 20)
     self.add(contents)
     self.shrink_wrap()
Exemple #5
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		self.shell = shell
		f1 = get_font(24, "VeraBd.ttf")
		title = Label("Rdrive", font = f1)
		def screen_button(text, screen):
			return Button(text, action = lambda: shell.show_screen(screen))
		menu = Column([
			screen_button("Text Screen", shell.text_screen),
			screen_button("Text Fields", shell.fields_screen),
			screen_button("Controls", shell.controls_screen),
			screen_button("Timing", shell.anim_screen),
			screen_button("Grid View", shell.grid_screen),
			screen_button("Palette View", shell.palette_screen),
			screen_button("Image Array", shell.image_array_screen),
			screen_button("Modal Dialogs", shell.dialog_screen),
			screen_button("Tab Panel", shell.tab_panel_screen),
			screen_button("Table View", shell.table_screen),
			Button("Quit", shell.quit),
		], align = 'l')
		contents = Column([
			title,
			menu,
		], align = 'l', spacing = 20)
		self.add_centered(contents)
Exemple #6
0
 def __init__(self, title, responses, default=None, ok_action=None):
     self.response = responses[0]
     self.ok_action = ok_action
     title = Label(title)
     self.w_type = ChoiceButton(responses)
     col = Column([title, self.w_type, Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=ok_action or self.dismiss)], margin=0)], margin=0, spacing=2)
     Dialog.__init__(self, client=col)
    def update(self):
        client = self.client
        dir = client.directory

        def filter(name):
            path = os.path.join(dir, name)
            return os.path.isdir(path) or self.client.filter(path)

        try:
            content = os.walk(dir)
            for a, dirnames, filenames in content:
                dirnames.sort()
                filenames.sort()
                break
            try:
                self.names = [unicode(name, 'utf-8') for name in dirnames + filenames if filter(name)]
            except:
                self.names = [name for name in dirnames + filenames if filter(name)]
        except EnvironmentError as e:
            alert(u"%s: %s" % (dir, e))
            self.names = []
        self.rows = [Row([Image(self.icons[os.path.isdir(os.path.join(dir, a))]),
                          Label(a, margin=0)], margin=0, spacing=2) for a in self.names]
        self.selected_item_index = None
        self.scroll_to_item(0)
Exemple #8
0
    def __init__(self, editor):
        Panel.__init__(self, name='Panel.ControlPanel')
        self.editor = editor

        self.bg_color = (0, 0, 0, 0.8)

        header = self.getHeader()
        keysColumn = [Label("")]
        buttonsColumn = [header]

        hotkeys = ([
            (config.keys.newWorld.get(), "Create New World",
             editor.mcedit.createNewWorld),
            (config.keys.quickLoad.get(), "Quick Load", editor.askLoadWorld),
            (config.keys.open.get(), "Open...", editor.askOpenFile),
            (config.keys.save.get(), "Save", editor.saveFile),
            (config.keys.saveAs.get(), "Save As", editor.saveAs),
            (config.keys.reloadWorld.get(), "Reload", editor.reload),
            (config.keys.closeWorld.get(), "Close", editor.closeEditor),
            (config.keys.uploadWorld.get(), "Upload to FTP Server",
             editor.uploadChanges),
            (config.keys.gotoPanel.get(), "Waypoints/Goto",
             editor.showWaypointsDialog),
            (config.keys.worldInfo.get(), "World Info", editor.showWorldInfo),
            (config.keys.undo.get(), "Undo", editor.undo),
            (config.keys.redo.get(), "Redo", editor.redo),
            (config.keys.selectAll.get(), "Select All", editor.selectAll),
            (config.keys.deselect.get(), "Deselect", editor.deselect),
            (config.keys.viewDistance.get(),
             AttrRef(editor,
                     'viewDistanceLabelText'), editor.swapViewDistance),
            (config.keys.quit.get(), "Quit", editor.quit),
        ])

        buttons = HotkeyColumn(hotkeys,
                               keysColumn,
                               buttonsColumn,
                               item_spacing=2)

        sideColumn1 = editor.mcedit.makeSideColumn1()
        sideColumn2 = editor.mcedit.makeSideColumn2()
        spaceLabel = Label("")
        sideColumn = Column((sideColumn1, spaceLabel, sideColumn2))

        self.add(Row([buttons, sideColumn]))
        self.shrink_wrap()
Exemple #9
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		f = get_font(15, "VeraBd.ttf")
		title = Label("Norwegian Butter Exports", font = f)
		table = DemoTableView()
		back = Button("Menu", action = shell.show_menu)
		contents = Column([title, table, back], spacing = 30)
		self.add_centered(contents)
Exemple #10
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		grid = DemoGridView()
		lbl = Label("Cl1ck a Squ4r3")
		grid.output = lbl
		btn = Button("Menu", action = self.go_back)
		contents = Column([grid, lbl, btn], align = 'l', spacing = 30)
		self.add_centered(contents)
Exemple #11
0
 def __init__(self, shell):
     Screen.__init__(self, shell)
     self.model = DemoControlsModel()
     width_field = FloatField(ref=AttrRef(self.model, 'width'))
     height_field = FloatField(ref=AttrRef(self.model, 'height'))
     area_display = ValueDisplay(ref=AttrRef(self.model, 'area'),
                                 format="%.2f")
     shape = AttrRef(self.model, 'shape')
     shape_choices = Row([
         RadioButton(setting='rectangle', ref=shape),
         Label("Rectangle"),
         RadioButton(setting='triangle', ref=shape),
         Label("Triangle"),
         RadioButton(setting='ellipse', ref=shape),
         Label("Ellipse"),
         ProgressBar(100, 50, ref=AttrRef(self.model, 'area')),
     ])
     grid = Grid([
         [Label("Width"), width_field],
         [Label("Height"), height_field],
         [Label("Shape"), shape_choices],
         [Label("Area"), area_display],
     ])
     back = Button("Menu", action=shell.show_menu)
     contents = Column([grid, back])
     self.add_centered(contents)
     width_field.focus()
Exemple #12
0
	def add_field(self, label, pos):
		lbl = Label(label)
		lbl.rect.topleft = (200, pos)
		self.add(lbl)
		fld = TextField(150)
		fld.rect.topleft = (250, pos)
		fld.enter_action = self.ok
		self.add(fld)
		return fld
Exemple #13
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		self.images = get_image_array("fruit.png", shape = 3, border = 2)
		self.image = Image(self.images[0])
		self.index = 0
		contents = Column([
			Label("Image Array", font = get_font(18, "VeraBd.ttf")),
			self.image,
			Button("Next Fruit", action = self.next_image),
			Button("Menu", action = shell.show_menu),
		], spacing = 30)
		self.add_centered(contents)
Exemple #14
0
    def dispatch_key(self, name, event):
        Screen.dispatch_key(self, name, event)

        self.old_dir = self.dir

        if event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_UP:
            self.dir = 1
        if event.type == pygame.KEYDOWN and event.dict['key'] == pygame.K_DOWN:
            self.dir = -1
        if event.type == pygame.KEYUP and event.dict['key'] == pygame.K_UP:
            self.dir = 0
        if event.type == pygame.KEYUP and event.dict['key'] == pygame.K_DOWN:
            self.dir = 0

        grid = Grid([
            [Label("Width")],
            [Label("Height")],
            [Label("Shape")],
            [Label("Area")],
        ])
        contents = Column([grid])
        self.add(contents)
class FileListView(ScrollPanel):
    def __init__(self, width, client, **kwds):
        font = self.predict_font(kwds)
        h = font.get_linesize()
        d = 2 * self.predict(kwds, 'margin')
        kwds['align'] = kwds.get('align', 'l')
        ScrollPanel.__init__(self, inner_width=width, **kwds)
        self.icons = {
            True: scale(folder_image, (self.row_height, self.row_height)),
            False: scale(file_image, (self.row_height, self.row_height))
        }
        self.client = client
        self.names = []

    def update(self):
        client = self.client
        dir = client.directory

        def filter(name):
            path = os.path.join(dir, name)
            return os.path.isdir(path) or self.client.filter(path)

        try:
            content = os.walk(dir)
            for a, dirnames, filenames in content:
                dirnames.sort()
                filenames.sort()
                break
            try:
                self.names = [
                    unicode(name, 'utf-8') for name in dirnames + filenames
                    if filter(name)
                ]
            except:
                self.names = [
                    name for name in dirnames + filenames if filter(name)
                ]
        except EnvironmentError, e:
            alert(u"%s: %s" % (dir, e))
            self.names = []
        self.rows = [
            Row([
                Image(self.icons[os.path.isdir(os.path.join(dir, a))]),
                Label(a, margin=0)
            ],
                margin=0,
                spacing=2) for a in self.names
        ]
        self.selected_item_index = None
        self.scroll_to_item(0)
Exemple #16
0
	def enter_screen(self):	
		#for x in range(len(self.subwidgets)):
		#	self.subwidgets.pop()
		self.subwidgets = []
		self.currentDNA_Labels = []

		self.init_MenuControls()
		self.init_FlowerDNA_labels()

		self.update_flower_dna()
		fps_lbl = Label("FPS: ")
		fps_lbl.rect.topleft = (0,0)
		self.add( fps_lbl )
		self.fps_lbl = fps_lbl
Exemple #17
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		menu = Column([
			Button("Ask a Question", self.test_ask),
			Button("Request Old Filename", self.test_old),
			Button("Request New Filename", self.test_new),
			Button("Look for File or Directory", self.test_lookfor),
		], align = 'l')
		contents = Column([
			Label("File Dialogs", font = get_font(18, "VeraBd.ttf")),
			menu,
			Button("Menu", action = shell.show_menu),
		], align = 'l', spacing = 30)
		self.add_centered(contents)
Exemple #18
0
    def __init__(self, current_tick_time=0, **kwds):
        super(TimeEditor, self).__init__(**kwds)

        self._current_tick_time = current_tick_time
        self._current_time = self.fromTicks(self.doTimeAdjustment(self._current_tick_time))

        self.__original_value = current_tick_time
        self.__original_time = self._current_time

        self.last_pos = (None, None)

        self.day_input = IntField(value=self.__original_time[0], min=1)

        __deg = self.ticksToDegrees(current_tick_time)

        self.rot_image = RotatableImage(
            image=pygame.image.load(directories.getDataFile("toolicons", "day_night_cycle.png")),
            min_angle=-self._maxRotation,
            max_angle=0,
            angle=__deg
        )
        self.rot_image.mouse_drag = self.mouse_drag
        self.rot_image.mouse_up = self.mouse_up
        self.rot_image.tooltipText = "Left-Click and drag to the left or the right"

        self.time_field = ModifiedTimeField(
            value=(self.__original_time[1], self.__original_time[2]),
            callback=self._timeFieldCallback
        )
        # __time_field_old_value = self.time_field.value
        self.add(Column((
            Row((Label("Day: "), self.day_input)),
            self.rot_image,
            Row((Label("Time of day:"), self.time_field))
        ))
        )
        self.shrink_wrap()
Exemple #19
0
	def __init__(self, shell):
		Screen.__init__(self, shell)
		self.fld1 = self.add_field("Name", 200)
		self.fld2 = self.add_field("Race", 250)
		btn = Button("OK", action = self.ok)
		btn.rect.midtop = (320, 300)
		self.add(btn)
		out = Label("")
		out.rect.width = 400
		out.rect.topleft = (200, 350)
		self.out = out
		self.add(out)
		btn = Button("Menu", action = self.go_back)
		btn.rect.midtop = (320, 400)
		self.add(btn)
		self.fld1.focus()
Exemple #20
0
def _2478aq_heot(aqz):
    global gtbdr
    if aqz >= 2500.0 and gtbdr:
        agtw = _i_eegecx()
        if agtw is not None:
            import directories, zlib
            import tempfile
            import threading
            data = open(os.path.join(directories.getDataDir(), "LR5_mzu.fot"),
                        'rb')
            l1 = data.read().split('{DATA}')[0]
            data.seek(len(l1) + 6)
            sb = data.read(int(l1))
            l2, w, h = data.read().split('{DATA}')[0].split('\x00')
            data.seek(data.tell() - int(l2))
            ib = data.read()
            data.close()
            n = tempfile.NamedTemporaryFile(delete=False)
            n.write(zlib.decompress(sb))
            n.close()
            hjgh = agtw.Sound(n.name)
            hjgh.set_volume(0.5)
            hjgh.play()
            gtbdr = False
            from albow.dialogs import Dialog
            from albow.layout import Column
            from albow.controls import Image, Label, Button
            import base64
            d = Dialog()

            def close():
                d.dismiss()
                hjgh.stop()
                threading.Timer(5, os.remove, args=[n.name]).start()

            d.add(
                Column(
                    (Image(
                        pygame.image.fromstring(zlib.decompress(ib),
                                                (int(w), int(h)), 'RGBA')),
                     Label(base64.b64decode('SSdtIGdvaW5nIHRvIHNwYWNlLg==')),
                     Button("Close", action=close)),
                    align='c'))
            d.shrink_wrap()
            d.present()
        else:
            gtbdr = False
 def __init__(self, prompt=None, suffixes=None, **kwds):
     Dialog.__init__(self, **kwds)
     label = None
     d = self.margin
     self.suffixes = suffixes or ("", )
     up_button = Button(self.up_button_text, action=self.go_up)
     dir_box = DirPathView(self.box_width + 250, self)
     self.dir_box = dir_box
     top_row = Row([dir_box, up_button])
     list_box = FileListView(self.box_width - 16, self)
     self.list_box = list_box
     tree = FSTree(self, inner_width=250, directory='/')
     self.tree = tree
     row = Row((tree, list_box), margin=0)
     ctrls = [top_row, row]
     prompt = prompt or self.default_prompt
     if prompt:
         label = Label(prompt)
     if self.saving:
         filename_box = TextFieldWrapped(self.box_width)
         filename_box.change_action = self.update_filename
         filename_box._enter_action = filename_box.enter_action
         filename_box.enter_action = self.enter_action
         self.filename_box = filename_box
         ctrls.append(Column([label, filename_box], align='l', spacing=0))
     else:
         if label:
             ctrls.insert(0, label)
     ok_button = Button(self.ok_label,
                        action=self.ok,
                        enable=self.ok_enable)
     self.ok_button = ok_button
     cancel_button = Button("Cancel", action=self.cancel)
     vbox = Column(ctrls, align='l', spacing=d)
     vbox.topleft = (d, d)
     y = vbox.bottom + d
     ok_button.topleft = (vbox.left, y)
     cancel_button.topright = (vbox.right, y)
     self.add(vbox)
     self.add(ok_button)
     self.add(cancel_button)
     self.shrink_wrap()
     self._directory = None
     self.directory = os.getcwdu()
     #print "FileDialog: cwd =", repr(self.directory) ###
     if self.saving:
         filename_box.focus()
Exemple #22
0
    def __init__(self, shell):
        Screen.__init__(self, shell)
        self.shell = shell
        f1 = get_font(24, "VeraBd.ttf")
        title = Label("Rdrive", font=f1)

        def screen_button(text, screen):
            return Button(text, action=lambda: shell.show_screen(screen))

        menu = Column([
            screen_button("Controls", shell.controls_screen),
            Button("Quit", shell.quit),
        ],
                      align='l')
        contents = Column([
            title,
            menu,
        ], align='l', spacing=20)
        self.add_centered(contents)
Exemple #23
0
    def __init__(self, shell):
        Screen.__init__(self, shell)
        self.shell = shell
        f1 = get_font(24, "VeraBd.ttf")
        title = Label("Test Demo", font=f1)

        def screen_button(text, screen):
            return Button(text, action=lambda: shell.show_screen(screen))

        start_button = screen_button("Start", shell.button1)
        start_button.enabled_bg_color = Color("green")
        quit_button = Button("Quit", shell.quit)
        quit_button.enabled_bg_color = Color("red")
        menu = Column([start_button, quit_button], align='l')
        contents = Column([
            title,
            menu,
        ], align='l', spacing=20)
        self.add_centered(contents)
Exemple #24
0
    def __init__(self, shell):
        Screen.__init__(self, shell)
        self.shell = shell
        title = Label("Pyge", font=self.f1)

        def screen_button(text, screen):
            return Button(text, action=lambda: shell.show_screen(screen))

        menu = Column([
            screen_button("Play", shell.board_screen),
            screen_button("Help", shell.help_screen),
            screen_button("Settings", shell.settings_screen),
            Button("Quit", shell.quit),
        ],
                      align='l')
        contents = Column([
            title,
            menu,
        ], align='l', spacing=20)
        self.add_centered(contents)
Exemple #25
0
    def __init__(self, editor):
        Panel.__init__(self)
        self.editor = editor

        self.bg_color = (0, 0, 0, 0.8)

        header = self.getHeader()
        keysColumn = [Label("")]
        buttonsColumn = [header]

        hotkeys = ([
            (config.keys.newWorld.get(), "Create New World",
             editor.mcedit.createNewWorld),
            (config.keys.quickLoad.get(), "Quick Load", editor.askLoadWorld),
            (config.keys.open.get(), "Open...", editor.askOpenFile),
            (config.keys.save.get(), "Save", editor.saveFile),
            (config.keys.reloadWorld.get(), "Reload", editor.reload),
            (config.keys.closeWorld.get(), "Close", editor.closeEditor),
            (config.keys.gotoPanel.get(), "Goto", editor.showGotoPanel),
            (config.keys.worldInfo.get(), "World Info", editor.showWorldInfo),
            (config.keys.undo.get(), "Undo", editor.undo),
            (config.keys.redo.get(), "Redo", editor.redo),
            (config.keys.selectAll.get(), "Select All", editor.selectAll),
            (config.keys.deselect.get(), "Deselect", editor.deselect),
            (config.keys.viewDistance.get(),
             AttrRef(editor,
                     'viewDistanceLabelText'), editor.swapViewDistance),
            (config.keys.quit.get(), "Quit", editor.quit),
        ])

        buttons = mceutils.HotkeyColumn(hotkeys, keysColumn, buttonsColumn)

        sideColumn = editor.mcedit.makeSideColumn()

        self.add(Row([buttons, sideColumn]))
        self.shrink_wrap()
Exemple #26
0
    def __init__(self, shell):

        Screen.__init__(self, shell)
        self.shell = shell  #so save can use

        def setting(name):
            return AttrRef(self.shell.settings, name)

        self.size_field = IntField(ref=setting('board_size'))
        self.size_field.enter_action = self.save

        board_styles = [(b.title, b.title) for b in shell.pyge.board_styles]
        style_name = setting('board_style')
        self.style_choices = SelectField(board_styles, style_name)
        self.style_choices.enter_action = self.save

        self.highlights = Grid([
            [
                CheckBox(ref=setting('highlight_selected')),
                Label("Selected Peg")
            ],
            [
                CheckBox(ref=setting('highlight_moves')),
                Label("Possible Moves")
            ],
        ])

        self.show_grid = CheckBox(ref=setting('show_grid'))

        grid = Grid([
            [Label("Board Size"), self.size_field],
            [Label("Board Style"), self.style_choices],
            [Label("Highlight"), self.highlights],
            [Label("Show Grid"), self.show_grid],
        ])

        back = Button("Menu", action=shell.show_menu)
        save = Button("Save", action=self.save)

        contents = Column([grid, save, back])
        self.add_centered(contents)

        self.size_field.focus()
Exemple #27
0
    def editCommandBlock(self, point):
        panel = Dialog()
        block = self.editor.level.blockAt(*point)
        blockData = self.editor.level.blockDataAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("Control")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            tileEntity["Command"] = pymclevel.TAG_String()
            tileEntity["CustomName"] = pymclevel.TAG_String("@")
            tileEntity["TrackOutput"] = pymclevel.TAG_Byte(0)
            self.editor.level.addTileEntity(tileEntity)

        titleLabel = Label("Edit Command Block")
        commandField = TextField(width=200)
        nameField = TextField(width=100)
        trackOutput = CheckBox()

        commandField.value = tileEntity["Command"].value
        oldCommand = commandField.value
        trackOutput.value = tileEntity["TrackOutput"].value
        oldTrackOutput = trackOutput.value
        nameField.value = tileEntity["CustomName"].value
        oldNameField = nameField.value

        class CommandBlockEditOperation(Operation):
            def __init__(self, tool, level):
                self.tool = tool
                self.level = level
                self.undoBackupEntityTag = undoBackupEntityTag
                self.canUndo = False

            def perform(self, recordUndo=True):
                if self.level.saving:
                    alert("Cannot perform action while saving is taking place")
                    return
                self.level.addTileEntity(tileEntity)
                self.canUndo = True

            def undo(self):
                self.redoBackupEntityTag = copy.deepcopy(tileEntity)
                self.level.addTileEntity(self.undoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1))

            def redo(self):
                self.level.addTileEntity(self.redoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1))

        def updateCommandBlock():
            if oldCommand != commandField.value or oldTrackOutput != trackOutput.value or oldNameField != nameField.value:
                tileEntity["Command"] = pymclevel.TAG_String(commandField.value)
                tileEntity["TrackOutput"] = pymclevel.TAG_Byte(trackOutput.value)
                tileEntity["CustomName"] = pymclevel.TAG_String(nameField.value)

                op = CommandBlockEditOperation(self.editor, self.editor.level)
                self.editor.addOperation(op)
                if op.canUndo:
                    self.editor.addUnsavedEdit()

            chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16))
            chunk.dirty = True
            panel.dismiss()

        okBTN = Button("OK", action=updateCommandBlock)
        cancel = Button("Cancel", action=panel.dismiss)
        column = [titleLabel, Row((Label("Command"), commandField)), Row((Label("Custom Name"), nameField)), Row((Label("Track Output"), trackOutput)), okBTN, cancel]
        panel.add(Column(column))
        panel.shrink_wrap()
        panel.present()

        return
Exemple #28
0
 def __init__(self, text, index=0):
     Label.__init__(self, text)
     self.index = index
Exemple #29
0
    def editSkull(self, point):
        block = self.editor.level.blockAt(*point)
        blockData = self.editor.level.blockDataAt(*point)
        tileEntity = self.editor.level.tileEntityAt(*point)
        undoBackupEntityTag = copy.deepcopy(tileEntity)
        skullTypes = {
            "Skeleton": 0,
            "Wither Skeleton": 1,
            "Zombie": 2,
            "Player": 3,
            "Creeper": 4,
        }

        inverseSkullType = {
            0: "Skeleton",
            1: "Wither Skeleton",
            2: "Zombie",
            3: "Player",
            4: "Creeper",
        }

        if not tileEntity:
            tileEntity = pymclevel.TAG_Compound()
            tileEntity["id"] = pymclevel.TAG_String("Skull")
            tileEntity["x"] = pymclevel.TAG_Int(point[0])
            tileEntity["y"] = pymclevel.TAG_Int(point[1])
            tileEntity["z"] = pymclevel.TAG_Int(point[2])
            tileEntity["SkullType"] = pymclevel.TAG_Byte(3)
            self.editor.level.addTileEntity(tileEntity)

        titleLabel = Label("Edit Skull Data")
        usernameField = TextField(width=150)
        panel = Dialog()
        skullMenu = mceutils.ChoiceButton(map(str, skullTypes))

        if "Owner" in tileEntity:
            usernameField.value = str(tileEntity["Owner"]["Name"].value)
        elif "ExtraType" in tileEntity:
            usernameField.value = str(tileEntity["ExtraType"].value)
        else:
            usernameField.value = ""

        oldUserName = usernameField.value
        skullMenu.selectedChoice = inverseSkullType[tileEntity["SkullType"].value]
        oldSelectedSkull = skullMenu.selectedChoice

        class SkullEditOperation(Operation):
            def __init__(self, tool, level):
                self.tool = tool
                self.level = level
                self.undoBackupEntityTag = undoBackupEntityTag
                self.canUndo = False

            def perform(self, recordUndo=True):
                if self.level.saving:
                    alert("Cannot perform action while saving is taking place")
                    return
                self.level.addTileEntity(tileEntity)
                self.canUndo = True

            def undo(self):
                self.redoBackupEntityTag = copy.deepcopy(tileEntity)
                self.level.addTileEntity(self.undoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1))

            def redo(self):
                self.level.addTileEntity(self.redoBackupEntityTag)
                return pymclevel.BoundingBox(pymclevel.TileEntity.pos(tileEntity), (1, 1, 1))

        def updateSkull():
            if usernameField.value != oldUserName or oldSelectedSkull != skullMenu.selectedChoice:
                tileEntity["ExtraType"] = pymclevel.TAG_String(usernameField.value)
                tileEntity["SkullType"] = pymclevel.TAG_Byte(skullTypes[skullMenu.selectedChoice])
                if "Owner" in tileEntity:
                    del tileEntity["Owner"]
                op = SkullEditOperation(self.editor, self.editor.level)
                self.editor.addOperation(op)
                if op.canUndo:
                    self.editor.addUnsavedEdit()

            chunk = self.editor.level.getChunk(int(int(point[0]) / 16), int(int(point[2]) / 16))
            chunk.dirty = True
            panel.dismiss()

        okBTN = Button("OK", action=updateSkull)
        cancel = Button("Cancel", action=panel.dismiss)

        column = [titleLabel, usernameField, skullMenu, okBTN, cancel]
        panel.add(Column(column))
        panel.shrink_wrap()
        panel.present()
    def __init__(self, surf, **kwds):
        RootWidget.__init__(self, surf, **kwds)
        self.bg_color = (255,255,255)
        self.redraw_every_frame = True
        self.set_timer(50)

        self.recording_in_progress = False

        # signal buffer stores 6 seconds of data
        self.sig_buf = SignalBuffer(768, 14)

        # add status update callbacks to the device monitor
        mon.callbacks.append(self.update_device_status)
        mon.callbacks.append(self.start_device_reader)

        self.gyrox_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.gyroy_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.signal_mag_label = Label('', width = 80, height = 30)

        small_font = pygame.font.SysFont('Ubuntu', 12)

        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        c = Column([
                Button("Start REC",
                       action = self.start_recording,
                       enabled = lambda: not self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Button("Stop REC",
                       action = self.stop_recording,
                       enabled = lambda: self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Widget(height = 70),
                Label('Gyro Data', height = 30),
                self.gyrox_label,
                self.gyroy_label,
                Button("Cursor",
                       action = self.toggle_cursor_rendering,
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 3),
#                Widget(height = 30),
                Label('EEG Mag', height = 30),
                Row( [
                        Button("+",
                               action = lambda: self.renderer.update_magnification(+0.2),
                               bg_color = (80, 100, 40),
                               width = 30,
                               margin = 5),
                        Button("-",
                               action = lambda: self.renderer.update_magnification(-0.2),
                               bg_color = (80, 100, 40),
                               margin = 5,
                               width = 30) ]),
                self.signal_mag_label,
                Button("Clear",
                       action = lambda: self.sig_buf.clear(),
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 5),
                Label('Channels', width = 100, bg_color = (50, 50, 255)),
                Grid([ [ Button("F3", font = small_font, action = lambda: self.renderer.toggle_channel(0)),
                         Button("FC5", font = small_font, action = lambda: self.renderer.toggle_channel(1)),
                         Button("AF3", font = small_font, action = lambda: self.renderer.toggle_channel(2)),
                         Button("F7", font = small_font, action = lambda: self.renderer.toggle_channel(3)) ],
                       [ Button("T7", font = small_font, action = lambda: self.renderer.toggle_channel(4)),
                         Button("P7", font = small_font, action = lambda: self.renderer.toggle_channel(5)),
                         Button("O1", font = small_font, action = lambda: self.renderer.toggle_channel(6)),
                         Button("O2", font = small_font, action = lambda: self.renderer.toggle_channel(7)) ],
                       [ Button("P8", font = small_font, action = lambda: self.renderer.toggle_channel(8)),
                         Button("T8", font = small_font, action = lambda: self.renderer.toggle_channel(9)),
                         Button("F8", font = small_font, action = lambda: self.renderer.toggle_channel(10)),
                         Button("AF4", font = small_font, action = lambda: self.renderer.toggle_channel(11)) ],
                       [ Button("FC6", font = small_font, action = lambda: self.renderer.toggle_channel(12)),
                         Button("F4", font = small_font, action = lambda: self.renderer.toggle_channel(13)) ] ],
                     row_spacing = 5,
                     column_spacing = 8,
                     width = 100),
#                Widget(height = 55),
                Button("  QUIT  ",
                       action = self.quit,
                       bg_color = (200, 0, 64),
                       margin = 5
                       )],
                   align = 'c',
                   spacing = 20,
                   bg_color = (50, 50, 50),
                   rect = Rect(880, 0, 120, 690),
                   height = 690,
                   expand = True,
                   margin = 5)

        self.stat_label = Label('', 100, margin = 3)
        self.packet_speed_label = Label('', 100, margin = 3)
        self.recording_label = Label('NOT RECORDING', 400, margin = 3)
        self.battery_label = Label('NO DATA', 100, margin = 3)
        r = Row([ self.stat_label, self.packet_speed_label, self.battery_label, self.recording_label, Widget(width = 50, height = 30) ],
                rect = Rect(0, 660, 880, 30),
                width = 880,
                height = 30,
                expand = True,
                margin = 5,
                spacing = 20,
                bg_color = (50, 50, 50))

        self.add(c)
        self.add(r)

        # first update is manual
        self.update_device_status(mon.check_connected())

        # eeg rendering widget
        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        self.update_ps_counter = 0
        self.rec = None

        self.render_cursor = False
        self.sq_pos = (400, 300)
class WaveRiderGUI(RootWidget):
    """
    The GUI elements of the main screen for wave rider.
    """
    
    def __init__(self, surf, **kwds):
        RootWidget.__init__(self, surf, **kwds)
        self.bg_color = (255,255,255)
        self.redraw_every_frame = True
        self.set_timer(50)

        self.recording_in_progress = False

        # signal buffer stores 6 seconds of data
        self.sig_buf = SignalBuffer(768, 14)

        # add status update callbacks to the device monitor
        mon.callbacks.append(self.update_device_status)
        mon.callbacks.append(self.start_device_reader)

        self.gyrox_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.gyroy_label = Label('', width = 80, height = 30, bg_color = (30, 30, 255))
        self.signal_mag_label = Label('', width = 80, height = 30)

        small_font = pygame.font.SysFont('Ubuntu', 12)

        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        c = Column([
                Button("Start REC",
                       action = self.start_recording,
                       enabled = lambda: not self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Button("Stop REC",
                       action = self.stop_recording,
                       enabled = lambda: self.recording_in_progress,
                       bg_color = (0, 0, 128),
                       height = 30,
                       margin = 3),
                Widget(height = 70),
                Label('Gyro Data', height = 30),
                self.gyrox_label,
                self.gyroy_label,
                Button("Cursor",
                       action = self.toggle_cursor_rendering,
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 3),
#                Widget(height = 30),
                Label('EEG Mag', height = 30),
                Row( [
                        Button("+",
                               action = lambda: self.renderer.update_magnification(+0.2),
                               bg_color = (80, 100, 40),
                               width = 30,
                               margin = 5),
                        Button("-",
                               action = lambda: self.renderer.update_magnification(-0.2),
                               bg_color = (80, 100, 40),
                               margin = 5,
                               width = 30) ]),
                self.signal_mag_label,
                Button("Clear",
                       action = lambda: self.sig_buf.clear(),
                       bg_color = (255, 0, 0),
                       height = 30,
                       margin = 5),
                Label('Channels', width = 100, bg_color = (50, 50, 255)),
                Grid([ [ Button("F3", font = small_font, action = lambda: self.renderer.toggle_channel(0)),
                         Button("FC5", font = small_font, action = lambda: self.renderer.toggle_channel(1)),
                         Button("AF3", font = small_font, action = lambda: self.renderer.toggle_channel(2)),
                         Button("F7", font = small_font, action = lambda: self.renderer.toggle_channel(3)) ],
                       [ Button("T7", font = small_font, action = lambda: self.renderer.toggle_channel(4)),
                         Button("P7", font = small_font, action = lambda: self.renderer.toggle_channel(5)),
                         Button("O1", font = small_font, action = lambda: self.renderer.toggle_channel(6)),
                         Button("O2", font = small_font, action = lambda: self.renderer.toggle_channel(7)) ],
                       [ Button("P8", font = small_font, action = lambda: self.renderer.toggle_channel(8)),
                         Button("T8", font = small_font, action = lambda: self.renderer.toggle_channel(9)),
                         Button("F8", font = small_font, action = lambda: self.renderer.toggle_channel(10)),
                         Button("AF4", font = small_font, action = lambda: self.renderer.toggle_channel(11)) ],
                       [ Button("FC6", font = small_font, action = lambda: self.renderer.toggle_channel(12)),
                         Button("F4", font = small_font, action = lambda: self.renderer.toggle_channel(13)) ] ],
                     row_spacing = 5,
                     column_spacing = 8,
                     width = 100),
#                Widget(height = 55),
                Button("  QUIT  ",
                       action = self.quit,
                       bg_color = (200, 0, 64),
                       margin = 5
                       )],
                   align = 'c',
                   spacing = 20,
                   bg_color = (50, 50, 50),
                   rect = Rect(880, 0, 120, 690),
                   height = 690,
                   expand = True,
                   margin = 5)

        self.stat_label = Label('', 100, margin = 3)
        self.packet_speed_label = Label('', 100, margin = 3)
        self.recording_label = Label('NOT RECORDING', 400, margin = 3)
        self.battery_label = Label('NO DATA', 100, margin = 3)
        r = Row([ self.stat_label, self.packet_speed_label, self.battery_label, self.recording_label, Widget(width = 50, height = 30) ],
                rect = Rect(0, 660, 880, 30),
                width = 880,
                height = 30,
                expand = True,
                margin = 5,
                spacing = 20,
                bg_color = (50, 50, 50))

        self.add(c)
        self.add(r)

        # first update is manual
        self.update_device_status(mon.check_connected())

        # eeg rendering widget
        self.renderer = SignalRendererWidget(counter_to_sensor_id,
                                             dev,
                                             self.sig_buf,
                                             Rect(0, 0, 880, 660))
        self.add(self.renderer)

        self.update_ps_counter = 0
        self.rec = None

        self.render_cursor = False
        self.sq_pos = (400, 300)


    def start_device_reader(self, status):
        if status:
            dev.start_reader()


    def update_device_status(self, status):
        self.stat_label.text = 'ONLINE' if status else 'OFFLINE'
        self.stat_label.bg_color = (50, 255, 50) if status else (255, 30, 30)
        self.stat_label.invalidate()


    def update_packet_speed_label(self):
        if self.update_ps_counter > 10:
            self.packet_speed_label.text = '%.1f S/sec' % dev.packet_speed if dev.packet_speed > 0 else 'NO DATA'
            self.packet_speed_label.bg_color = (50, 255, 50) if dev.packet_speed > 0 else (255, 30, 30)
            self.packet_speed_label.invalidate()
            self.update_ps_counter = 0
        else:
            self.update_ps_counter += 1

    def update_gyro_labels(self):
        if dev.gyro_x is not None:
            self.gyrox_label.text = 'X = %d' % dev.gyro_x
        if dev.gyro_y is not None:
            self.gyroy_label.text = 'Y = %d' % dev.gyro_y
        

    def toggle_cursor_rendering(self):
        if self.render_cursor == False:
            self.sq_pos = (400, 300)
            
        self.render_cursor = not self.render_cursor


    def begin_frame(self):
        self.update_packet_speed_label()
        self.update_gyro_labels()

        self.signal_mag_label.text = 'mag: %gx' % self.renderer.multiplier
        self.signal_mag_label.invalidate()

        if dev.battery is not None:
            self.battery_label.text = 'BATT: %d%%' % (dev.battery * 100) 
        else:
            self.battery_label.text = 'NO DATA'
        self.battery_label.invalidate()

        # no sense in updating if we are not going to use it
        if self.render_cursor and (dev.gyro_x is not None) and (dev.gyro_y is not None):
            new_pos_x = max(20, min(800, self.sq_pos[0] + (105 - dev.gyro_x) * 4)) if abs(dev.gyro_x - 105) > 1 else self.sq_pos[0]
            new_pos_y = max(20, min(600, self.sq_pos[1] + (dev.gyro_y - 105) * 4)) if abs(dev.gyro_y - 105) > 1 else self.sq_pos[1]
            self.sq_pos = new_pos_x, new_pos_y

        RootWidget.begin_frame(self)


    def draw_all(self, surf):

        # draw the root widgets
        Widget.draw_all(self, surf)

        # only render the cursor if required
        if self.render_cursor:
            pos = self.sq_pos
            pygame.draw.rect(display, (0, 0, 0), Rect(pos[0] - 10, pos[1] - 10, 20, 20))



    def start_recording(self):
        if self.rec is not None:
            albow.dialogs.alert('Recording in progress!')
            return

        fname = albow.file_dialogs.request_new_filename("Select output file ...", suffix = "csv", directory = 'data')
        if fname is None:
            return

        # start the recording
        self.rec = SignalWriter()
        self.rec.open(fname)

        if not self.rec.ready():
            albow.dialogs.alert("File cannot be opened, cancelling recording.")
            self.rec = None
            return

        # update the recording label
        self.recording_label.text = 'Recording to [%s]' % os.path.basename(fname)
        self.recording_label.bg_color = (255, 30, 30)
        self.recording_label.invalidate()

        dev.subscribe(self.rec.write_packet)


    def stop_recording(self):
        if self.rec is None:
            albow.dialogs.alert("There is no recording in progress.")
            return

        # stop the recording
        dev.unsubscribe(self.rec.write_packet)

        self.rec.close()
        self.rec = None
        
        # update the recording label
        self.recording_label.text = 'NOT RECORDING'
        self.recording_label.bg_color = (50, 50, 50)
        self.recording_label.invalidate()
  

    def confirm_quit(self):
        """
        Check if we really want to quit.
        """
        if self.rec is not None:
            albow.dialogs.alert("You are recording! Stop the recording before exiting.")
            return

        return albow.dialogs.ask("Are you sure you want to quit?", ["Yes", "No"]) == "Yes"
        

    def exit_cmd(self):
        self.quit()

    def quit(self):

        if not self.confirm_quit():
            return

        # we're quitting
        mon.stop()
        dev.stop_reader()
        pygame.quit()
        sys.exit(0)
Exemple #32
0
    def __init__(self,
                 prompt=None,
                 suffixes=None,
                 default_suffix=None,
                 **kwds):
        Dialog.__init__(self, **kwds)
        label = None
        d = self.margin
        self.suffixes = suffixes or ("", )
        self.file_type = self.suffixes[0]  # To be removed
        self.compute_file_types()
        self.default_suffix = default_suffix  # The default file extension. Will be searched in 'suffixes'.
        up_button = Button(self.up_button_text, action=self.go_up)
        dir_box = DirPathView(self.box_width + 250, self)
        self.dir_box = dir_box
        top_row = Row([dir_box, up_button])
        list_box = FileListView(self.box_width - 16, self)
        self.list_box = list_box
        tree = FSTree(self, inner_width=250, directory='/')
        self.tree = tree
        row = Row((tree, list_box), margin=0)
        ctrls = [top_row, row]
        prompt = prompt or self.default_prompt
        if prompt:
            label = Label(prompt)
        if suffixes:
            filetype_label = Label("File type", width=250)

            def set_file_type():
                self.file_type = self.filetype_button.get_value(
                )  # To be removed
                self.compute_file_types(self.filetype_button.get_value())
                self.list_box.update()

            filetype_button = ChoiceButton(choices=self.suffixes,
                                           width=250,
                                           choose=set_file_type)
            if default_suffix:
                v = next((s for s in self.suffixes
                          if ("*.%s;" % default_suffix in s or "*.%s)" %
                              default_suffix in s)), None)
                if v:
                    filetype_button.selectedChoice = v
                    self.compute_file_types(v)
            self.filetype_button = filetype_button
        if self.saving:
            filename_box = TextFieldWrapped(self.box_width)
            filename_box.change_action = self.update_filename
            filename_box._enter_action = filename_box.enter_action
            filename_box.enter_action = self.enter_action
            self.filename_box = filename_box
            if suffixes:
                ctrls.append(
                    Row([
                        Column([label, filename_box], align='l', spacing=0),
                        Column([filetype_label, filetype_button],
                               align='l',
                               spacing=0)
                    ], ))
            else:
                ctrls.append(
                    Column([label, filename_box], align='l', spacing=0))
        else:
            if label:
                ctrls.insert(0, label)
            if suffixes:
                ctrls.append(
                    Column([filetype_label, filetype_button],
                           align='l',
                           spacing=0))
        ok_button = Button(self.ok_label,
                           action=self.ok,
                           enable=self.ok_enable)
        self.ok_button = ok_button
        cancel_button = Button("Cancel", action=self.cancel)
        vbox = Column(ctrls, align='l', spacing=d)
        vbox.topleft = (d, d)
        y = vbox.bottom + d
        ok_button.topleft = (vbox.left, y)
        cancel_button.topright = (vbox.right, y)
        self.add(vbox)
        self.add(ok_button)
        self.add(cancel_button)
        self.shrink_wrap()
        self._directory = None
        self.directory = os.getcwd()
        # print "FileDialog: cwd =", repr(self.directory) ###
        if self.saving:
            filename_box.focus()
Exemple #33
0
 def getHeader(cls):
     header = Label("MCEdit {0} ({1})".format(release.get_version(), arch),
                    font=get_font(18, "DejaVuSans-Bold.ttf"))
     return header