def init(): args = sys.argv.copy() options = [] while len(args) > 1: # args[0] = script name arg = args.pop() if (arg == "--debug") or (arg == "-d"): options.append("debug") print( "[LPHK] Debugging mode active! Will not shut down on window close." ) print( "[LPHK] Run shutdown() to manually close the program correctly." ) elif arg == "--autoconnect": options.append("autoconnect") elif arg.startswith("--layout="): options.append("loadlayout") options.insert(0, arg[9:]) else: print("[LPHK] Invalid argument: " + arg + ". Ignoring...") files.init(PATH) sound.init(PATH) return options
def setup(self): """Initialize pygame, find the main game file and parse it.""" #initialise pygame pygame.init() #find the main game file and parse it if settings.path is not None: fn = os.path.join(settings.path, "data", "game.xml") else: raise error.DittoInvalidResourceException("settings.py", "path") root = data.getTreeRoot(fn, "Ditto Main") for p in data.getChildren(root, "property"): if data.getAttr(p, "name", data.D_STRING) == "tilesize": globs.TILESIZE = data.getAttr(p, "value", data.D_INT2LIST) elif data.getAttr(p, "name", data.D_STRING) == "font": globs.FONT = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "dialog": globs.DIALOG = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "pokemon": globs.POKEMON = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "soundeffects": soundPath = os.path.join( settings.path, "data", data.getAttr(p, "value", data.D_STRING)) elif data.getAttr(p, "name", data.D_STRING) == "moves": globs.MOVES = os.path.join( settings.path, "data", data.getAttr(p, "value", data.D_STRING)) elif data.getAttr(p, "name", data.D_STRING) == "behaviours": globs.BEHAVIOURS = os.path.join( settings.path, "data", data.getAttr(p, "value", data.D_STRING)) #if there's an icon specified, use it if len(data.getChildren(root, "icon")) > 0: node = data.getChild(root, "icon") iconPath = os.path.join(settings.path, "data", data.getAttr(node, "file", data.D_STRING)) icon = data.getImage(iconPath, fn) pygame.display.set_icon(icon) #set up the main window windowSize = settings.screenSize[0] * globs.TILESIZE[ 0], settings.screenSize[1] * globs.TILESIZE[1] self.screen = pygame.display.set_mode(windowSize) pygame.display.set_caption("%s --- Ditto Engine" % data.getAttr(root, "title", data.D_STRING)) #create a clock object self.clock = pygame.time.Clock() #initialise sound sound.init(soundPath) #set up the initial scene, the intro self.activeScene = intro.Intro(self.screen)
def init(): global EXIT_ON_WINDOW_CLOSE if len(sys.argv) > 1: if ("--debug" in sys.argv) or ("-d" in sys.argv): EXIT_ON_WINDOW_CLOSE = False print("[LPHK] Debugging mode active! Will not shut down on window close.") print("[LPHK] Run shutdown() to manually close the program correctly.") else: print("[LPHK] Invalid argument: " + sys.argv[1] + ". Ignoring...") files.init(PATH) sound.init(PATH)
def setup(self): """Initialize pygame, find the main game file and parse it.""" #initialise pygame pygame.init() #find the main game file and parse it if settings.path is not None: fn = os.path.join(settings.path, "data", "game.xml") else: raise error.DittoInvalidResourceException("settings.py", "path") root = data.getTreeRoot(fn, "Ditto Main") for p in data.getChildren(root, "property"): if data.getAttr(p, "name", data.D_STRING) == "tilesize": globs.TILESIZE = data.getAttr(p, "value", data.D_INT2LIST) elif data.getAttr(p, "name", data.D_STRING) == "font": globs.FONT = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "dialog": globs.DIALOG = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "pokemon": globs.POKEMON = data.getAttr(p, "value", data.D_STRING) elif data.getAttr(p, "name", data.D_STRING) == "soundeffects": soundPath = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING)) elif data.getAttr(p, "name", data.D_STRING) == "moves": globs.MOVES = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING)) elif data.getAttr(p, "name", data.D_STRING) == "behaviours": globs.BEHAVIOURS = os.path.join(settings.path, "data", data.getAttr(p, "value", data.D_STRING)) #if there's an icon specified, use it if len(data.getChildren(root, "icon")) > 0: node = data.getChild(root, "icon") iconPath = os.path.join(settings.path, "data", data.getAttr(node, "file", data.D_STRING)) icon = data.getImage(iconPath, fn) pygame.display.set_icon(icon) #set up the main window windowSize = settings.screenSize[0]*globs.TILESIZE[0], settings.screenSize[1]*globs.TILESIZE[1] self.screen = pygame.display.set_mode(windowSize) pygame.display.set_caption("%s --- Ditto Engine" % data.getAttr(root, "title", data.D_STRING)) #create a clock object self.clock = pygame.time.Clock() #initialise sound sound.init(soundPath) #set up the initial scene, the intro self.activeScene = intro.Intro(self.screen)
def prepare_console(): """ Initialise backend and console. """ import state import backend import display import sound import console # we need this prepared for input to work, # even if we don't use any function from it import inputs interface = config.get('interface') or 'graphical' display.init(interface) sound.init('none' if config.get('nosound') else interface) if not state.loaded: console.init_mode() return backend, console
def build_world(): gfw.world.init(['bg', 'ui']) center = (canvas_width // 2, canvas_height // 2) bg = gobj.ImageObject('title.png', center) gfw.world.add(gfw.layer.bg, bg) font = gfw.font.load(gobj.res('Sam3KRFont.ttf'), 40) l, b, w, h = 500, 250, get_canvas_width() - 1000, 80 btn = Button(l, b, w, h, font, "Start", lambda: start()) gfw.world.add(gfw.layer.ui, btn) b -= 100 btn = Button(l, b, w, h, font, "Option", lambda: option()) gfw.world.add(gfw.layer.ui, btn) sound.init() sound.bgm_title.repeat_play()
def init(): global EXIT_ON_WINDOW_CLOSE global DEFAULT_LOAD_FILE if args["debug"] is True: EXIT_ON_WINDOW_CLOSE = False print( "[LPHK] Debugging mode active! Will not shut down on window close." ) print("[LPHK] Run shutdown() to manually close the program correctly.") if args["load"] is not None: DEFAULT_LOAD_FILE = args["load"] files.init(USER_PATH) sound.init(USER_PATH)
def __init__(self, save): pygame.display.set_icon(pygame.image.load(resource_path("assets/icon_2_256.png"))) pygame.mixer.pre_init(buffer=512) pygame.init() self.save = save self.scaled_screen = pygame.display.set_mode((RES[0] * SCALE, RES[1] * SCALE)) pygame.display.set_caption("Picket Puzzle") sound.init() self.screen = pygame.Surface(RES) if len(sys.argv) > 1 and DEV: if sys.argv[1] == 'credits': self.scene = creditsscene.CreditsScene(self) else: self.scene = levelscene.LevelScene(self, sys.argv[1]) else: self.scene = alphascene.AlphaScene(self) self.playing_level_index = None self.vignette = simplesprite.SimpleSprite("assets/vignette.png", (0,0))
def enter(): gfw.world.init(['bg', 'ui']) center = (canvas_width // 2, canvas_height // 2) sound.init() if gobj.IS_VICTORY: bg = gobj.ImageObject('victory.png', center) sound.se_victory.play() else: bg = gobj.ImageObject('defeat.png', center) sound.se_defeat.play() gfw.world.add(gfw.layer.bg, bg) global font font = gfw.font.load(gobj.res('Sam3KRFont.ttf'), 35) global l, b, w, h l, b, w, h = 50, 100, get_canvas_width() - 100, 80 btn = Button(l, b, w, h, font, "Back to Title", lambda: back_to_title()) gfw.world.add(gfw.layer.ui, btn)
def init(): syscmd("jack_control start") # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) sensors.init() devices.init() #controls init must be after devices and sensors, because it using them controls.init() controls.set_telegram_warning_handle(send_warning_telegram) sound.init() # must be after controls # arguments parser = argparse.ArgumentParser() parser.add_argument("--time") parser.add_argument("--check_water_level", action='store_true') args = parser.parse_args() if args.time: config.DEF_TIME_WATER_S = int(args.time) #just check water level if args.check_water_level: my_logging.logger.info( "water level: " + ("ok" if check_water_level() else "low")) exit() my_logging.logger.info("this is "+socket.gethostname()+" and we will run server and telegram bot") web_server.run(__name__) start_bot() status=devices.get_status_str()+sensors.get_status_str()+controls.get_status_str() my_logging.logger.info(status) TTS.init() # this must be before STT # sopare_plugin.init() STT.init() # this must be at the end watch_thread.init() my_logging.logger.info("end init")
def init(): #Temperature use Analog pin 1 temperature.init() #LED use Digital pin 13 led.init() #Light is on I2C, doesn't use a specific pin light.init() #Sound uses A0 Grove Port sound.init() #LCD is on I2C, doesn't use a specific pin lcd.init() lcd.setRGB(0,255,0) #Air Quality is on Analog Pin 1 air_quality.init() #Led bar is on pin D8, uses pin 8 and 9 led_bar.init()
def init(): global EXIT_ON_WINDOW_CLOSE ap = argparse.ArgumentParser() # argparse makes argument processing easy ap.add_argument( # reimnplementation of debug (-d or --debug) "-d", "--debug", help = "Turn on debugging mode", action="store_true") ap.add_argument( # option to automatically load a layout "-l", "--layout", help = "Load an initial layout", type=argparse.FileType('r')) ap.add_argument( # option to start minimised "-m", "--minimised", help = "Start the application minimised", action="store_true") ap.add_argument( # option to start without connecting to a Launchpad "-s", "--standalone", help = "Operate without connection to Launchpad", type=str, choices=[LP_MK1, LP_MK2, LP_MINI, LP_PRO]) ap.add_argument( # option to start with launchpad window in a particular mode "-M", "--mode", help = "Launchpad mode", type=str, choices=[LM_EDIT, LM_MOVE, LM_SWAP, LM_COPY, LM_RUN], default=LM_EDIT) ap.add_argument( # turn of unnecessary verbosity "-q", "--quiet", help = "Disable information popups", action="store_true") ap.add_argument( # make button text variable in size (default is small) "-f", "--fit", help = "Make short button text fit the button", action="store_true") global_vars.ARGS = vars(ap.parse_args()) # store the arguments in a place anything can get to if global_vars.ARGS['debug']: EXIT_ON_WINDOW_CLOSE = False print("[LPHK] Debugging mode active! Will not shut down on window close.") print("[LPHK] Run shutdown() to manually close the program correctly.") files.init(USER_PATH) sound.init(USER_PATH) global LP LP = Launchpad()
def build_world(): gobj.IS_VICTORY = False gobj.SCORE = 0 gobj.KILLED_ENEMY = 0 gobj.PICKED_GOLD = 0 gobj.CONSUMED_GOLD = 0 gobj.DIFFICULTY_NOW = gobj.DIFFICULTY gfw.world.init(['bg', 'any', 'ui']) Player.load_all_images() global player player = Player() player.reset_delta() gfw.world.add(gfw.layer.any, player) bg = Background('Sprites/Backgrounds/stage1/spr_bkg_stage1.png') gfw.world.add(gfw.layer.bg, bg) ui = UIFrame(player) gfw.world.add(gfw.layer.ui, ui) generate_wall() global WC WC = WaveControl(ui, gobj.DIFFICULTY) global UC UC = UpgradeControl(ui, player) sound.init() sound.bgm_ingame.repeat_play()
def __init__(self, save): Game.inst = self self.debug_console = False global DEV #pygame.display.set_icon(pygame.image.load(resource_path("assets/icon_2_256.png"))) pygame.mixer.pre_init(buffer=256) pygame.init() self.save = save self.achievements = achievements.Achievements(self.save) self.intel = IntelManager(self.save) resolution = self.save.get_setting("resolution") if resolution == None: resolution = (1200,800) self.save.set_setting("resolution", resolution) self.save.save() self.set_resolution(V2(*resolution), self.save.get_setting("fullscreen")) pygame.display.set_caption("Hostile Quadrant") sound.init() text.preload() self.joysticks = [pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count())] self.last_joy_axes = None try: self.run_info = self.save.get_run_state() if not DEV and self.run_info.anticheat_level_started: self.run_info.no_score = True self.save.set_run_state(self.run_info) self.save.save() except Exception as e: print(e) self.run_info = run.RunInfo() self.input_mode = self.INPUT_MOUSE self.player_inputs = [] self.threads = {} self.thread_return_values = {} self.thread_index = 0 if len(sys.argv) > 1: DEV = True if sys.argv[1] == "draw": self.scene = buildingcreatorscene.BuildingCreatorScene(self) elif sys.argv[1] == "editor": self.scene = leveleditorscene.LevelEditorScene(self) elif sys.argv[1] == "star": self.run_info = run.RunInfo() self.scene = starmapscene.StarMapScene(self) elif sys.argv[1] == "upgrades": self.scene = allupgradesscene.AllUpgradesScene(self) elif sys.argv[1] == "tutorial": self.scene = tutorial.tutorial1scene.Tutorial1Scene(self) elif sys.argv[1] == "game": self.scene = levelscene.LevelScene(self, "cross", "alien2", 6, 6, "Testing", "This is a test string for the description") elif sys.argv[1] == "boss": self.scene = levelscene.LevelScene(self, "boss2", "boss", 9, 9, "Boss", "It's the boss") elif sys.argv[1] == "planet": self.scene = planetgenscene.PlanetGenScene(self) elif sys.argv[1] == "new": self.scene = newgamescene.NewGameScene(self) elif sys.argv[1] == "perf": self.scene = levelscene.LevelScene(self, "choke", "alien3", 3, 3, "", "", options='performance') elif sys.argv[1] == "flowfield": self.scene = levelscene.LevelScene(self, "cross", "alien3", 1, 1, "", "", options='flowfield') elif sys.argv[1] == "multiplayer": # self.player_inputs = [ # playerinput.Player(0, playerinput.Player.INPUT_MOUSE), # playerinput.Player(1, playerinput.Player.INPUT_JOYSTICK, 0), # playerinput.Player(2, playerinput.Player.INPUT_JOYSTICK, 1), # playerinput.Player(3, playerinput.Player.INPUT_JOYSTICK, 2) # ] # self.input_mode = self.INPUT_MULTIPLAYER # self.scene = multiplayerscene.MultiplayerScene(self, 4) self.scene = multiplayermenu.MultiplayerMenu(self) else: self.scene = menuscene.MenuScene(self) else: self.scene = menuscene.MenuScene(self) #self.scene = introscene.IntroScene(self) self.playing_level_index = None self.game_speed_input = 0 self.last_joystick_pos = defaultdict(lambda:self.game_resolution / 2) self.menu_bg_cache_obj = None self.first_load = True self.frame_time = 0 self.frame_times = [] self.scale_mode = "xbr" self.fps_limited_pause = False self._profiling = False self._profile_start_time = 0 self._profiler = None
pygame.display.flip() def start_connection(): ws = websocket.WebSocketApp(server_address, on_message = on_message, on_error = on_error, on_close = on_close) thread.start_new_thread(ws.run_forever, ()) return ws if __name__ == "__main__": try: LOG_FILENAME = 'example.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) render_obj = init_graphics() sound.init() ws = start_connection() t = 0 while running: while time.time() - t < time_fraction: pass t = time.time() events(ws) render(render_obj) except Exception, ex: print("Fatal error!", ex) terminate(ws)
def prepare_console(): """ Initialise backend and console. """ import state import backend import sound # load backend modules # this can't be done in backend.py as it would create circular dependency import console import error import fp # we need this prepared for input to work, # even if we don't use any function from it import redirect # hack: mark modules for inclusion by pyinstaller # see https://groups.google.com/forum/#!topic/pyinstaller/S8QgHXiGJ_A if False: import video_none import video_curses import video_ansi import video_cli import video_pygame import audio_none import audio_beep import audio_pygame backends = { 'none': ('video_none', 'audio_none'), 'cli': ('video_cli', 'audio_beep'), 'text': ('video_curses', 'audio_beep'), 'ansi': ('video_ansi', 'audio_beep'), 'graphical': ('video_pygame', 'audio_pygame'), } if not config.get('interface'): config.options['interface'] = 'graphical' # select interface video_name, audio_name = backends[config.get('interface')] # initialise video backend before console while True: try: # __name__ global is needed when calling from setuptools package video = __import__(video_name, globals={"__name__": __name__}) except ImportError as e: video = None if not video: if not video_name or video_name == 'video_none': logging.error('Failed to initialise interface.') raise error.Exit() logging.error('Could not load module %s.', video_name) video_name = 'video_none' continue if backend.init_video(video): break else: video_name = video.fallback if video: video.close() if video_name: logging.info('Falling back to %s interface.', video_name) if config.get('nosound'): sound.audio = __import__('audio_none', globals={"__name__": __name__}) else: sound.audio = __import__(audio_name, globals={"__name__": __name__}) if not sound.init(): sound.audio = __import__('audio_none', globals={"__name__": __name__}) sound.init() logging.warning('Failed to initialise sound. Sound will be disabled.\r') if not state.loaded: console.init_mode() # set the output for maths error messages fp.init(error_stream=console) return backend, console
# create etc object # this holds all the data (mode and preset names, knob values, midi input, sound input, current states, etc...) # it gets passed to the modes which use the audio midi and knob values etc = etc_system.System() # load shift params from file etc.recall_shift_params() # just to make sure etc.clear_flags() # setup osc and callbacks osc.init(etc) # setup alsa sound sound.init(etc, AOUT_NORNS) # init pygame, this has to happen after sound is setup # but before the graphics stuff below pygame.init() clocker = pygame.time.Clock() # for locking fps print "pygame version " + pygame.version.ver # on screen display and other screen helpers osd.init(etc) osc.send("/led", 7) # set led to running # init fb and main surfaces print "opening frame buffer..." #os.putenv('SDL_VIDEODRIVER', "directfb")
# Copyright (C) 2003-2005 Michael J. Kahana # Authors: Ian Schleifer, Per Sederberg, Aaron Geller, Josh Jacobs # URL: http://memory.psych.upenn.edu/programming/pyepl # # Distributed under the terms of the GNU Lesser General Public License # (LGPL). See the license.txt that came with this file. import sound import time import Numeric import struct secs = 5 formatsize = 2 sound.init(60, 2) print "Recording for %d seconds..." % secs sound.recstart() time.sleep(secs) sound.recstop() s = sound.consume(secs * 44100 * 2) # duplicate it print sound.getRecChans() if sound.getRecChans() == 1: buff = Numeric.array(struct.unpack(str(len(s) / formatsize) + 'h', s), typecode=Numeric.Int16) xbuff = Numeric.zeros((len(buff) * 2), typecode=Numeric.Int16)
import os print "starting..." # create etc object # this holds all the data (mode and preset names, knob values, midi input, sound input, current states, etc...) # it gets passed to the modes which use the audio midi and knob values etc = etc_system.System() # just to make sure etc.clear_flags() # setup osc and callbacks osc.init(etc) # setup alsa sound sound.init(etc) # init pygame, this has to happen after sound is setup # but before the graphics stuff below pygame.init() clocker = pygame.time.Clock() # for locking fps print "pygame version " + pygame.version.ver # on screen display and other screen helpers osd.init(etc) osc.send("/led", 7) # set led to running # init fb and main surfaces print "opening frame buffer..." #os.putenv('SDL_VIDEODRIVER', "directfb")
import tkinter as tk from tkinter import Tk, Canvas from entity import entity, vector import sound import images import world import background window = Tk() window.attributes('-fullscreen', True) # Initialisation de sound images et world sound.init() images.init() world.init() window.title("SpaceShooter") # Récupération de la taille de l'écran de l'utilisateur width = window.winfo_screenwidth() height = window.winfo_screenheight() # Création de la fenêtre principale can = Canvas(window, height = height, width = width) can.pack() can.focus_set() background.init(can, window)
def prepare_console(): """ Initialise backend and console. """ import state import backend import sound # load backend modules # this can't be done in backend.py as it would create circular dependency import console import error import fp # we need this prepared for input to work, # even if we don't use any function from it import redirect # hack: mark modules for inclusion by pyinstaller # see https://groups.google.com/forum/#!topic/pyinstaller/S8QgHXiGJ_A if False: import video_none import video_curses import video_ansi import video_cli import video_pygame import audio_none import audio_beep import audio_pygame backends = { 'none': ('video_none', 'audio_none'), 'cli': ('video_cli', 'audio_beep'), 'text': ('video_curses', 'audio_beep'), 'ansi': ('video_ansi', 'audio_beep'), 'graphical': ('video_pygame', 'audio_pygame'), } if not config.get('interface'): config.options['interface'] = 'graphical' # select interface video_name, audio_name = backends[config.get('interface')] # initialise video backend before console while True: try: # __name__ global is needed when calling from setuptools package video = __import__(video_name, globals={"__name__": __name__}) except ImportError as e: video = None if not video: if not video_name or video_name == 'video_none': logging.error('Failed to initialise interface.') raise error.Exit() logging.error('Could not load module %s.', video_name) video_name = 'video_none' continue if backend.init_video(video): break else: video_name = video.fallback if video: video.close() if video_name: logging.info('Falling back to %s interface.', video_name) if config.get('nosound'): sound.audio = __import__('audio_none', globals={"__name__": __name__}) else: sound.audio = __import__(audio_name, globals={"__name__": __name__}) if not sound.init(): sound.audio = __import__('audio_none', globals={"__name__": __name__}) sound.init() logging.warning( 'Failed to initialise sound. Sound will be disabled.\r') if not state.loaded: console.init_mode() # set the output for maths error messages fp.init(error_stream=console) return backend, console
# create etc object # this holds all the data (mode and preset names, knob values, midi input, sound input, current states, etc...) # it gets passed to the modes which use the audio midi and knob values etc = etc_system.System() # load shift params from file etc.recall_shift_params() # just to make sure etc.clear_flags() # setup osc and callbacks osc.init(etc) # setup alsa sound sound.init(etc, AOUT_JACK) # init pygame, this has to happen after sound is setup # but before the graphics stuff below pygame.init() clocker = pygame.time.Clock() # for locking fps print "pygame version " + pygame.version.ver # on screen display and other screen helpers osd.init(etc) osc.send("/led", 7) # set led to running # init fb and main surfaces print "opening frame buffer..." #os.putenv('SDL_VIDEODRIVER', "directfb")
from Tkinter import Tk from titleScreen import TitleScreen import sound sound.init(music="Korobeiniki.mid", sounds="lock_in rotate pause line_clear game_lost".split()) root = Tk() root.wm_title("Falling Block Game") root.bind("<Escape>", lambda event: root.destroy()) g = TitleScreen(root) g.pack() g.start() root.mainloop()