def init_gui(): #themes = cfg['theme'].split(",") #gui.theme.load(themes) #gui.theme.load(['default','tools']) global top top = gui.Desktop(theme=gui.Theme([ os.path.join('data', 'themes', 'default'), os.path.join('data', 'themes', 'tools') ]))
def __init__(self, surface): self.music = True self.sfx = True self.surface = surface self.bg = pygame.image.load("png/bg.png") self.surface.blit(self.bg, (0, 0)) self.app = gui.App(theme=gui.Theme("data/themes/clean")) self.app.connect(gui.QUIT, self.app.quit, None) self.table = gui.Table(width=self.surface.get_width(), height=self.surface.get_height()) self.table.tr() self.font = pygame.font.Font("font.ttf", 50) self.sfont = pygame.font.Font("font.ttf", 16) self.table.td(gui.Label("Zombie Hordes", font=self.font)) self.table.tr() self.button = gui.Button("Play", width=200, font=self.sfont) self.button.connect(gui.CLICK, self.playgame) self.table.td(self.button) self.quit = gui.Button("Quit", width=200, font=self.sfont) self.quit.connect(gui.CLICK, self.app.quit, None) self.dlg = None def dlo(): self.dlg = TestDialog(self) self.dlg.open() threading.Thread(target=dlc).start() def dlc(): while self.dlg.is_open(): pass self.surface.blit(self.bg, (0, 0)) self.app.repaint() self.options = gui.Button("Options", width=200, font=self.sfont) self.options.connect(gui.CLICK, dlo) self.table.tr() self.table.td(self.options) self.table.tr() self.table.td(self.quit) self.game = None
def init_gui(): #themes = cfg['theme'].split(",") # themes2 = [] # for t in themes: # if t[0] == "/" or t[0] == ".": themes2.append(t) # else: themes2.append(dname+"/"+t) #gui.theme.load(themes) #gui.theme.load(['default','tools']) global top top = gui.Desktop(theme=gui.Theme([os.path.join('data','themes','default'),os.path.join('data','themes','tools')])) #top.theme.load(['default','tools']) pass
def load(self): # Create the top level widget self._app = gui.Desktop(theme = gui.Theme("media/menu/defaultTheme")) self._app.connect(gui.QUIT, self._noteWars.quit) # Create a table to organise our menu highScoreTable = gui.Table() spaceLabel = gui.Label(' | ') # Add the table header highScoreTable.tr() highScoreTable.td(gui.Label("Song")) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label("Name")) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label("Score")) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label("Date")) # Load high scores into table highScores = self._loadHighScores() for highScore in highScores: highScoreTable.tr() highScoreTable.td(gui.Label(highScore[0])) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label(highScore[1])) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label(str(highScore[2]))) highScoreTable.td(spaceLabel) highScoreTable.td(gui.Label(highScore[3])) # Add a gap highScoreTable.tr() highScoreTable.td(gui.Label(), colspan=8) # Add a back button backButton = gui.Button("Return to main menu") backButton.connect(gui.CLICK, self._displayMainMenu) highScoreTable.tr() # New table row highScoreTable.td(backButton, colspan = 8) # Add the menu to the top level widget self._app.init(highScoreTable) # Signify that the high score menu is visible self._isVisible = True
def __init__(self, width, height): """ build the application givent it's width and height """ # set logger self._l = logging.getLogger('gunconf.ui.gunapp') tmLb = 'HD' self._size = sizeHD # allocate screen if not width or not height: self._screen = pygame.display.set_mode((0, 0), FULLSCREEN) else: self._screen = pygame.display.set_mode((width, height), SWSURFACE) # disable mouse pygame.mouse.set_visible(False) pygame.event.set_blocked(pygame.MOUSEMOTION) pygame.event.set_blocked(pygame.MOUSEBUTTONUP) pygame.event.set_blocked(pygame.MOUSEBUTTONDOWN) # init joysticks pygame.joystick.init() for x in range(pygame.joystick.get_count()): jtk = pygame.joystick.Joystick(x) if 'Ultimarc Ultimarc' != jtk.get_name(): pygame.joystick.Joystick(x).init() # rollback to SD res if needed if 720 >= pygame.display.Info().current_h: self._size = sizeSD tmLb = 'SD' # create app object theme = gui.Theme( os.path.join(os.path.dirname(__file__), "../data/theme/%s" % (tmLb, ))) gui.Desktop.__init__(self, theme=theme) self._ctrl = None self._waitNbScan = 0 self.connect(gui.QUIT, self.quit, None) # init UI self._initUi()
def main_function(): # On évite PGU pour Michel if len(sys.argv) >= 4 and sys.argv[1] == "--michel": ip = sys.argv[2] port = int(sys.argv[3]) jeu(ip, port) else: app = gui.Desktop(theme=gui.Theme("data/themes/clean")) app.connect(gui.QUIT, app.quit, None) table = gui.Table() # Titre table.tr() table.td(gui.Label("Connexion au serveur"), colspan=4) # IP table.tr() table.td(gui.Label("IP :")) champ_ip = gui.Input(value="127.0.0.1", size=15) table.td(champ_ip, colspan=3) # Port d'écoute table.tr() table.td(gui.Label("Port : ")) champ_port = gui.Input(value="8888", size=5) table.td(champ_port, colspan=3) # Bouton connexion table.tr() bouton_conn = gui.Button("Connexion") table.td(bouton_conn) def lancer_jeu(valeurs): (ip, port) = valeurs jeu(ip.value, int(port.value)) sys.exit(0) bouton_conn.connect(gui.CLICK, lancer_jeu, (champ_ip, champ_port)) app.run(table)
def __init__(self): super(Menu, self).__init__(theme=gui.Theme('data/themes/clean')) self.active = True self.veil = pygame.Surface((app.screen_width, app.screen_height), pygame.SRCALPHA) self.veil.fill((0, 0, 0, 128)) # Some basic elements label_title = gui.Label('Only fighters', cls='h1', color=(255, 255, 255)) keyboard = gui.Image('data/themes/keyboard.png', align=1) button_hi = gui.Button('Hi world') button_quit = gui.Button('Quit') # Making useful the 'Quit' button button_quit.connect(gui.CLICK, quit, None) # An usage example of a poping dialog t = gui.Table(width=50, height=50) t.tr() t.td(gui.Label('Game made by Álvaro González Redondo')) t.tr() t.td(gui.Label('*****@*****.**')) t.tr() e = gui.Button("Oh. Great.") t.td(e, colspan=2) dialog = gui.Dialog(gui.Label('Hello world'), t) e.connect(gui.CLICK, dialog.close, None) button_hi.connect(gui.CLICK, dialog.open, None) # Arranging the elements of the menu menu = gui.Table(width=500, height=500) menu.tr() menu.td(label_title) menu.tr() menu.td(keyboard) menu.tr() menu.td(button_hi) menu.tr() menu.td(button_quit) # Initializes the object self.init(widget=menu)
def load_assets(screen=None): global __screen __screen = screen config_directory = get_path(_assets_config_path) config = ConfigParser() for file in list_dir(config_directory): path = get_path(_assets_config_path + file) config.read(path) for section in config.sections(): _assets_switch[config.get(section, "type")](section, dict(config.items(section))) config.clear() global theme theme = pgui.Theme(get_path("data/assets/default/")) print(music) print(texture) print(sound) print(font)
def main(): whereami = os.path.dirname(os.path.realpath(__file__)) # Parse arguments p = argparse.ArgumentParser(description="A pygame GUI for Home Assistant.") p_config = p.add_argument_group('Configuration') p_config.add_argument('-c', '--config', help="config file to use", required=True, type=argparse.FileType('r')) p_config.add_argument('-f', '--framebuffer', help="Use this framebuffer as output for the UI\ (defaults to window mode)", default=None, type=str, metavar="/dev/fbX") p_config.add_argument('-t', '--touchscreen', help="Enable touchscreen integration.\ Use this as event input", default=None, type=str, metavar="/dev/input/eventX") p_config.add_argument('-n', '--no-display', help="We don't have a display. Sets the\ SDL_VIDEODRIVER to \"dummy\". Usefull for testing", dest="dummy", action="store_true", default=False) p_config.add_argument('--width', help="The width of the display or window", dest="width", type=int, default=False) p_config.add_argument('--heigth', help="The height of the display or window", dest="height", type=int, default=False) p_homeassistant = p.add_argument_group( 'HomeAssistant', " (optional) Parameters to override the config file") p_homeassistant.add_argument('-H', '--homeassistant', default=None, help="The location of home-assistant", metavar="host.name") p_homeassistant.add_argument('-p', '--port', default=None, help="the port to use for home-assistant\ (default: 8123)", type=int) p_homeassistant.add_argument( '-k', '--key', default=None, help="The api password to use (default: None)", type=str) p_homeassistant.add_argument('-s', '--ssl', help="Use ssl (default false)", default=False, action="store_true") p_logging = p.add_argument_group('Logging', " (optional) Logging settings") p_logging.add_argument('-v', '--verbose', help="Log output", default=False, action="store_true") p_logging.add_argument( '-L', '--logLevel', dest="logLevel", help="Log level to use (default: ERROR)", choices=["INFO", "WARNING", "ERROR", "CRITICAL", "DEBUG"], default="ERROR", type=str) p_logging.add_argument( '-l', '--logfile', help="Instead of logging to stdout, log to this file", default=None) args = p.parse_args() # Setup logger logFormat = "%(asctime)s [%(threadName)s:%(name)s]\ [%(levelname)-5.5s] %(message)s" logFormatter = logging.Formatter(logFormat) log = logging.getLogger("HUD") log.setLevel(getattr(logging, args.logLevel.upper())) if args.verbose: if not args.logfile: consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logFormatter) log.addHandler(consoleHandler) else: fileHandler = logging.FileHandler(str(args.logfile)) fileHandler.setFormatter(logFormatter) log.addHandler(fileHandler) # Setup Home assistant config log.info("Startup: Load config") config = configparser.ConfigParser() config.read(args.config.name) print(config.sections()) try: haconfig = { "host": (args.homeassistant if args.homeassistant else config["HomeAssistant"]["Host"]), "port": (args.port if args.port else config["HomeAssistant"]["Port"]), "ssl": (args.ssl if args.ssl else config["HomeAssistant"]["SSL"]), "key": (args.key if args.key else config["HomeAssistant"]["Password"]) } except KeyError as e: log.error("Cannot find section [{}] in config file '{}'!".format( str(e), str(args.config.name))) exit(1) # Setup home assistant connection log.info("Startup: Create EventHandler") hass = remote.API(haconfig['host'], haconfig['key'], haconfig['port'], haconfig['ssl']) HAE = HAWebsocketEventHandler(settings=haconfig) try: validation = remote.validate_api(hass) if str(validation) != "ok": log.info("Startup: Successfully connected to HomeAssistant!") raise Exception(validation) except Exception as e: log.error("hass connection verification failed: {}".format( str(validation))) exit(1) # Start the EventDaemon log.info("Startup: start HAWebsocketEventHandler") HAE.start() log.info("Startup: start EventWorker") eventWorker.start(1, HAE) log.info("Startup: Setting screen") width = args.width height = args.height if args.framebuffer: log.info("Startup: Setting framebuffer") os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV', args.framebuffer) if args.touchscreen: log.info("Startup: Setting up touchscreen support") os.putenv('SDL_MOUSEDRV', 'TSLIB') os.putenv('SDL_MOUSEDEV', args.touchscreen) if args.dummy: os.putenv('SDL_VIDEODRIVER', 'dummy') if args.framebuffer: pygame_opts = FULLSCREEN | HWSURFACE | DOUBLEBUF # ^UNTESTED!^ else: pygame_opts = SWSURFACE screen = pygame.display.set_mode((width, height), pygame_opts) if args.touchscreen: # Hide the mouse cursor if we have a touchscreen pygame.mouse.set_visible(False) pygame.display.set_caption("HUD") screen.fill([200, 200, 200]) pygame.display.update() log.info("Startup: Load Theme") app = gui.Desktop(theme=gui.Theme(whereami + "/elements/pgu.theme")) app.connect(gui.QUIT, app.quit, None) timeout = 5 while timeout != 0: if HAE.authenticated: pygame_print("Connected. Loading view...", screen, 10, height / 2) break else: timeout -= 1 log.info("Waiting for connection") pygame_print("Connecting to home assistant", screen, 10, height / 2) time.sleep(1) if not HAE.authenticated: log.error("Connection failed") pygame_print("Connection failed", screen, 10, height / 2) time.sleep(2) sys.exit(1) view = renderer.renderConfig(remote.get_states(hass), width, height, config, HAE) RunPlease = True while RunPlease: try: app.run(view, screen=screen) except (KeyboardInterrupt, SystemExit): log.warning("Got Exit or Ctrl-C. Stopping.") RunPlease = False pass except AttributeError as e: log.exception(e) log.error("AttributeError, restarting") sys.exit(1) HAE.stop() eventWorker.stop() sys.exit(0)
def init_gui(): #themes = cfg['theme'].split(",") #gui.theme.load(themes) #gui.theme.load(['default','tools']) global top top = gui.Desktop(theme=gui.Theme(['default', 'tools']))
import spyral # PGU Imports from pgu import text from pgu import gui from pgu import html # System setting manipulations os.environ['SDL_VIDEO_CENTERED'] = '1' #os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (25, -75) # First Broadway Imports from auxiliary import * from constants import * pgu['theme'] = gui.Theme('libraries/pgu/gui.theme') fonts['normal'] = pygame.font.SysFont('Vera.ttf', 30) fonts['italic'] = pygame.font.SysFont('VeraIt.ttf', 30) # Last Broadway Imports import script import panel import tab import actor from recorder import Recorder class Broadway(spyral.scene.Scene): def __init__(self): """Initializes cameras""" spyral.scene.Scene.__init__(self)
def main(): env.app = gui.App(theme=gui.Theme(p("theme/default/"))) settings = gui.Image(p("icons/settings.png")) console = gui.Image(p("icons/python.png")) # settings.connect c = gui.Container(align=-1, valign=-1) c.add(console, 970, 10) c.add(settings, 960, 400) env.app.init(c, env.screen) running = True if len(sys.argv) > 1: robot = Robot(wboot=False) robot.draw() prog = sys.argv[1] robot.progLoad() robot.prog = robot.progs.index(prog) robot.screen = 3 robot.wboot = False def runner(): robot.screen_y = 3 robot.scrout() pygame.time.delay(800) robot.onCenter() RoboThread(target=runner).start() else: robot = Robot() robot.draw() clicker = Clicker() clicker.bind(((810, 252), (41, 40)), robot.onCenter) clicker.bind(((810, 308), (41, 26)), robot.onBack) clicker.bind(((751, 252), (41, 40)), robot.onLeft) clicker.bind(((870, 252), (41, 40)), robot.onRight) clicker.bind(((970, 10), (45, 45)), robot.onConsole) clicker.bind(((960, 400), (50, 50)), robot.background_dialog) # sensor binds clicker.bind(((735, 440), (19, 23)), robot.port1) clicker.bind(((795, 440), (19, 23)), robot.port2) clicker.bind(((855, 440), (19, 23)), robot.port3) clicker.bind(((915, 440), (19, 23)), robot.port4) robot.load_config('./config.yml') while running: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: clicker.process(pygame.mouse.get_pos()) if event.type == KEYDOWN: if event.mod & KMOD_CTRL: if event.key == K_h: robot.brick_hidden = not robot.brick_hidden env.check_brick() if event.key == K_d: robot.background_dialog() if event.key == K_c: robot.onConsole() if event.type == QUIT: robot.die = True running = False pygame.quit() sys.exit(0) elif event.type == MOUSEBUTTONDOWN and robot.mouseOver(): if event.button == 1: robot.dragged = not robot.dragged if robot.dragged: pygame.mouse.set_cursor(*pygame.cursors.broken_x) else: pygame.mouse.set_cursor(*pygame.cursors.arrow) if event.button == 4: robot.angle += 1 robot.angle = round(robot.angle, 0) elif event.button == 5: robot.angle -= 1 robot.angle = round(robot.angle, 0) env.app.event(event) pygame.event.pump() keystate = pygame.key.get_pressed() mod = pygame.key.get_mods() # rotate robot by keys if keystate[K_LEFT] and mod & KMOD_SHIFT: robot.angle -= 1 elif keystate[K_RIGHT] and mod & KMOD_SHIFT: robot.angle += 1 if robot.dragged: robot.draw() robot.drag() else: robot.tick() clock.tick(40) # Frame rate
pygame.display.flip() if __name__ == "__main__": # On évite PGU pour Michel if len(sys.argv) >= 4 and sys.argv[1] == "--michel": ip = sys.argv[2] port = int(sys.argv[3]) if len(sys.argv) == 5: nb = int(sys.argv[4]) else: nb = 2 MyServer(localaddr=(ip, port), nb_joueurs=nb) else: # Les autres ont le droit à une interface jolie app = gui.Desktop(title="coucou", theme=gui.Theme("data/themes/clean")) app.connect(gui.QUIT, app.quit, None) table = gui.Table() # Titre table.tr() table.td(gui.Label("Config serveur"), colspan=4) # IP du serveur table.tr() table.td(gui.Label("IP : ")) champ_ip = gui.Input(value="0.0.0.0", size=15) table.td(champ_ip, colspan=3)
def main(): global rtri, rquad, gui_screen video_flags = OPENGL | DOUBLEBUF pygame.init() pygame.display.set_mode((640, 480), video_flags) font = pygame.font.SysFont("default", 18) fontBig = pygame.font.SysFont("default", 24) fontSub = pygame.font.SysFont("default", 20) theme = pgui.Theme('test_theme'); resize((640, 480)) init() # create PanelOverlaySurface # gui_screen = lamina.LaminaPanelSurface((640,480), (-3.3, 2.5, 6.6, 5)) gui_screen = lamina.LaminaScreenSurface() gui = pgui.App(theme=theme) gui._screen = gui_screen.surf # func to toggle triangle spin def triTog(): global triOn triOn = not triOn # func to toggle quad spin def quadTog(): global quadOn quadOn = not quadOn # func to toggle zoom def zoomTog(): global zoomAngle if zoomAngle == 45: zoomAngle = 30 else: zoomAngle = 45 resize((640, 480)) gui_screen.refreshPosition() gui.repaint(gui_screen.surf) # create page # layout using document lo = pgui.Container(width=640) # create page label title = pgui.Label("Lamina Demo : PGU", font=fontBig) lo.add(title, 29, 13) # create triangle button, connect to triTog handler function, # and install in gui btn1 = pgui.Button("Stop/Start Triangle") btn1.connect(pgui.CLICK, triTog) lo.add(btn1, 120, 440) btn2 = pgui.Button("Stop/Start Quad") btn2.connect(pgui.CLICK, quadTog) lo.add(btn2, 420, 440) # create zoom button, connect to zoomTog handler function, # and install in gui btn3 = pgui.Button('Zoom') btn3.connect(pgui.CLICK, zoomTog) lo.add(btn3, 300, 440) gui.init(lo) frames = 0 ticks = pygame.time.get_ticks() while 1: event = pygame.event.poll() if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): break # handle gui events and raster updating gui.event((event)) chg = gui.update(gui_screen.surf) if chg: gui_screen.refresh(chg) # draw all objects draw() # update rotation counters if triOn: rtri += 0.2 if quadOn: rquad += 0.2 # make changes visible pygame.display.flip() frames = frames + 1 print "fps: %d" % ((frames * 1000) / (pygame.time.get_ticks() - ticks))
''' Simple example showing: - Change to a custom theme. - Using Table widget to arrange the menu. ''' from pgu import gui if __name__ == '__main__': # Creating an App app = gui.Desktop(theme=gui.Theme('clean')) # Creating the widgets label1 = gui.Label('Mi super juego') #label1.background = gui.Color((255,255,255), width=100,height=100) button1 = gui.Button('Testing') button2 = gui.Button('Quit') # Adding widgets to a container container = gui.Table(width=500, height=500) container.tr() container.td(label1) container.tr() container.td(button1) container.tr() container.td(gui.Spacer(10, 50)) container.tr() container.td(button2) # Enabling quit, connecting the "quit" button's click event to the app's quit function. button2.connect(gui.CLICK, app.quit, None)
def main(): whereami = os.path.dirname(os.path.realpath(__file__)) # Parse arguments p = argparse.ArgumentParser(description="A pygame GUI for Home Assistant.") p_config = p.add_argument_group('Configuration') p_config.add_argument('-c','--config',help="config file to use",required=True,type=argparse.FileType('r')) p_config.add_argument('-f','--framebuffer',help="Use this framebuffer as output for the UI (defaults to window mode)", default=None,type=str,metavar="/dev/fbX") p_config.add_argument('-t','--touchscreen',help="Enable touchscreen integration. Use this as event input", default=None,type=str,metavar="/dev/input/eventX") p_config.add_argument('-n','--no-display',help="We don't have a display. Sets the SDL_VIDEODRIVER to \"dummy\". Usefull for testing",dest="dummy",action="store_true", default=False) p_homeassistant = p.add_argument_group('HomeAssistant'," (optional) Parameters to override the config file") p_homeassistant.add_argument('-H','--homeassistant',default=None,help="The location of home-assistant",metavar="host.name") p_homeassistant.add_argument('-p','--port',default=None,help="the port to use for home-assistant (default: 8123)",type=int) p_homeassistant.add_argument('-k','--key',default=None,help="The api password to use (default: None)",type=str) p_homeassistant.add_argument('-s','--ssl',help="Use ssl (default false)",default=False,action="store_true") p_logging = p.add_argument_group('Logging'," (optional) Logging settings") p_logging.add_argument('-v','--verbose',help="Log output",default=False,action="store_true") p_logging.add_argument('-L','--logLevel',dest="logLevel",help="Log level to use (default: ERROR)",choices=["INFO","WARNING","ERROR","CRITICAL","DEBUG"],default="ERROR",type=str) p_logging.add_argument('-l','--logfile',help="Instead of logging to stdout, log to this file",default=None) args = p.parse_args(); # Setup logger logFormatter = logging.Formatter("%(asctime)s [%(threadName)s:%(name)s] [%(levelname)-5.5s] %(message)s") log = logging.getLogger("HUD") log.setLevel(getattr(logging, args.logLevel.upper())) if args.verbose: if not args.logfile: consoleHandler = logging.StreamHandler(sys.stdout) consoleHandler.setFormatter(logFormatter) log.addHandler(consoleHandler) else: fileHandler = logging.FileHandler(str(args.logfile)) fileHandler.setFormatter(logFormatter) log.addHandler(fileHandler) # Setup Home assistant config log.info("Startup: Load config") config = configparser.ConfigParser() config.read(args.config.name) print((config.sections())) try: haconfig = { "host" : (args.homeassistant if args.homeassistant else config["HomeAssistant"]["Host"]), "port" : (args.port if args.port else config["HomeAssistant"]["Port"]), "ssl" : (args.ssl if args.ssl else config["HomeAssistant"]["SSL"]), "key": (args.key if args.key else config["HomeAssistant"]["Password"]) } except KeyError as e: log.error("Cannot find section [{}] in config file '{}'!".format(str(e),str(args.config.name))) exit(1) # Setup home assistant connection log.info("Startup: Create EventHandler") hass = remote.API(haconfig['host'],haconfig['key'],haconfig['port'],haconfig['ssl']) HAE = HAEventHandler(hass,settings=haconfig) try: validation = remote.validate_api(hass) if str(validation) != "ok": log.info("Startup: Successfully connected to HomeAssistant!") raise Exception(validation) except Exception as e: log.error("hass connection verification failed: {}".format(str(validation))) exit(1) log.info("Startup: Setting screen") if args.framebuffer: log.info("Startup: Setting framebuffer") os.putenv('SDL_VIDEODRIVER', 'fbcon') os.putenv('SDL_FBDEV' , args.framebuffer) if args.touchscreen: log.info("Startup: Setting up touchscreen support") os.putenv('SDL_MOUSEDRV' , 'TSLIB') os.putenv('SDL_MOUSEDEV' , args.touchscreen) if args.dummy: os.putenv('SDL_VIDEODRIVER', 'dummy') if args.framebuffer: pygame_opts = FULLSCREEN | HWSURFACE | DOUBLEBUF # ^UNTESTED!^ else: pygame_opts = SWSURFACE screen = pygame.display.set_mode((320,480),pygame_opts) if args.touchscreen: ## Hide the mouse cursor if we have a touchscreen pygame.mouse.set_visible(False) log.info("Startup: Load Theme") app = gui.Desktop(theme=gui.Theme(whereami+"/pgu.theme")) app.connect(gui.QUIT,app.quit,None) container=gui.Table(width=230,vpadding=0, hpadding=0) for section in config.sections(): if section != "HomeAssistant": log.info("Startup: Loading section {}".format(str(section))) c = container c.tr() state = remote.get_state(hass,"group.{}".format(str(config[section]["group"]))) header = elements.rowHeader(hass,state,table=c) HAE.add_listener(state.entity_id,header.set_hass_event) c.td(header.draw(),align=-1) c.tr() if state == None: log.warning("Startup: Unable to find group.{}".format(str(config[section]["group"]))) c.td(gui.Label("Startup: Unable to find group.{}".format(str(config[section]["group"])))) else: log.info("Startup: Fetching entity statusses") # get all states from entities & add to the list if entity is not None (eg. not found) entities = [e for e in [remote.get_state(hass,eid) for eid in state.attributes['entity_id']] if e != None] for entity in entities: log.info("Startup: Loading entity {}".format(entity.entity_id)) # Changeable, lights are hmmMMmmm if (entity.domain == "light"): row = elements.rowLight(hass,entity,last=(True if entity == entities[-1] else False),table=c) log.info("Startup: Adding Event listener for {}".format(entity.entity_id)) HAE.add_listener(entity.entity_id,row.set_hass_event) #row.draw() c.td(row.draw(),align=-1) elif (entity.domain in ('sensor','device_tracker')): # widget = gui.Label("{} : {}".format(str(entity.name),str(entity.state))) # c.td(widget) row = elements.rowSensor(hass,entity,last=(True if entity == entities[-1] else False)) log.info("Startup: Adding Event listener for {}".format(entity.entity_id)) HAE.add_listener(entity.entity_id,row.set_hass_event) c.td(row.draw(),align=-1) c.tr() container.td(gui.Spacer(height=4,width=320)) log.info("Startup: Load elements onto surface") main = gui.Container(width=320,height=480) header = elements.Header("Home Assistant",width=320,height=40) main.add(header,0,0) main.add(container,0,60) # Start the EventDaemon log.info("Startup: start HAEventHandler") HAE.start() RunPlease = True while RunPlease: try: log.info("Start screen") app.run(main,screen=screen ) except (KeyboardInterrupt, SystemExit): log.warning("Got Exit or Ctrl-C. Stopping.") RunPlease = False pass except AttributeError as e: log.error("AttributeError, restarting") pass HAE.stop() sys.exit(0)
""" import pygame from pygame.locals import * # the following line is not needed if pgu is installed import sys sys.path.insert(0, "..") from pgu import gui # Load an alternate theme to show how it is done. You can also # specify a path (absolute or relative) to your own custom theme: # # app = gui.Desktop(theme=gui.Theme("path/to/theme")) # app = gui.Desktop(theme=gui.Theme("./data/themes/default")) app.connect(gui.QUIT, app.quit, None) ##:: WIDTH = 640 HEIGHT = 320 ctn = gui.Container() ctn.add(gui.Label("ZScripts path:"), 5, 0) def cb(): print("Input received") pathInput = gui.Input(value='', size=90)
# env.background.fill((255, 255, 255)) # pygame.display.set_caption("nxtemu") # #background.blit(pygame.image.load("./icons/brick.jpg").convert(), (640, 0)) # env.background.blit(imgs.brick.convert(), (640, 0)) # pygame.draw.rect(env.background, pygame.Color("gray"), ((0, 0), (646, 486))) # pygame.draw.rect(env.background, pygame.Color("white"), ((3, 3), (640, 480))) # background.blit(pygame.image.load("settings.png").convert_alpha(), (970, 400)) #background.blit(pygame.image.load("./line.jpg"), (3, 3)) clock = pygame.time.Clock() if __name__ == "__main__": env.app = gui.App(theme=gui.Theme(p("theme/default/"))) settings = gui.Image(p("icons/settings.png")) # settings.connect c = gui.Container(align=-1, valign=-1) c.add(settings, 960, 400) env.app.init(c, env.screen) running = True if len(sys.argv) > 1: robot = Robot(wboot=False) robot.draw() prog = sys.argv[1] robot.progLoad() #print robot.progs
def load(self): # Create the top level widget self._app = gui.Desktop(theme=gui.Theme("media/menu/defaultTheme")) self._app.connect(gui.QUIT, self._noteWars.quit) # Create a table to organise our menu menuTable = gui.Table() # Add the title banner bannerImage = gui.Image('media/menu/NoteWarsLogo.png') menuTable.tr() # New table row menuTable.td(bannerImage) # Add author information sentenceWordLength = 10 aboutText = 'A game by Fahmi for WoGaDeMo 2013' self._displayText(menuTable, aboutText, 10) # Add a gap self._displayText(menuTable, '', 10) # Add instruction information instText = 'Use WASD to move your ship and your mouse to aim. Press backspace to go back to this menu. Your ship fires with the music. Your enemies spawn with the music.' self._displayText(menuTable, instText, 10) # Add a gap self._displayText(menuTable, '', 10) # Add button to play a song song1Button = gui.Button("Play Song: Battlefield1942") song1Button.connect(gui.CLICK, self._noteWars.goPlayGameRound, 'media/music/battlefield1942') menuTable.tr() # New table row menuTable.td(song1Button) # Add button to play a song song2Button = gui.Button("Play Song: Morrowind Dance Mix") song2Button.connect(gui.CLICK, self._noteWars.goPlayGameRound, 'media/music/morrowind_dance_mix') menuTable.tr() # New table row menuTable.td(song2Button) # Add button to play a song song3Button = gui.Button("Play Song: Deus Ex Theme") song3Button.connect(gui.CLICK, self._noteWars.goPlayGameRound, 'media/music/Deus_Ex_Theme') menuTable.tr() # New table row menuTable.td(song3Button) # Add button to view high scores highScoresButton = gui.Button("High Scores") highScoresButton.connect(gui.CLICK, self.displayHighScores) menuTable.tr() # New table row menuTable.td(highScoresButton) # Add button to quit quitButton = gui.Button("Quit Game") quitButton.connect(gui.CLICK, self._noteWars.quit) menuTable.tr() # New table row menuTable.td(quitButton) # Add the menu to the top level widget self._app.init(menuTable) # Signify that the main menu is visible self._isVisible = True
def make_gui(): global pb, font, textArea, lines font = pygame.font.SysFont("default", 18) fontBig = pygame.font.SysFont("default", 24) fontSub = pygame.font.SysFont("default", 20) theme = pgui.Theme('test_theme') # create GUI object gui = pgui.App(theme=theme) textArea = pygame.Rect(390, 20, 250, 320) # layout using document lo = pgui.Container(width=screenSize[0]) # create page label # lo.block(align=-1) #lo.br(8) #lo.tr() title = pgui.Label("Pygame GUI Test Page - PGU", font=fontBig) lo.add(title, 29, 13) # create progress bar label # progress bar pbl = pgui.Label('Progress Bar') lo.add(pbl, 354, 351) pb = pgui.ProgressBar(10, 0, 100, width=200) lo.add(pb, 354, 371) # create checkbuttons and add to gui cbt = pgui.Table() cb1 = pgui.Switch() cb1.connect(pgui.CHANGE, logCheckAction, (cb1, "Check Box 1")) cb1l = pgui.Label("Check Box 1") cbt.add(cb1) cbt.add(cb1l) cbt.tr() cb2 = pgui.Switch() cb2.connect(pgui.CHANGE, logCheckAction, (cb2, "Check Box 2")) cb2l = pgui.Label("Check Box 2") cbt.add(cb2) cbt.add(cb2l) cbt.tr() cb3 = pgui.Switch() cb3.connect(pgui.CHANGE, logCheckAction, (cb3, "Check Box 3")) cb3l = pgui.Label("Check Box 3") cbt.add(cb3) cbt.add(cb3l) lo.add(cbt, 52, 52) # create radio buttons, put in table, and add to gui rbt = pgui.Table() radio = pgui.Group() rb1 = pgui.Radio(radio, 1) rb1l = pgui.Label("Radio Button 1") rbt.add(rb1) rbt.add(rb1l) rbt.tr() rb2 = pgui.Radio(radio, 2) rb2l = pgui.Label("Radio Button 2") rbt.add(rb2) rbt.add(rb2l) rbt.tr() rb3 = pgui.Radio(radio, 3) rb3l = pgui.Label("Radio Button 3") rbt.add(rb3) rbt.add(rb3l) rbt.tr() lo.add(rbt, 210, 52) radio.connect(pgui.CHANGE, logRadioAction, (radio, "Radio Button 3")) # create txt box label txtl = pgui.Label("Text Box", font=fontSub) lo.add(txtl, 30, 127) # create text box txt = pgui.Input("next line of input", size=40) txt.connect(pgui.BLUR, logInputAction, txt) lo.add(txt, 28, 149) # add buttons, both regular and toggle btn1 = pgui.Button("Button 1") btn1.connect(pgui.CLICK, logButtonAction, ("Button 1 clicked")) lo.add(btn1, 36, 250) btn2 = pgui.Button("Button 2") btn2.connect(pgui.CLICK, logButtonAction, ("Button 2 clicked")) lo.add(btn2, 133, 250) btn3 = pgui.Button("Button 3") btn3.connect(pgui.CLICK, logButtonAction, ("Button 3 clicked")) lo.add(btn3, 230, 250) # create toggle button not avail label tbl = pgui.Label("Toggle Buttons Not Supported") lo.add(tbl, 36, 290) img = pgui.Image("clear.png") img.connect(pgui.CLICK, logImg) # iml = pgui.Label("Image Map Not Supported") lo.add(img, 36, 340) # create slider label sll = pgui.Label("Slider", font=fontSub) lo.add(sll, 36, 195) # create slider sl = pgui.HSlider(value=1, min=0, max=100, size=32, width=200, height=16) sl.connect(pgui.CHANGE, logSliderAction, sl) lo.add(sl, 53, 210) # , colspan=3) # make some insensitive btn2.disabled = True cb3.disabled = True # clear setup noise, and put initial content in lines = [] lines.append('top line of input') lines.append('second line of input') progBar(pb, lines) # update progress bar for above two items gui.init(lo) return gui
COLORS = [COLOR1, COLOR2, COLOR3, COLOR4, COLOR5] NEW_BOARDS_EASY = 3 NEW_BOARDS_MED = 3 NEW_BOARDS_HARD = 3 NEW_BOARDS_SUPER = 3 #-------------------------------------------------------------------- #Variables #-------------------------------------------------------------------- #Screen screen_size = (1024, 600) screen_center = (screen_size[0] / 2, screen_size[1] / 2) gui_theme = gui.Theme("assets/images/gui/themes/default") #Rooms room = LOADING_SCREEN all_highs = high.Highs('high_scores.txt') current_highs = high.Highs('high_scores.txt')['time_challenge_med'] #Game board_size = BOARD_LARGE map_size = (520, 520) fill_board = 0 use_darkness = 1 paused = False #Game Modes game_mode = TIME_CHALLENGE