コード例 #1
0
class DanceCV():
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode(
            (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input,
                               speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)

    def run(self):
        while True:
            for events in pygame.event.get():
                if events.type == QUIT:
                    sys.exit(0)
            self.input.run()
            self.scene.run()
            pygame.display.update()
            self.clock.tick(30)
コード例 #2
0
 def __init__(self, device):
     self.track_list = None
     self.menu_items = {}
     self.player = Audio()
     self.renderer = MusicRender()
     self.parent = device
     self.index = 0
コード例 #3
0
ファイル: DanceCV.py プロジェクト: guru81/DanceCV
class DanceCV():
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input, speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)

        
        
    def run(self):
        while True:
            for events in pygame.event.get():
                if events.type == QUIT:
                    sys.exit(0)
            self.input.run()
            self.scene.run()
            pygame.display.update()
            self.clock.tick(30)
コード例 #4
0
ファイル: main.py プロジェクト: gseddon/baymax
 def __init__(self):
     self.queries = {
         "start": self.start,
         "stop": self.stop,
         "hello": self.hello,
         "inflate": self.inflate,
         "ouch": self.inflate,
         "how are you": self.how_are_you,
         "deflate": self.deflate,
     }
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(11, GPIO.OUT)
     GPIO.setup(10, GPIO.OUT)
     GPIO.output(11, GPIO.LOW)
     GPIO.output(10, GPIO.LOW)
     result_queue = queue.Queue()
     self.recogniser = Audio(result_queue, list(self.queries.keys()))
     self.recogniser.start()
     pygame.init()
     #self.play_sound_duration('care.mp3',2)
     #sleep(1)
     #self.play_sound_duration('hello_baymax.mp3',2)
     #sleep(1)
     while 1:
         result = result_queue.get(True)
         self.queries[result]()
コード例 #5
0
ファイル: MusicApp.py プロジェクト: Monolite/evdp
    def __init__(self, device):

        self.ListaDeTracks = []
        self.menu_items = {}
        GM = GestorMusica()
        self.ListaDeTracks = GM.get_tracks()
        self.Player = Audio()
        self.parent = device
コード例 #6
0
def main():
    """
    A user input interface for terminal
    """

    # Import all audio files from audio folder
    files = glob.glob(
        os.path.join(os.path.dirname(__file__), 'audio/', '*.' + '*'))

    # show all audio files
    for i, x in enumerate(files):
        print(str(i + 1) + ') ' + x.title())

    filepath = ''
    hertz = 0
    languageCode = ''
    chooseMethod = 0

    # When the user provides system arguments at script startup, use those instead.
    if len(sys.argv) > 1:
        filepath = sys.argv[1]
        hertz = int(sys.argv[2])
        languageCode = sys.argv[3]
        chooseMethod = int(sys.argv[4])
    else:
        filepath = files[int(input("Press the number of the audio file \n")) -
                         1]
        hertz = int(input('Enter hertz E.G. 16000 \n'))
        languageCode = input('Enter language code E.G. nl-NL or en-GB \n')
        chooseMethod = int(
            input(
                '1) Google Storage audio \n2) Audio file Sliced \n3) Audio file Async \n'
            ))

    if chooseMethod == 1:
        AudioTranscribe.fromGoogleStorage(Audio(filename='woordentest',
                                                fileFormat='mp3',
                                                languageCode='nl-NL'),
                                          enable_word_time=True)

    elif chooseMethod == 2:
        AudioTranscribe.AudioTranscribe.fromAudioFile(
            Audio(filepath, hertz, languageCode))

    elif chooseMethod == 3:
        AudioTranscribe.AudioTranscribe.transcribeFromSlicedAudio(
            configAudio=Audio(filepath, hertz, languageCode),
            configSlicing=ConfigSlicing(0, 60000, 60000, 500, -40))

    else:
        print('Something went wrong, please choose [1] or [2] or for exit [q]')
        if input() == 'q':
            exit(1)
        else:
            main()
    pass
コード例 #7
0
ファイル: Play.py プロジェクト: kyminbb/DanceDanceCV
 def __init__(self, song):
     self.audio = Audio()
     self.audio.preOpen()
     self.detect = Detect()
     pygame.init()
     self.audio.open()
     self.song = LoadSong(song).song
     pygame.display.set_mode((WIDTH, HEIGHT))
     pygame.display.set_caption('DanceDanceCV')
     screen = pygame.display.get_surface()
     self.view = View(screen, self.detect, self.song)
コード例 #8
0
 def get_new_audio(self):
     if self.result is not None:
         new_audio = Audio(self.audio.get_sampling_rate(), self.result)
         return new_audio
     else:
         print('ERROR: Apply filter in audio before getting it\'s result.')
         exit(1)
コード例 #9
0
 def get_text_response_via_speech_recognition(self):
     response = SpeechToText(Audio().record(),
                             language=self.language).convert_to_text()
     if isinstance(response, str) and not None:
         return response.strip()
     print("Something went wrong, retrying.")
     return self.get_text_response_via_speech_recognition()
コード例 #10
0
    def initializeGameWorld(self):

        base.setFrameRateMeter(True)
        self.setupLights()
        self.accept('escape', self.doExit)
        self.keyMap = {"reset": 0}
        # input states
        self.accept('f1', self.toggleWireframe)
        self.accept('f2', self.toggleTexture)
        self.accept('f3', self.toggleDebug)
        self.accept('f5', self.doScreenshot)
        self.accept("r", self.resetCar)
        self.accept('1', self.activateBoost)
        # Network Setup
        #self.cManager.startConnection()
        # Create Audio Manager
        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()
        #taskMgr.add(self.enterGame, "EnterGame")

        #taskMgr.add(self.usePowerup, "usePowerUp")
        self.accept('bullet-contact-added', self.onContactAdded)
        #Physics -- Terrain
        self.setup()  # Create Players
        self.createPlayers()

        # Camera
        self.setupCamera()
        # Create Powerups
        self.createPowerups()
        taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask")
        self.dashboard = Dashboard(self, taskMgr)
コード例 #11
0
    def __init__(self):
        self.__version__ = '3.1.3'

        logger_format = '%(asctime)s %(message)s'
        logging.basicConfig(format=logger_format, level=logging.INFO,
                            datefmt="%H:%M:%S", filename='./logfile.log', filemode='w')
        logging.getLogger().addHandler(SysLogHandler(facility=SysLogHandler.LOG_DAEMON, address='/dev/log'))

        self._SIGKILL = False
        self.logging = logging
        self.config = DB('./config.json')

        self.network = Network(self)
        self.display = DisplayContent()
        self.detector = Detector()
        self.ultrasound = Ultrasound(self)
        self.temp = Temp()
        self.server = SimpleWebSocketServer('', 8069, WebSocketServer, self)
        self.cook = Cook(self)
        self.energy = Energy(self)
        self.history = History(self)
        self.audio = Audio(self)
        self.users = Users(self)
        self.automations = Automations(self)

        signal.signal(signal.SIGTERM, self.sig_handler)
        signal.signal(signal.SIGINT, self.sig_handler)

        self.log("Boot: v" + self.__version__)
コード例 #12
0
    def __init__(self, main, actor):
        self.actor = actor
        self.powerupViews = {}
        self.takenPowers = []
        self.activePowers = []
        self.main = main
        self.cManager = main.cManager
        self.Audio = Audio(self)

        powerupTypes = PowerupTypes()
        self.powerupPositions = PowerupPositions().positions

        pwrKey = 1
        instanceCount = 0
        for posKey in self.powerupPositions.keys():
            if instanceCount >= PowerupManager.MAX_COUNT:
                instanceCount = 0
                pwrKey += 1
            posValue = self.powerupPositions[posKey]
            pwrVal = powerupTypes.list[pwrKey]
            posValue["item"] = pwrVal
            self.powerupPositions[posKey] = posValue
            powerUpView = PowerupIcon(self.main, posValue)
            self.powerupViews[posKey] = powerUpView
            if posKey not in self.activePowers:
                self.activePowers.append(posKey)
            instanceCount += 1
コード例 #13
0
def Automode_C(js, sc, dl):
    print("AutoMode_C")
    with StepperMotor(0.02) as smFront:
        switchCount = 0
        motorCount = 0
        global stepping
        global continuing
        with open(js) as f:
            sequence = json.load(f)

        StepperService(smFront).start()
        for i in sequence:
            if i.get("star") != None:
                for pin in i["star"]:
                    sc.senddata(str(pin))
                    time.sleep(0.08)
            if i.get("daylight") != None:
                if i.get("daylight"):
                    dl.dawn()
                else:
                    dl.dusk()
            if i.get("audio") != None:
                name = i.get("audio")
                Audio(name).start()

            if i.get("motor") != None:
                stepping += i["motor"]
                motorCount += i["motor"]

            if i["interval"] == "wait":
                while True:
                    if stepping == 0:
                        break
                    time.sleep(0.05)
            elif i["interval"] == "end":
                continuing = False

            else:
                time.sleep(i["interval"] - 0.09 * switchCount)
                switchCount = 0

    time.sleep(1)

    with StepperMotor(0.04) as smRear:
        StepperService(smRear).start()
        stepping += -motorCount
        sc.senddata("star")
        print("Turn off the all StarPins")
        for pin in allstarsPin:
            sc.senddata(str(-pin))
            time.sleep(0.06)
        sc.senddata("exit")
        while True:
            if stepping == 0:
                continuing = False
                break
            time.sleep(0.03)
    sc.senddata("exit")
    print("Automode_C end\n")
コード例 #14
0
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode(
            (Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input,
                               speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)
コード例 #15
0
ファイル: Play.py プロジェクト: kyminbb/DanceDanceCV
class Play():
    def __init__(self, song):
        self.audio = Audio()
        self.audio.preOpen()
        self.detect = Detect()
        pygame.init()
        self.audio.open()
        self.song = LoadSong(song).song
        pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption('DanceDanceCV')
        screen = pygame.display.get_surface()
        self.view = View(screen, self.detect, self.song)

    def run(self):
        playing = True
        while playing:
            for events in pygame.event.get():
                if events.type == QUIT:
                    return 'quit'
            self.detect.run()
            self.view.run()
            pygame.display.update()
        pygame.quit()
コード例 #16
0
    def process_audio(self, input_data, output_folder):

        audio = Audio(data=read_json(input_data), output_folder=output_folder)
        print("BEGIN", end="")

        start = time.time()
        audio.check_up()
        print(" OK - {}".format(time.time() - start))

        print("\tPREPROCESADO")
        audio.clean_audio()

        print("\tAUDIO LIMPIO ", end="")
        sys.stdout.flush()
        start = time.time()
        audio.split_audio()
        print(" OK - {}".format(time.time() - start))

        print("\tAUDIO SPLITTED", end="")
        return audio.process_output()
コード例 #17
0
ファイル: DanceCV.py プロジェクト: guru81/DanceCV
    def __init__(self, song, speed):

        self.input = Input()
        self.resource = Resource()
        self.audio = Audio()
        self.audio.pre_open()
        pygame.init()
        self.audio.open()
        if song != None:
            self.song = loadSong(self.resource, song)
        else:
            self.song = loadSong(self.resource, "gangnam")
        self.clock = pygame.time.Clock()
        pygame.display.set_mode((Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT))
        pygame.display.set_caption("DanceCV")
        screen = pygame.display.get_surface()
        if speed != None:
            self.scene = Scene(self.resource, self.song, screen, self.input, speed)
        else:
            self.scene = Scene(self.resource, self.song, screen, self.input, 2)
コード例 #18
0
ファイル: GameEngine.py プロジェクト: chk666/fofix
    def __init__(self, config = None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None    #placeholder for main menu object - to prevent reinstantiation

        self.createdGuitarScene = False   #MFH - so we only create ONE guitarscene...!
        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver) )
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))

        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title             = self.versionString
        self.restartRequested  = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video             = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio             = Audio()
        self.frames            = 0
        self.fpsEstimate       = 0
        self.priority          = self.config.get("engine", "highpriority")
        self.show_fps          = self.config.get("video", "show_fps")
        self.advSettings       = self.config.get("game", "adv_settings")
        self.restartRequired   = False
        self.quicksetRestart   = False
        self.quicksetPerf      = self.config.get("quickset", "performance")
        self.scrollRate        = self.config.get("game", "scroll_rate")
        self.scrollDelay       = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        self.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        self.gameStarted       = False
        self.world             = None

        self.audioSpeedFactor  = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0 # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.startupMessages   = self.video.error
        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.mainloop  = self.loading
        self.menuMusic = False

        self.setlistMsg = None


        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized = False)

        self.addTask(self.view, synchronized = False)

        self.addTask(self.resource, synchronized = False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(stagespath)   #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(aniFile)[1] == ".png" or os.path.splitext(aniFile)[1] ==  ".jpg" or os.path.splitext(aniFile)[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)


            i = len(self.stageFolders)
            if i > 0: #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
            aniStageOptions.update({"Normal":_("Slideshow")})
            if i > 1:   #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random":_("Random")})
            Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game","last_theme")
            if lastTheme == "" or lastTheme != currentTheme:   #MFH - no last theme, and theme just changed:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force defaultAniStage
            self.config.set("game","last_theme",currentTheme)

            selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
                    self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
            Log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
            self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)


        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False
        self.graphicMenuShown   = False

        Log.debug("Ready.")
コード例 #19
0
ファイル: GameEngine.py プロジェクト: Hawkheart/fof-reborn
class GameEngine(Engine):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
                # evilynux - With self.audio.close(), calling self.quit() results in
                #            a crash. Calling the parent directly as a workaround.
            Engine.quit(self)

    def quit(self):
        self.audio.close()
        Engine.quit(self)

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def isServerRunning(self):
        return bool(self.server)

    def startServer(self):
        """Start the game server."""
        if not self.server:
            Log.debug("Starting server.")
            self.server = Server(self)
            self.addTask(self.server, synchronized = False)

    def connect(self, host):
        """
        Connect to a game server.

        @param host:  Name of host to connect to
        @return:      L{Session} connected to remote server
        """
        Log.debug("Connecting to host %s." % host)
        session = ClientSession(self)
        session.connect(host)
        self.addTask(session, synchronized = False)
        self.sessions.append(session)
        return session

    def stopServer(self):
        """Stop the game server."""
        if self.server:
            Log.debug("Stopping server.")
            self.removeTask(self.server)
            self.server = None

    def disconnect(self, session):
        """
        Disconnect a L{Session}

        param session:    L{Session} to disconnect
        """
        if session in self.sessions:
            Log.debug("Disconnecting.")
            self.removeTask(session)
            self.sessions.remove(session)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""
        done = Engine.run(self)
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        # Tune the scheduler priority so that transitions are as smooth as possible
        if self.view.isTransitionInProgress():
            self.boostBackgroundThreads(False)
        else:
            self.boostBackgroundThreads(True)

        done = Engine.run(self)
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        return done

    def run(self):
        try:
            return self.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            Log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
コード例 #20
0
class World(DirectObject):
    def __init__(self):

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.speed = 0

        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')

        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png",
                                       scale=.5,
                                       pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h",
                     style=1,
                     fg=(1, 1, 1, 1),
                     font=self.font_digital,
                     scale=.07,
                     pos=(1.25, -.92))

        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed),
                                          style=1,
                                          fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95),
                                          align=TextNode.ARight,
                                          scale=.07,
                                          font=self.font_digital)

        # Health Bar

        self.bars = {'H': 100, 'EH': 0, 'A': 0}

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text="",
                                        value=100,
                                        pos=(0.280, 0, 0.475),
                                        barColor=(1, 0, 0, 1),
                                        frameSize=(0, .705, .3, .35))

        self.EHealth_bar = DirectWaitBar(text="",
                                         value=0,
                                         pos=(1, 0, 0.475),
                                         barColor=(0, 1, 0, 1),
                                         frameSize=(0, .23, .3, .35),
                                         range=50)

        self.Armour_bar = DirectWaitBar(text="",
                                        value=0,
                                        pos=(.43, 0, .593),
                                        barColor=(159, 0, 255, 1),
                                        frameSize=(0, .8, .3, .35))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0),
        #     barColor = (0.97,0,0,1),
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025,
        #     text_pos = (0,0.01,0))

        def getHealthStatus():
            return self.bars

        def displayBars():
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']

        def armourPickup():
            self.bars['A'] += 25
            displayBars()

        def healthPickup():
            self.bars['EH'] += 25
            displayBars()

        def decHealth():
            self.bars['H'] -= 10
            displayBars()

        # Post the instructions
        self.frame = OnscreenImage(image="models/gframe.png",
                                   pos=(0, 0, 0),
                                   scale=(1.25, 1, 1))
        self.frame.setTransparency(TransparencyAttrib.MAlpha)

        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0, 0, 0)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

        taskMgr.add(self.move, "moveTask")

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()

        self.audioManager.initialiseSound(self.ralph)

    def show_speed(self, task):
        # self.speed = str(format(self.ralph.getCurrentSpeedKmHour(), '0.2f'))
        # self.speed = 2
        # print self.speed

        # Update Speed Display
        self.display_speed.destroy()
        self.display_speed = OnscreenText(text=str(self.speed),
                                          style=3,
                                          fg=(1, 1, 1, 1),
                                          pos=(1.2, -0.95),
                                          align=TextNode.ARight,
                                          scale=.15,
                                          font=self.font_digital)
        return task.cont

    #Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        base.camera.lookAt(self.ralph)
        if (self.keyMap["cam-left"] != 0):
            base.camera.setX(base.camera, -20 * globalClock.getDt())
        if (self.keyMap["cam-right"] != 0):
            base.camera.setX(base.camera, +20 * globalClock.getDt())

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if (self.keyMap["left"] != 0):
            self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt())
        if (self.keyMap["right"] != 0):
            self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt())
        if (self.keyMap["forward"] != 0):
            self.ralph.setY(self.ralph, -25 * globalClock.getDt())
            # print "walk", self.speed
            if self.speed < 100:
                self.speed = self.speed + self.speed / 100 + 1
            else:
                self.speed = self.speed + self.speed / 200 + 1
                # print self.speed
            # self.audioManager.updateSound()
            self.audioManager.updateSound()

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.keyMap["forward"] != 0) or (self.keyMap["left"] !=
                                             0) or (self.keyMap["right"] != 0):
            if self.isMoving is False:
                self.ralph.loop("run")
                # print "run"
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.speed = 0
                self.ralph.pose("walk", 5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralph.getPos() - base.camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        camvec.normalize()
        if (camdist > 10.0):
            base.camera.setPos(base.camera.getPos() + camvec * (camdist - 10))
            camdist = 10.0
        if (camdist < 5.0):
            base.camera.setPos(base.camera.getPos() - camvec * (5 - camdist))
            camdist = 5.0

        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.

        self.floater.setPos(self.ralph.getPos())
        self.floater.setZ(self.ralph.getZ() + 2.0)
        base.camera.lookAt(self.floater)

        return task.cont
コード例 #21
0
    def __init__(self):

        self.keyMap = {
            "left": 0,
            "right": 0,
            "forward": 0,
            "cam-left": 0,
            "cam-right": 0
        }
        base.win.setClearColor(Vec4(0, 0, 0, 1))

        self.speed = 0

        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')

        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png",
                                       scale=.5,
                                       pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h",
                     style=1,
                     fg=(1, 1, 1, 1),
                     font=self.font_digital,
                     scale=.07,
                     pos=(1.25, -.92))

        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed),
                                          style=1,
                                          fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95),
                                          align=TextNode.ARight,
                                          scale=.07,
                                          font=self.font_digital)

        # Health Bar

        self.bars = {'H': 100, 'EH': 0, 'A': 0}

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text="",
                                        value=100,
                                        pos=(0.280, 0, 0.475),
                                        barColor=(1, 0, 0, 1),
                                        frameSize=(0, .705, .3, .35))

        self.EHealth_bar = DirectWaitBar(text="",
                                         value=0,
                                         pos=(1, 0, 0.475),
                                         barColor=(0, 1, 0, 1),
                                         frameSize=(0, .23, .3, .35),
                                         range=50)

        self.Armour_bar = DirectWaitBar(text="",
                                        value=0,
                                        pos=(.43, 0, .593),
                                        barColor=(159, 0, 255, 1),
                                        frameSize=(0, .8, .3, .35))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0),
        #     barColor = (0.97,0,0,1),
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025,
        #     text_pos = (0,0.01,0))

        def getHealthStatus():
            return self.bars

        def displayBars():
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']

        def armourPickup():
            self.bars['A'] += 25
            displayBars()

        def healthPickup():
            self.bars['EH'] += 25
            displayBars()

        def decHealth():
            self.bars['H'] -= 10
            displayBars()

        # Post the instructions
        self.frame = OnscreenImage(image="models/gframe.png",
                                   pos=(0, 0, 0),
                                   scale=(1.25, 1, 1))
        self.frame.setTransparency(TransparencyAttrib.MAlpha)

        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")

        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(100, 100, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        # Create the main character, Ralph

        self.ralph = Actor("models/ralph", {
            "run": "models/ralph-run",
            "walk": "models/ralph-walk"
        })
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0, 0, 0)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.

        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left", 1])
        self.accept("arrow_right", self.setKey, ["right", 1])
        self.accept("arrow_up", self.setKey, ["forward", 1])
        self.accept("a", self.setKey, ["cam-left", 1])
        self.accept("s", self.setKey, ["cam-right", 1])
        self.accept("arrow_left-up", self.setKey, ["left", 0])
        self.accept("arrow_right-up", self.setKey, ["right", 0])
        self.accept("arrow_up-up", self.setKey, ["forward", 0])
        self.accept("a-up", self.setKey, ["cam-left", 0])
        self.accept("s-up", self.setKey, ["cam-right", 0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

        taskMgr.add(self.move, "moveTask")

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera

        base.disableMouse()
        base.camera.setPos(self.ralph.getX(), self.ralph.getY() + 10, 2)

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))

        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()

        self.audioManager.initialiseSound(self.ralph)
コード例 #22
0
class World(DirectObject):
    gameStateDict = {"Login": 0, "CreateLobby": 4, "EnterGame": 1, "BeginGame": 2, "InitializeGame": 3}
    gameState = -1
    # Login , EnterGame , BeginGame
    responseValue = -1
    currentTime = 0
    idleTime = 0
    mySequence = None
    pandaPace = None
    jumpState = False
    isWalk = False
    previousPos = None  # used to store the mainChar pos from one frame to another
    host = ""
    port = 0
    characters = []

    def __init__(self, manager):
        # Stores the list of all the others players characters
        self.cleanParticle = False
        self.vehiclelist = {}
        self.isActive = False
        self.nodeFilterList = []
        self.collisionThreadSet = []
        self.otherPlayer = None
        self.deadCounter = 0
        self.manager = manager
        self.lobby = manager.lobby
        self.login = self.lobby.World.username
        #self.cManager = self.manager.cManager
        self.isDebug = False
        self.enemyHealthList = {}

    def initializeGameWorld(self):

        base.setFrameRateMeter(True)
        self.setupLights()
        self.accept('escape', self.doExit)
        self.keyMap = {"reset": 0}
        # input states
        self.accept('f1', self.toggleWireframe)
        self.accept('f2', self.toggleTexture)
        self.accept('f3', self.toggleDebug)
        self.accept('f5', self.doScreenshot)
        self.accept("r", self.resetCar)
        self.accept('1', self.activateBoost)
        # Network Setup
        #self.cManager.startConnection()
        # Create Audio Manager
        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()
        #taskMgr.add(self.enterGame, "EnterGame")

        #taskMgr.add(self.usePowerup, "usePowerUp")
        self.accept('bullet-contact-added', self.onContactAdded)
        #Physics -- Terrain
        self.setup()  # Create Players
        self.createPlayers()

        # Camera
        self.setupCamera()
        # Create Powerups
        self.createPowerups()
        taskMgr.add(self.powerups.checkPowerPickup, "checkPowerupTask")
        self.dashboard = Dashboard(self, taskMgr)


    def activateKeys(self):
        inputState.watchWithModifiers('boostUp', '1-up')
        inputState.watchWithModifiers('forward', 'w')
        inputState.watchWithModifiers('left', 'a')
        inputState.watchWithModifiers('brake', 's')
        inputState.watchWithModifiers('right', 'd')
        inputState.watchWithModifiers('turnLeft', 'q')
        inputState.watchWithModifiers('turnRight', 'e')

        self.world.setGravity(Vec3(0, 0, -9.81))
    def activateBoost(self):
        self.vehicleContainer.addBoost()

    def resetCar(self):
        self.vehicleContainer.reset()

    def createPowerups(self):
        self.powerups = PowerupManager(self, self.vehicleContainer)

    def setTime(self):
        self.cManager.sendRequest(Constants.CMSG_TIME)

    def doExit(self):
        self.cleanup()
        sys.exit(1)

    def cleanup(self):
        self.cManager.sendRequest(Constants.CMSG_DISCONNECT)
        self.cManager.closeConnection()
        self.world = None
        self.outsideWorldRender.removeNode()


    def doReset(self):
        self.mainCharRef.reset()

    def doRanking(self):
        #print "doRanking called"
        self.cManager.sendRequest(Constants.CMSG_RANKINGS)


    def enterGame(self, task):
        self.startGameNow()
        return task.done
        if self.gameState == self.gameStateDict["Login"]:
            #responseValue = 1 indicates that this state has been finished
            if self.responseValue == 1:
                print "Authentication succeeded"
                # Authentication succeeded
                self.cManager.sendRequest(Constants.CMSG_CREATE_LOBBY, ["raceroyal", "0", "1"])
                self.gameState = self.gameStateDict["CreateLobby"]
                self.responseValue = -1
        elif self.gameState == self.gameStateDict["CreateLobby"]:
            if self.responseValue == 1:
                # Lobby Created and we are already in
                print "Lobby Created and we are already in"
                self.gameState = self.gameStateDict["EnterGame"]
                self.responseValue = -1
                self.cManager.sendRequest(Constants.CMSG_READY)

            elif self.responseValue == 0:
                #Game already created, let's join it
                print "Game already created, let's join it"
                self.cManager.sendRequest(Constants.CMSG_ENTER_GAME_NAME, "raceroyal")
                #self.gameState = self.gameStateDict["EnterGame"]
                #self.responseValue = -1
                self.responseValue = -1
                self.gameState = self.gameStateDict["InitializeGame"]
                #               Everyone is in the game, we send ReqReady, and the server will send positions when every client did
                self.cManager.sendRequest(Constants.CMSG_READY)

        elif self.gameState == self.gameStateDict["EnterGame"]:
            if self.responseValue == 1:
                #                 When the positions are sent, an acknowledgment is sent and we begin the InitializeGame
                print "When the positions are sent, an acknowledgment is sent and we begin the InitializeGame"
                self.responseValue = -1
                self.gameState = self.gameStateDict["InitializeGame"]
                #               Everyone is in the game, we send ReqReady, and the server will send positions when every client did
                self.cManager.sendRequest(Constants.CMSG_READY)

        elif self.gameState == self.gameStateDict["InitializeGame"]:
            if self.responseValue == 1:
                print "Set up the camera"
                # Set up the camera
                self.camera = Camera(self.mainChar)
                self.gameState = self.gameStateDict["BeginGame"]
                self.cManager.sendRequest(Constants.CMSG_READY)
                self.responseValue = -1

        elif self.gameState == self.gameStateDict["BeginGame"]:
            if self.responseValue == 1:
                print "Begin Game"
                #taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')
                taskMgr.add(self.update, "moveTask")
                return task.done

        return task.cont


    def startGameNow(self):
        #self.camera = Camera(self.mainChar)
        #taskMgr.doMethodLater(.1, self.updateMove, 'updateMove')
        taskMgr.add(self.update, "moveTask")


    def createEnvironment(self):
        self.environ = loader.loadModel("models/square")
        self.environ.reparentTo(render)
        self.environ.setPos(0, 0, 0)
        self.environ.setScale(500, 500, 1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
        self.environ.setTexture(self.moon_tex, 1)

        shape = BulletPlaneShape(Vec3(0, 0, 1), 0)
        node = BulletRigidBodyNode('Ground')
        node.addShape(shape)
        np = render.attachNewNode(node)
        np.setPos(0, 0, 0)

        self.bulletWorld.attachRigidBody(node)

        self.visNP = loader.loadModel('models/track.egg')
        self.tex = loader.loadTexture("models/tex/Main.png")
        self.visNP.setTexture(self.tex)

        geom = self.visNP.findAllMatches('**/+GeomNode').getPath(0).node().getGeom(0)
        mesh = BulletTriangleMesh()
        mesh.addGeom(geom)
        trackShape = BulletTriangleMeshShape(mesh, dynamic=False)

        body = BulletRigidBodyNode('Bowl')
        self.visNP.node().getChild(0).addChild(body)
        bodyNP = render.anyPath(body)
        bodyNP.node().addShape(trackShape)
        bodyNP.node().setMass(0.0)
        bodyNP.setTexture(self.tex)

        self.bulletWorld.attachRigidBody(bodyNP.node())

        self.visNP.reparentTo(render)

        self.bowlNP = bodyNP
        self.visNP.setScale(70)

    def makeCollisionNodePath(self, nodepath, solid):
        '''
        Creates a collision node and attaches the collision solid to the
        supplied NodePath. Returns the nodepath of the collision node.
        '''
        # Creates a collision node named after the name of the NodePath.
        collNode = CollisionNode("%s c_node" % nodepath.getName())
        collNode.addSolid(solid)
        collisionNodepath = nodepath.attachNewNode(collNode)

        return collisionNodepath


    # Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value


    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def getDist(self):
        mainCharX = self.mainChar.getPos().x
        mainCharY = self.mainChar.getPos().y
        pandaX = self.pandaActor2.getPos().x
        pandaY = self.pandaActor2.getPos().y
        dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2)
        return dist


    def removeCollisionSet(self, arg):
        sleep(2)
        self.nodeFilterList.pop(0)


    # _____HANDLER_____
    def onContactAdded(self, node1, node2):
        isMyCarColliding = False
        if node1.notifiesCollisions() and node2.notifiesCollisions():
            self.audioManager.play_collision()
            isEnable = True
            list2 = [node1.getName(), node2.getName()]
            for nodeSet in self.nodeFilterList:
                if (list2[0] == nodeSet[0]) or (list2[0] == nodeSet[1]):
                    if (list2[1] == nodeSet[0]) or (list2[1] == nodeSet[1]):
                        isEnable = False

            if isEnable:
                isMyCarColliding = False
                if node1.getName() == self.login:
                    isMyCarColliding = True
                    if node2.getName() == 'UniverseNode':
                        self.killMe()
                        return
                elif node2.getName() == self.login:
                    isMyCarColliding = True
                    if node1.getName() == 'UniverseNode':
                        self.killMe()
                        return

                if isMyCarColliding:
                    name1 = node1.getName()
                    vehicle1 = self.vehiclelist[name1]
                    vehicle1.props.setVelocity(node1.getLinearVelocity().length())
                    name2 = node2.getName()
                    vehicle2 = self.vehiclelist[name2]
                    vehicle2.props.setVelocity(node2.getLinearVelocity().length())
                    self.calculateDamage(vehicle1, vehicle2)

                self.nodeFilterList.append((node1.getName(), node2.getName()))
                thread = Thread(target=self.removeCollisionSet, args=(1, ))
                self.collisionThreadSet.append(thread)
                thread.start()

    def killMe(self):
        self.vehicleContainer.props.health = self.vehicleContainer.props.armor = 0
        self.cManager.sendRequest(Constants.CMSG_HEALTH, 0)
        #self.vehicleContainer.chassisNP.removeNode()
        self.cManager.sendRequest(Constants.CMSG_DEAD)
        self.gameEnd(True)

    def gameEnd(self, isDead=False):
        self.dashboard.gameResult(isDead)
        self.audioManager.StopAudioManager()
        self.cleanup()


    def callLobby(self):

        self.cleanup()
        # self.lobby.createSocialization()
        self.lobby.World.startMusic()
        self.lobby.World.doMenu()

    def doExit(self):
        self.cleanup()
        sys.exit(1)

    def doReset(self):
        self.cleanup()
        self.setup()

    def toggleWireframe(self):
        base.toggleWireframe()

    def toggleTexture(self):

        base.toggleTexture()


    def toggleDebug(self):
        if self.debugNP.isHidden() and self.isDebug:
            self.debugNP.show()
        else:
            self.debugNP.hide()


    def calculateDamage(self, fromCar, toCar, fromCollisionSection=2, toCollisionSection=2):
        # toCar takes more damage than fromCar
        fromWeight = fromCar.props.weight
        toWeight = toCar.props.weight
        fromSpeed = fromCar.props.velocity
        toSpeed = toCar.props.velocity

        #Speed Max = 100
        #Weights Max = 10
        #Front collisionSection = 3, mid = 2, back = 1
        damageFactor = (((fromWeight + toWeight) * (fromSpeed + toSpeed)) / 100)

        damage = .5 * damageFactor / fromCollisionSection
        #toDamage = .5 * damageFactor / toCollisionSection
        damage = int(damage)
        print "Damage: ", damage
        #print "To Damage: ", toDamage
        if fromCar.username == self.login:
            if not fromCar.props.setDamage(damage):
                self.killMe()
            else:
                self.cManager.sendRequest(Constants.CMSG_HEALTH, fromCar.props.getHitPoint())

        else:
            if not toCar.props.setDamage(damage):
                self.killMe()
            else:
                self.cManager.sendRequest(Constants.CMSG_HEALTH, toCar.props.getHitPoint())

        print "My health: ", self.vehicleContainer.props.health
        if self.vehicleContainer.props.health < 50 and not self.cleanParticle:
            #self.vehicleContainer.loadParticleConfig('steam.ptf')
            self.cleanParticle = True
        else:
            if self.cleanParticle:
                #self.vehicleContainer.p.cleanup()
                self.cleanParticle = False

    def doScreenshot(self):

        base.screenshot('Bullet')

    def toggleHeightfield(self):

        self.terrainContainer.setDebugEnabled()
    # ____TASK___
    def update(self, task):
        dt = globalClock.getDt()
        self.audioManager.updateSound(self.vehicleContainer)
        #print "Type: ", type(self.vehicleContainer)
        forces = self.vehicleContainer.processInput(inputState, dt)
        moving = self.vehicleContainer.chassisNP.getPos()
        if forces!= None and forces[0] != None and forces[1] != None and forces[2] != None:
            #fake move for other playera
                # self.otherPlayer.move(forces[0], forces[1], forces[2], moving.getX()+10, moving.getY(), moving.getZ(),
                #                            self.vehicleContainer.chassisNP.getH(), self.vehicleContainer.chassisNP.getP(), self.vehicleContainer.chassisNP.getR())
            #print"sending move: ", self.login, forces[0], forces[1], forces[2], moving.getX(), moving.getY(), moving.getZ(), self.vehicleContainer.chassisNP.getH(), self.vehicleContainer.chassisNP.getP(), self.vehicleContainer.chassisNP.getR()
            self.cManager.sendRequest(Constants.CMSG_MOVE,
                                      [forces[0], forces[1], forces[2], moving.getX(), moving.getY(), moving.getZ(),
                                       self.vehicleContainer.chassisNP.getH(), self.vehicleContainer.chassisNP.getP(), self.vehicleContainer.chassisNP.getR()])

        #self.moveCrazyCar(dt)
        if self.world != None:
            self.world.doPhysics(dt, 10, 0.008)

        # if inputState.isSet('step'):
        #     self.vehicleContainer.processInput(inputState, dt)
        #     self.moveCrazyCar(dt)
        #     self.stepPhysicsWorld()

        self.updateCamera(self.vehicleContainer.speed)
        return task.cont


    def updateCamera(self, speed=0.0, initial=False):
        #"""Reposition camera depending on the vehicle speed"""
        minDistance = 8.0
        maxDistance = 13.0
        minHeight = 1.5
        maxHeight = 3.0
        maxSpeed = 30.0  # m/s

        distance = (minDistance + (maxDistance - minDistance) * speed / maxSpeed)
        distance = min(maxDistance, distance)
        height = minHeight + (maxHeight - minHeight) * speed / maxSpeed
        height = min(maxHeight, height)

        vPos = self.vehicleContainer.chassisNP.getPos()
        headingRad = self.vehicleContainer.chassisNP.getH() * math.pi / 180.0

        targetPos = vPos + Vec3(distance * math.sin(headingRad), -distance * math.cos(headingRad), height)
        cameraPos = base.camera.getPos()

        base.camera.setPos(cameraPos + (targetPos - cameraPos) * 0.1)
        # Look slightly ahead of the car
        base.camera.lookAt(*vPos)
        base.camera.setP(base.camera.getP() + 7)

    def cleanup(self):
        self.world = None
        self.worldNP.removeNode()
        self.cManager.closeConnection()

    def setupCamera(self):
        base.disableMouse()
        base.camera.setPos(self.vehicleContainer.chassisNP.getX(), self.vehicleContainer.chassisNP.getY() + 10, 2)
        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

    def setupLights(self):
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.setFrameRateMeter(True)
        # Add a light to the scene.
        self.lightpivot = render.attachNewNode("lightpivot")
        self.lightpivot.setPos(0, 0, 5)
        self.lightpivot.hprInterval(10, Point3(360, 0, 0)).loop()
        plight = PointLight('plight')
        plight.setColor(Vec4(1, 0, 0, 1))
        plight.setAttenuation(Vec3(0.37, 0.025, 0))
        plnp = self.lightpivot.attachNewNode(plight)
        plnp.setPos(45, 0, 0)
        plnp.lookAt(*Vec3(0, 0, 0, ))

        # Light
        alight = AmbientLight('ambientLight')
        alight.setColor(Vec4(0.2, 0.2, 0.2, 1))
        alightNP = render.attachNewNode(alight)

        #   dlight = DirectionalLight('directionalLight')
        #   dlight.setDirection(Vec3(1, 1, -1))
        #   dlight.setColor(Vec4(0.7, 0.7, 0.7, 1))
        #   dlightNP = render.attachNewNode(dlight)

        render.clearLight()
        render.setLight(alightNP)
        #   render.setLight(dlightNP)
        render.setLight(plnp)

        # create a sphere to denote the light
        sphere = loader.loadModel("models/sphere")
        sphere.reparentTo(plnp)
        sun_tex = loader.loadTexture("models/tex/sun.jpg")
        sphere.setTexture(sun_tex, 1)

        render.setShaderAuto()


    def stepPhysicsWorld(self):
        dt = globalClock.getDt()
        self.world.doPhysics(dt, 10, 0.008)


    def setup(self):
        self.worldNP = render.attachNewNode('World')
        # World
        self.debugNP = self.worldNP.attachNewNode(BulletDebugNode('Debug'))
        #self.debugNP.show()
        #self.debugNP.node().showNormals(True)

        self.world = BulletWorld()
        self.world.setDebugNode(self.debugNP.node())

        # Obstruction
        # self.obstruction = Obstruction(self)

        # Heightfield (static)
        self.terrainContainer = Terrain(self, base, render)


    def createPlayers(self):
        # Dynamic - moving bodies
        # Car
        for createPlayerUsername in self.manager.playerList.keys():
            if createPlayerUsername in self.vehiclelist.keys():
                print "Player Already rendered"
            else:
                #print "Creating main other player @ 100"
                vehicleAttributes = self.manager.playerList[createPlayerUsername]
                isCurrentPlayer=False
                if self.login == createPlayerUsername:
                    isCurrentPlayer = True
                playerVehicle = Vehicle(self, createPlayerUsername, pos=LVecBase3(vehicleAttributes.x, vehicleAttributes.y, vehicleAttributes.z),isCurrentPlayer=isCurrentPlayer, carId=vehicleAttributes.carId)
                if self.login != createPlayerUsername:
                    self.enemyHealth = OtherPlayersHealth(self,playerVehicle)
                    self.enemyHealthList[createPlayerUsername] = self.enemyHealth
                    #taskMgr.add(self.updateStatusBars,"healthchange")
                #Send Health
                # CMSG_HEALTH
                self.cManager.sendRequest(Constants.CMSG_HEALTH, playerVehicle.props.getHitPoint())
                if self.login == createPlayerUsername:
                    self.vehicleContainer = playerVehicle
                    # self.audioManager.play_music_dd()
                    self.audioManager.initialiseSound(self.vehicleContainer)
                    print "I AM: ", createPlayerUsername
                #print "Creating other players: ", createPlayerUsername, "@ ", vehicleAttributes.x, vehicleAttributes.y, vehicleAttributes.z
                self.vehiclelist[createPlayerUsername] = playerVehicle

    def updateStatusBars(self, username, health):
        if username in self.enemyHealthList.keys():
            enemyHealth = self.enemyHealthList[username]
            print "self.vehicleContainer.props.health", self.vehicleContainer.props.health
            enemyHealth.HealthBar['value'] = health
        else:
            print "updateStatusBars: Enemy entry not found"

    def startConnection(self):
        """Create a connection to the remote host.

        If a connection cannot be created, it will ask the user to perform
        additional retries.

        """
        if self.cManager.connection == None:
            if not self.cManager.startConnection():
                return False

        return True


    def listFromInputState(self, inputState):
        # index 0 == forward
        # index 1 == brake
        # index 2 == right
        # index 3 == left
        result = [0, 0, 0, 0]
        if inputState.isSet('forward'):
            result[0] = 1
        if inputState.isSet('brake'):
            result[1] = 1
        if inputState.isSet('right'):
            result[2] = 1
        if inputState.isSet('left'):
            result[3] = 1

        return result
コード例 #23
0
from Audio import Audio
from services.audio_service import export

if __name__ == "__main__":
    audio_name = input('Type your audio file name: ')
    start_minutes, start_seconds = input(
        'Type your desired start_time: ').split(':')
    end_minutes, end_seconds = input('Type your desired end_time: ').split(':')

    audio = Audio(audio_name, start_minutes, start_seconds, end_minutes,
                  end_seconds)
    export(audio)
コード例 #24
0
ファイル: GameEngine.py プロジェクト: chk666/fofix
class GameEngine(object):
    """The main game engine."""
    def __init__(self, config = None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None    #placeholder for main menu object - to prevent reinstantiation

        self.createdGuitarScene = False   #MFH - so we only create ONE guitarscene...!
        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver) )
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " + repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))

        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title             = self.versionString
        self.restartRequested  = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename, "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video             = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio             = Audio()
        self.frames            = 0
        self.fpsEstimate       = 0
        self.priority          = self.config.get("engine", "highpriority")
        self.show_fps          = self.config.get("video", "show_fps")
        self.advSettings       = self.config.get("game", "adv_settings")
        self.restartRequired   = False
        self.quicksetRestart   = False
        self.quicksetPerf      = self.config.get("quickset", "performance")
        self.scrollRate        = self.config.get("game", "scroll_rate")
        self.scrollDelay       = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        self.cmdPlay           = 0
        self.cmdMode           = None
        self.cmdDiff           = None
        self.cmdPart           = None

        self.gameStarted       = False
        self.world             = None

        self.audioSpeedFactor  = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " + ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0 # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.startupMessages   = self.video.error
        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.mainloop  = self.loading
        self.menuMusic = False

        self.setlistMsg = None


        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized = False)

        self.addTask(self.view, synchronized = False)

        self.addTask(self.resource, synchronized = False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme, "backgrounds")
        themepath  = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(stagespath)   #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(os.path.join(stagespath,name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(aniFile)[1] == ".png" or os.path.splitext(aniFile)[1] ==  ".jpg" or os.path.splitext(aniFile)[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)


            i = len(self.stageFolders)
            if i > 0: #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme + " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),self.stageFolders[n]) for n in range(0, i)])
            aniStageOptions.update({"Normal":_("Slideshow")})
            if i > 1:   #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random":_("Random")})
            Config.define("game", "animated_stage_folder", str, defaultAniStage, text = _("Animated Stage"), options = aniStageOptions )

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game","last_theme")
            if lastTheme == "" or lastTheme != currentTheme:   #MFH - no last theme, and theme just changed:
                self.config.set("game","animated_stage_folder",defaultAniStage)   #force defaultAniStage
            self.config.set("game","last_theme",currentTheme)

            selectedAnimatedStage = self.config.get("game", "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(os.path.join(stagespath,selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " + selectedAnimatedStage + " does not exist, forcing Normal.")
                    self.config.set("game","animated_stage_folder","Normal") #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game", "animated_stage_folder", str, "None", text = _("Animated Stage"), options = ["None",_("None")])
            Log.warn("No stages\ folder found, forcing None setting for Animated Stage.")
            self.config.set("game","animated_stage_folder", "None") #MFH: force "None" when Stages folder can't be found



        try:
            fp, pathname, description = imp.find_module("CustomTheme",[themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)


        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False
        self.graphicMenuShown   = False

        Log.debug("Ready.")


    # evilynux - This stops the crowd cheers if they're still playing (issue 317).
    def quit(self):
        # evilynux - self.audio.close() crashes when we attempt to restart
        if not self.restartRequested:
            self.audio.close()
        Player.savePlayers()
        for t in list(self.tasks + self.frameTasks):
            self.removeTask(t)
        self.running = False

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.svg.setGeometry((0, 0, width, height))

    def startWorld(self, players, maxplayers = None, gameMode = 0, multiMode = 0, allowGuitar = True, allowDrum = True, allowMic = False, tutorial = False):
        self.world = World(self, players, maxplayers, gameMode, multiMode, allowGuitar, allowDrum, allowMic, tutorial)

    def finishGame(self):
        if not self.world:
            Log.notice("GameEngine.finishGame called before World created.")
            return
        self.world.finishGame()
        self.world = None
        self.gameStarted = False
        self.view.pushLayer(self.mainMenu)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize: Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    #volshebnyi
    def drawStarScore(self, screenwidth, screenheight, xpos, ypos, stars, scale = None, horiz_spacing = 1.2, space = 1.0, hqStar = False, align = LEFT):
        minScale = 0.02
        w = screenwidth
        h = screenheight
        if not scale:
            scale = minScale
        elif scale < minScale:
            scale = minScale
        if self.data.fcStars and stars == 7:
            star = self.data.starFC
        else:
            star = self.data.starPerfect
        wide = scale * horiz_spacing
        if align == CENTER: #center - akedrou (simplifying the alignment...)
            xpos  -= (2 * wide)
        elif align == RIGHT: #right
            xpos  -= (4 * wide)
        if stars > 5:
            for j in range(5):

                if self.data.maskStars:
                    if self.data.theme == 2:
                        self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (1, 1, 0, 1), stretched=11)
                    else:
                        self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), color = (0, 1, 0, 1), stretched=11)
                else:
                    self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched=11)
        else:
            for j in range(5):
                if j < stars:
                    if hqStar:
                        star = self.data.star4
                    else:
                        star = self.data.star2
                else:
                    if hqStar:
                        star = self.data.star3
                    else:
                        star = self.data.star1
                self.drawImage(star, scale = (scale,-scale), coord = (w*(xpos+wide*j)*space**4,h*ypos), stretched=11)

    def drawImage(self, image, scale = (1.0, -1.0), coord = (0, 0), rot = 0, \
                  color = (1,1,1,1), rect = (0,1,0,1), stretched = 0, fit = 0, \
                  alignment = CENTER, valignment = 1):
        """
        Draws the image/surface to screen

        @param image:        The openGL surface
        @param scale:        Scale factor (between 0.0 and 1.0, second value must be negative due to texture flipping)
        @param coord:        Where the image will be translated to on the screen
        @param rot:          How many degrees it will be rotated
        @param color:        The color of the image
                                 (values are between 0.0 and 1.0)
                                 (can have 3 values or 4, if 3 are given the alpha is automatically set to 1.0)
        @param rect:         The surface rectangle, this is used for cropping the texture
        @param stretched:    Stretches the image in one of 5 ways according to following passed values
                                 1) fits it to the width of the viewport
                                 2) fits it to the height of the viewport
                                11) fits it to the width of the viewport and scales the height while keeping the aspect ratio
                                12) fits it to the heigh of the viewport and scales the width while keeping the aspect ratio
                                 0) stretches it so it fits the whole viewport
                             Any other values will have the image maintain its size passed by scale
        @param fit:          Adjusts the texture so the coordinate for the y-axis placement can be
                             on the top side (1), bottom side (2), or center point (any other value) of the image
        @param alignment:    Adjusts the texture so the coordinate for x-axis placement can either be
                             on the left side (0), center point (1), or right(2) side of the image
        @param valignment:   Adjusts the texture so the coordinate for y-axis placement can either be
                             on the bottom side (0), center point (1), or top(2) side of the image
        """

        if not isinstance(image, ImgDrawing):
            return

        width, height = scale
        x, y = coord
        if stretched == 1: # fit to width
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
        elif stretched == 2: # fit to height
            height = height / image.pixelSize[1] * self.view.geometry[3]
        elif stretched == 11: # fit to width and keep ratio
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
            height = height / image.pixelSize[0] * self.view.geometry[2]
        elif stretched == 12: # fit to height and keep ratio
            width  = width  / image.pixelSize[1] * self.view.geometry[3]
            height = height / image.pixelSize[1] * self.view.geometry[3]
        elif not stretched == 0: # fit to screen
            width  = width  / image.pixelSize[0] * self.view.geometry[2]
            height = height / image.pixelSize[1] * self.view.geometry[3]

        if fit == 1: #y is on top (not center)
            y = y - ((image.pixelSize[1] * abs(scale[1]))*.5*(self.view.geometry[3]/480.0))
        elif fit == 2: #y is on bottom
            y = y + ((image.pixelSize[1] * abs(scale[1]))*.5*(self.view.geometry[3]/480.0))

        image.setRect(rect)
        image.setScale(width, height)
        image.setPosition(x, y)
        image.setAlignment(alignment)
        image.setVAlignment(valignment)
        image.setAngle(rot)
        image.setColor(color)
        image.draw()

    #blazingamer
    def draw3Dtex(self, image, vertex, texcoord, coord = None, scale = None, rot = None, color = (1,1,1), multiples = False, alpha = False, depth = False, vertscale = 0):
        '''
        Simplifies tex rendering

        @param image: self.xxx - tells the system which image/resource should be mapped to the plane
        @param vertex: (Left, Top, Right, Bottom) - sets the points that define where the plane will be drawn
        @param texcoord: (Left, Top, Right, Bottom) - sets where the texture should be drawn on the plane
        @param coord: (x,y,z) - where on the screen the plane will be rendered within the 3d field
        @param scale: (x,y,z) - scales an glplane how far in each direction

        @param rot: (degrees, x-axis, y-axis, z-axis)
        a digit in the axis is how many times you want to rotate degrees around that axis

        @param color: (r,g,b) - sets the color of the image when rendered
        0 = No Color, 1 = Full color

        @param multiples: True/False
        defines whether or not there should be multiples of the plane drawn at the same time
        only really used with the rendering of the notes, keys, and flames

        @param alpha: True/False - defines whether or not the image should have black turned into transparent
        only really used with hitglows and flames

        @param depth: True/False - sets the depth by which the object is rendered
        only really used by keys and notes

        @param vertscale: # - changes the yscale when setting vertex points
        only really used by notes
        '''


        if not isinstance(image, ImgDrawing):
            return

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE)

        if len(color) == 4:
            col_array  = np.array([[color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]],
                               [color[0],color[1],color[2], color[3]]], dtype=np.float32)
        else:
            col_array  = np.array([[color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1],
                               [color[0],color[1],color[2], 1]], dtype=np.float32)

        glEnable(GL_TEXTURE_2D)
        image.texture.bind()

        if multiples == True:
            glPushMatrix()

        if coord != None:
            glTranslate(coord[0], coord[1], coord[2])
        if rot != None:
            glRotate(rot[0], rot[1], rot[2], rot[3])
        if scale != None:
            glScalef(scale[0], scale[1], scale[2])

        if depth == True:
            glDepthMask(1)

        if not isinstance(vertex, np.ndarray):
            vertex = np.array(
              [[ vertex[0],  vertscale, vertex[1]],
               [ vertex[2],  vertscale, vertex[1]],
               [ vertex[0], -vertscale, vertex[3]],
               [ vertex[2], -vertscale, vertex[3]]], dtype=np.float32)

        if not isinstance(texcoord, np.ndarray):
            texcoord = np.array(
              [[texcoord[0], texcoord[1]],
               [texcoord[2], texcoord[1]],
               [texcoord[0], texcoord[3]],
               [texcoord[2], texcoord[3]]], dtype=np.float32)

        cmgl.drawArrays(GL_TRIANGLE_STRIP, vertices=vertex, colors=col_array, texcoords=texcoord)

        if depth == True:
            glDepthMask(0)

        if multiples == True:
            glPopMatrix()

        glDisable(GL_TEXTURE_2D)

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    #glorandwarf: renamed to retrieve the path of the file
    def fileExists(self, fileName):
        return self.data.fileExists(fileName)

    def getPath(self, fileName):
        return self.data.getPath(fileName)

    def loading(self):
        """Loading state loop."""
        done = self.doRun()
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.svg.clear(*self.theme.backgroundColor)

    def addTask(self, task, synchronized = True):
        """
        Add a task to the engine.

        @param task:          L{Task} to add
        @type  synchronized:  bool
        @param synchronized:  If True, the task will be run with small
                              timesteps tied to the engine clock.
                              Otherwise the task will be run once per frame.
        """
        if synchronized:
            queue = self.tasks
        else:
            queue = self.frameTasks

        if not task in queue:
            queue.append(task)
            task.started()

    def removeTask(self, task):
        """
        Remove a task from the engine.

        @param task:    L{Task} to remove
        """
        queues = self._getTaskQueues(task)
        for q in queues:
            q.remove(task)
        if queues:
            task.stopped()

    def _getTaskQueues(self, task):
        queues = []
        for queue in [self.tasks, self.frameTasks]:
            if task in queue:
                queues.append(queue)
        return queues

    def pauseTask(self, task):
        """
        Pause a task.

        @param task:  L{Task} to pause
        """
        self.paused.append(task)

    def resumeTask(self, task):
        """
        Resume a paused task.

        @param task:  L{Task} to resume
        """
        self.paused.remove(task)

    def enableGarbageCollection(self, enabled):
        """
        Enable or disable garbage collection whenever a random garbage
        collection run would be undesirable. Disabling the garbage collector
        has the unfortunate side-effect that your memory usage will skyrocket.
        """
        if enabled:
            gc.enable()
        else:
            gc.disable()

    def collectGarbage(self):
        """
        Run a garbage collection run.
        """
        gc.collect()

    def _runTask(self, task, ticks = 0):
        if not task in self.paused:
            self.currentTask = task
            task.run(ticks)
            self.currentTask = None

    def main(self):
        """Main state loop."""
        done = self.doRun()
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        # evilynux - Estimate the rendered frames per second.
        self.frames = self.frames+1
        # Estimate every 120 frames when highpriority is True.
        # Estimate every 2*config.fps when highpriority is False,
        # if you are on target, that should be every 2 seconds.
        if( not self.priority and self.frames == (self.fps << 1) ) or ( self.priority and self.frames == 120 ):
            self.fpsEstimate = self.clock.get_fps()
            # evilynux - Printing on the console with a frozen binary may cause a crash.
            if self.show_fps and not Version.isWindowsExe():
                print("%.2f fps" % self.fpsEstimate)
            self.frames = 0
        return done

    def doRun(self):
        """Run one cycle of the task scheduler engine."""
        if not self.frameTasks and not self.tasks:
            return False

        for task in self.frameTasks:
            self._runTask(task)
        tick = self.clock.get_time()
        for task in self.tasks:
            self._runTask(task, tick)
        self.clock.tick(self.fps)
        return True

    def run(self):
        return self.mainloop()
コード例 #25
0
    def __init__(self, config=None):
        """
    Constructor.

    @param config:  L{Config} instance for settings
    """

        if not config:
            config = Config.load()

        self.config = config

        fps = self.config.get("video", "fps")
        tickrate = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps=fps, tickrate=tickrate)

        pygame.init()

        self.title = _("Frets on Fire")
        self.restartRequested = False
        self.handlingException = False
        self.video = Video(self.title)
        self.audio = Audio()

        Log.debug("Initializing audio.")
        frequency = self.config.get("audio", "frequency")
        bits = self.config.get("audio", "bits")
        stereo = self.config.get("audio", "stereo")
        bufferSize = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency=frequency,
                            bits=bits,
                            stereo=stereo,
                            bufferSize=bufferSize)
        pygame.init()
        self.audio.open(frequency=frequency,
                        bits=bits,
                        stereo=stereo,
                        bufferSize=bufferSize)

        Log.debug("Initializing video.")
        width, height = [
            int(s) for s in self.config.get("video", "resolution").split("x")
        ]
        fullscreen = self.config.get("video", "fullscreen")
        multisamples = self.config.get("video", "multisamples")
        self.video.setMode((width, height),
                           fullscreen=fullscreen,
                           multisamples=multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        self.svg.setRenderingQuality(self.config.get("opengl", "svgquality"))
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]),
                   int(viewport[3]))

        self.input = Input()
        self.view = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource = Resource(Version.dataPath())
        self.server = None
        self.sessions = []
        self.mainloop = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game",
                           "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl",
                            "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized=False)
        self.addTask(self.input, synchronized=False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized=False)
        self.data = Data(self.resource, self.svg)

        self.input.addKeyListener(FullScreenSwitcher(self), priority=True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer = None
        self.startupLayer = None
        self.loadingScreenShown = False

        Log.debug("Ready.")
コード例 #26
0
ファイル: App.py プロジェクト: DevBryson/Movie-Retile
def sound_input2(E2):
    audio = Audio()
    audio.record_voice()
    text = audio.shibie_voice()
    if text is not None:
        E2.insert(END, text)
コード例 #27
0
ファイル: decoder.py プロジェクト: aqfort/audio_encryper
#!/usr/bin/env python3
import argparse
from Audio import Audio
import rsa
from Cryptographer import Cryptographer

parser = argparse.ArgumentParser(description='Encryptor parser')
parser.add_argument('-i', type=str, default=r'audio.wav')
parser.add_argument('-enc', type=str, default="utf-8")

with open("private_key.txt", "r") as pr:
    private_str = pr.read().split(" ")
    private = rsa.PrivateKey(int(private_str[0]), int(private_str[1]),
                             int(private_str[2]), int(private_str[3]),
                             int(private_str[4]))

args = parser.parse_args()
audio = Audio(filename=args.i)
decoder = Cryptographer(audio=audio, coding=args.enc)
res = decoder.decode(private)
print(res.replace("*", "\n"))
コード例 #28
0
    def __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))


        self.speed = 0



        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')


        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1),
                     font=self.font_digital, scale=.07, pos=(1.25, -.92))


        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital)

        # Health Bar

        self.bars = {'H' : 100, 'EH' : 0 ,'A' : 0 }

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text = "", value = 100, pos = (0.280,0,0.475), barColor= (1,0,0,1), frameSize = (0,.705,.3,.35))

        self.EHealth_bar = DirectWaitBar(text = "", value = 0, pos = (1,0,0.475), barColor= (0,1,0,1), frameSize = (0,.23,.3,.35),range = 50 )

        self.Armour_bar = DirectWaitBar(text = "", value = 0, pos = (.43,0,.593), barColor= (159,0,255,1), frameSize = (0,.8,.3,.35))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0), 
        #     barColor = (0.97,0,0,1), 
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025, 
        #     text_pos = (0,0.01,0))


        def getHealthStatus() :
            return self.bars

        def displayBars() :
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']


        def armourPickup() :
            self.bars['A'] += 25
            displayBars()

        def healthPickup() :
            self.bars['EH'] += 25
            displayBars()

        def decHealth() :
            self.bars['H'] -= 10
            displayBars()


              


        # Post the instructions
        self.frame = OnscreenImage(image = "models/gframe.png", pos = (0,0,0), scale = (1.25, 1, 1) )
        self.frame.setTransparency(TransparencyAttrib.MAlpha)


        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        
        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)
        
        # Create the main character, Ralph

        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

        taskMgr.add(self.move,"moveTask")

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))



        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()

        self.audioManager.initialiseSound(self.ralph)
コード例 #29
0
class GameEngine(object):
    """The main game engine."""
    def __init__(self, config=None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None  #placeholder for main menu object - to prevent reinstantiation

        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME  #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver))
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " +
                      repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))
        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config = config

        fps = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title = self.versionString
        self.restartRequested = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename,
                                 "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio = Audio()
        self.frames = 0
        self.fpsEstimate = 0
        self.priority = self.config.get("engine", "highpriority")
        self.show_fps = self.config.get("video", "show_fps")
        self.advSettings = self.config.get("game", "adv_settings")
        self.restartRequired = False
        self.quicksetRestart = False
        self.quicksetPerf = self.config.get("quickset", "performance")
        self.scrollRate = self.config.get("game", "scroll_rate")
        self.scrollDelay = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency = self.config.get("audio", "frequency")
        bits = self.config.get("audio", "bits")
        stereo = self.config.get("audio", "stereo")
        bufferSize = self.config.get("audio", "buffersize")
        self.audio.open(frequency=frequency,
                        bits=bits,
                        stereo=stereo,
                        bufferSize=bufferSize)

        self.cmdPlay = 0
        self.cmdMode = None
        self.cmdDiff = None
        self.cmdPart = None

        self.gameStarted = False
        self.world = None

        self.audioSpeedFactor = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [
            int(s) for s in self.config.get("video", "resolution").split("x")
        ]
        fullscreen = self.config.get("video", "fullscreen")
        multisamples = self.config.get("video", "multisamples")
        self.video.setMode((width, height),
                           fullscreen=fullscreen,
                           multisamples=multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " +
                  ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0  # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]),
                   int(viewport[3]))

        self.startupMessages = self.video.error
        self.input = Input()
        self.view = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource = Resource(Version.dataPath())
        self.mainloop = self.loading
        self.menuMusic = False

        self.setlistMsg = None

        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized=False)

        self.addTask(self.view, synchronized=False)

        self.addTask(self.resource, synchronized=False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme,
                                  "backgrounds")
        themepath = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(
                stagespath
            )  #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(
                        os.path.join(stagespath, name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(
                            aniFile
                    )[1] == ".png" or os.path.splitext(
                            aniFile
                    )[1] == ".jpg" or os.path.splitext(
                            aniFile
                    )[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)

            i = len(self.stageFolders)
            if i > 0:  #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme +
                      " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),
                                     self.stageFolders[n])
                                    for n in range(0, i)])
            aniStageOptions.update({"Normal": _("Slideshow")})
            if i > 1:  #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random": _("Random")})
            Config.define("game",
                          "animated_stage_folder",
                          str,
                          defaultAniStage,
                          text=_("Animated Stage"),
                          options=aniStageOptions)

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game", "last_theme")
            if lastTheme == "" or lastTheme != currentTheme:  #MFH - no last theme, and theme just changed:
                self.config.set("game", "animated_stage_folder",
                                defaultAniStage)  #force defaultAniStage
            self.config.set("game", "last_theme", currentTheme)

            selectedAnimatedStage = self.config.get("game",
                                                    "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(
                        os.path.join(stagespath, selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " +
                             selectedAnimatedStage +
                             " does not exist, forcing Normal.")
                    self.config.set(
                        "game", "animated_stage_folder", "Normal"
                    )  #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game",
                          "animated_stage_folder",
                          str,
                          "None",
                          text=_("Animated Stage"),
                          options=["None", _("None")])
            Log.warn(
                "No stages\ folder found, forcing None setting for Animated Stage."
            )
            self.config.set(
                "game", "animated_stage_folder",
                "None")  #MFH: force "None" when Stages folder can't be found

        try:
            fp, pathname, description = imp.find_module(
                "CustomTheme", [themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)

        self.input.addKeyListener(FullScreenSwitcher(self), priority=True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer = None
        self.startupLayer = None
        self.loadingScreenShown = False
        self.graphicMenuShown = False

        Log.debug("Ready.")

    # evilynux - This stops the crowd cheers if they're still playing (issue 317).
    def quit(self):
        # evilynux - self.audio.close() crashes when we attempt to restart
        if not self.restartRequested:
            self.audio.close()
        Player.savePlayers()
        for t in list(self.tasks + self.frameTasks):
            self.removeTask(t)
        self.running = False

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.svg.setGeometry((0, 0, width, height))

    def startWorld(self,
                   players,
                   maxplayers=None,
                   gameMode=0,
                   multiMode=0,
                   allowGuitar=True,
                   allowDrum=True,
                   allowMic=False,
                   tutorial=False):
        self.world = World(self, players, maxplayers, gameMode, multiMode,
                           allowGuitar, allowDrum, allowMic, tutorial)

    def finishGame(self):
        if not self.world:
            Log.notice("GameEngine.finishGame called before World created.")
            return
        self.world.finishGame()
        self.world = None
        self.gameStarted = False
        self.view.pushLayer(self.mainMenu)

    def loadImgDrawing(self, target, name, fileName, textureSize=None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize: Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    #volshebnyi
    def drawStarScore(self,
                      screenwidth,
                      screenheight,
                      xpos,
                      ypos,
                      stars,
                      scale=None,
                      horiz_spacing=1.2,
                      space=1.0,
                      hqStar=False,
                      align=LEFT):
        minScale = 0.02
        w = screenwidth
        h = screenheight
        if not scale:
            scale = minScale
        elif scale < minScale:
            scale = minScale
        if self.data.fcStars and stars == 7:
            star = self.data.starFC
        else:
            star = self.data.starPerfect
        wide = scale * horiz_spacing
        if align == CENTER:  #center - akedrou (simplifying the alignment...)
            xpos -= (2 * wide)
        elif align == RIGHT:  #right
            xpos -= (4 * wide)
        if stars > 5:
            for j in range(5):

                if self.data.maskStars:
                    if self.data.theme == 2:
                        self.drawImage(star,
                                       scale=(scale, -scale),
                                       coord=(w * (xpos + wide * j) * space**4,
                                              h * ypos),
                                       color=(1, 1, 0, 1),
                                       stretched=KEEP_ASPECT | FIT_WIDTH)
                    else:
                        self.drawImage(star,
                                       scale=(scale, -scale),
                                       coord=(w * (xpos + wide * j) * space**4,
                                              h * ypos),
                                       color=(0, 1, 0, 1),
                                       stretched=KEEP_ASPECT | FIT_WIDTH)
                else:
                    self.drawImage(star,
                                   scale=(scale, -scale),
                                   coord=(w * (xpos + wide * j) * space**4,
                                          h * ypos),
                                   stretched=KEEP_ASPECT | FIT_WIDTH)
        else:
            for j in range(5):
                if j < stars:
                    if hqStar:
                        star = self.data.star4
                    else:
                        star = self.data.star2
                else:
                    if hqStar:
                        star = self.data.star3
                    else:
                        star = self.data.star1
                self.drawImage(star,
                               scale=(scale, -scale),
                               coord=(w * (xpos + wide * j) * space**4,
                                      h * ypos),
                               stretched=KEEP_ASPECT | FIT_WIDTH)

    def drawImage(self, image, scale = (1.0, -1.0), coord = (0, 0), rot = 0, \
                  color = (1,1,1,1), rect = (0,1,0,1), stretched = 0, fit = CENTER, \
                  alignment = CENTER, valignment = MIDDLE):
        """
        Draws the image/surface to screen
        @depreciated please use the specific methods of the image or Im.drawImage

        @param image:        The openGL surface
        @param scale:        Scale factor (between 0.0 and 1.0, second value must be negative due to texture flipping)
        @param coord:        Where the image will be translated to on the screen
        @param rot:          How many degrees it will be rotated
        @param color:        The color of the image
                                 (values are between 0.0 and 1.0)
                                 (can have 3 values or 4, if 3 are given the alpha is automatically set to 1.0)
        @param rect:         The surface rectangle, this is used for cropping the texture

                             Any other values will have the image maintain its size passed by scale
        @param alignment:    Adjusts the texture so the coordinate for x-axis placement can either be
                             on the left side (0), center point (1), or right(2) side of the image
        @param valignment:   Adjusts the texture so the coordinate for y-axis placement can either be
                             on the bottom side (0), center point (1), or top(2) side of the image
        """

        return ImgDrawing.drawImage(image, scale, coord, rot, color, rect,
                                    stretched, fit, alignment, valignment)

    #blazingamer
    def draw3Dtex(self,
                  image,
                  vertex,
                  texcoord,
                  coord=None,
                  scale=None,
                  rot=None,
                  color=(1, 1, 1),
                  multiples=False,
                  alpha=False,
                  depth=False,
                  vertscale=0):
        '''
        Simplifies tex rendering

        @param image: self.xxx - tells the system which image/resource should be mapped to the plane
        @param vertex: (Left, Top, Right, Bottom) - sets the points that define where the plane will be drawn
        @param texcoord: (Left, Top, Right, Bottom) - sets where the texture should be drawn on the plane
        @param coord: (x,y,z) - where on the screen the plane will be rendered within the 3d field
        @param scale: (x,y,z) - scales an glplane how far in each direction

        @param rot: (degrees, x-axis, y-axis, z-axis)
        a digit in the axis is how many times you want to rotate degrees around that axis

        @param color: (r,g,b) - sets the color of the image when rendered
        0 = No Color, 1 = Full color

        @param multiples: True/False
        defines whether or not there should be multiples of the plane drawn at the same time
        only really used with the rendering of the notes, keys, and flames

        @param alpha: True/False - defines whether or not the image should have black turned into transparent
        only really used with hitglows and flames

        @param depth: True/False - sets the depth by which the object is rendered
        only really used by keys and notes

        @param vertscale: # - changes the yscale when setting vertex points
        only really used by notes
        '''

        if not isinstance(image, ImgDrawing):
            return

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE)

        if len(color) == 4:
            col_array = np.array([[color[0], color[1], color[2], color[3]],
                                  [color[0], color[1], color[2], color[3]],
                                  [color[0], color[1], color[2], color[3]],
                                  [color[0], color[1], color[2], color[3]]],
                                 dtype=np.float32)
        else:
            col_array = np.array([[color[0], color[1], color[2], 1],
                                  [color[0], color[1], color[2], 1],
                                  [color[0], color[1], color[2], 1],
                                  [color[0], color[1], color[2], 1]],
                                 dtype=np.float32)

        glEnable(GL_TEXTURE_2D)
        image.texture.bind()

        if multiples == True:
            glPushMatrix()

        if coord != None:
            glTranslate(coord[0], coord[1], coord[2])
        if rot != None:
            glRotate(rot[0], rot[1], rot[2], rot[3])
        if scale != None:
            glScalef(scale[0], scale[1], scale[2])

        if depth == True:
            glDepthMask(1)

        if not isinstance(vertex, np.ndarray):
            vertex = np.array([[vertex[0], vertscale, vertex[1]],
                               [vertex[2], vertscale, vertex[1]],
                               [vertex[0], -vertscale, vertex[3]],
                               [vertex[2], -vertscale, vertex[3]]],
                              dtype=np.float32)

        if not isinstance(texcoord, np.ndarray):
            texcoord = np.array(
                [[texcoord[0], texcoord[1]], [texcoord[2], texcoord[1]],
                 [texcoord[0], texcoord[3]], [texcoord[2], texcoord[3]]],
                dtype=np.float32)

        cmgl.drawArrays(GL_TRIANGLE_STRIP,
                        vertices=vertex,
                        colors=col_array,
                        texcoords=texcoord)

        if depth == True:
            glDepthMask(0)

        if multiples == True:
            glPopMatrix()

        glDisable(GL_TEXTURE_2D)

        if alpha == True:
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    #glorandwarf: renamed to retrieve the path of the file
    def fileExists(self, fileName):
        return self.data.fileExists(fileName)

    def getPath(self, fileName):
        return self.data.getPath(fileName)

    def loading(self):
        """Loading state loop."""
        done = self.doRun()
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.svg.clear(*self.theme.backgroundColor)

    def fadeScreen(self, v):
        """
        Fade the screen to a dark color to make whatever is on top easier to read.

        @param v: Visibility factor [0..1], 0 is fully visible
        """
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_COLOR_MATERIAL)

        glBegin(GL_TRIANGLE_STRIP)
        glColor4f(0, 0, 0, .3 - v * .3)
        glVertex2f(0, 0)
        glColor4f(0, 0, 0, .3 - v * .3)
        glVertex2f(1, 0)
        glColor4f(0, 0, 0, .9 - v * .9)
        glVertex2f(0, 1)
        glColor4f(0, 0, 0, .9 - v * .9)
        glVertex2f(1, 1)
        glEnd()

    def addTask(self, task, synchronized=True):
        """
        Add a task to the engine.

        @param task:          L{Task} to add
        @type  synchronized:  bool
        @param synchronized:  If True, the task will be run with small
                              timesteps tied to the engine clock.
                              Otherwise the task will be run once per frame.
        """
        if synchronized:
            queue = self.tasks
        else:
            queue = self.frameTasks

        if not task in queue:
            queue.append(task)
            task.started()

    def removeTask(self, task):
        """
        Remove a task from the engine.

        @param task:    L{Task} to remove
        """
        queues = self._getTaskQueues(task)
        for q in queues:
            q.remove(task)
        if queues:
            task.stopped()

    def _getTaskQueues(self, task):
        queues = []
        for queue in [self.tasks, self.frameTasks]:
            if task in queue:
                queues.append(queue)
        return queues

    def pauseTask(self, task):
        """
        Pause a task.

        @param task:  L{Task} to pause
        """
        self.paused.append(task)

    def resumeTask(self, task):
        """
        Resume a paused task.

        @param task:  L{Task} to resume
        """
        self.paused.remove(task)

    def enableGarbageCollection(self, enabled):
        """
        Enable or disable garbage collection whenever a random garbage
        collection run would be undesirable. Disabling the garbage collector
        has the unfortunate side-effect that your memory usage will skyrocket.
        """
        if enabled:
            gc.enable()
        else:
            gc.disable()

    def collectGarbage(self):
        """
        Run a garbage collection run.
        """
        gc.collect()

    def _runTask(self, task, ticks=0):
        if not task in self.paused:
            self.currentTask = task
            task.run(ticks)
            self.currentTask = None

    def main(self):
        """Main state loop."""
        done = self.doRun()
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        # evilynux - Estimate the rendered frames per second.
        self.frames = self.frames + 1
        # Estimate every 120 frames when highpriority is True.
        # Estimate every 2*config.fps when highpriority is False,
        # if you are on target, that should be every 2 seconds.
        if (not self.priority and self.frames
                == (self.fps << 1)) or (self.priority and self.frames == 120):
            self.fpsEstimate = self.clock.get_fps()
            # evilynux - Printing on the console with a frozen binary may cause a crash.
            if self.show_fps and not Version.isWindowsExe():
                print("%.2f fps" % self.fpsEstimate)
            self.frames = 0
        return done

    def doRun(self):
        """Run one cycle of the task scheduler engine."""
        if not self.frameTasks and not self.tasks:
            return False

        for task in self.frameTasks:
            self._runTask(task)
        tick = self.clock.get_time()
        for task in self.tasks:
            self._runTask(task, tick)
        self.clock.tick(self.fps)
        return True

    def run(self):
        return self.mainloop()
コード例 #30
0
ファイル: main-2.py プロジェクト: imppppp7/time
def saveaudio():
    path1 = r'C:\Users\Administrator\Desktop\recording\%s.wav' % n
    time = 5
    Audio.record_audio(time, path1)
コード例 #31
0
ファイル: GameEngine.py プロジェクト: Hawkheart/fof-reborn
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")
コード例 #32
0
while 1:
    frame = cv2.imread(r'C:\Users\Administrator\Desktop\image1\%s.png' % n)
    cv2.resize(frame, (800, 600), frame)
    pro.addimage(frame)
    # 调同轴前两个参数调大小,后两个参数调位置,第五个参数调框的宽度
    pro.changeimage(550, 400, 245, 190, 5)
    pro.showimage()
    # 保存一屏的标记图
    cv2.imwrite(r'C:\Users\Administrator\Desktop\image3\%s.png' % n,
                pro.image3)
    # 保存二屏的标记图
    cv2.imwrite(r'C:\Users\Administrator\Desktop\image5\%s.png' % n,
                pro.image5)
    z = cv2.getTrackbarPos('z', 'projector_3')
    print('n=', n)
    # waitkey的时间决定了播放的帧率 waitkey 时间越短,放的越快
    k = cv2.waitKey(100) & 0xFF
    if k == ord('m'):
        pro.mode = not pro.mode
    if k == ord(' '):
        cv2.waitKey()
    if k == ord('z'):
        # n = int(input())
        n = z
    if k == ord('r'):
        # 保存音频,建议在Main-3里面专门录音,不要既录音也画标记,忙不过来
        path1 = r'C:\Users\Administrator\Desktop\recording\%s.wav' % n
        time = 5
        Audio.record_audio(time, path1)
    n += 1
コード例 #33
0
class GameEngine(Engine):
    """The main game engine."""
    def __init__(self, config=None):
        """
    Constructor.

    @param config:  L{Config} instance for settings
    """

        if not config:
            config = Config.load()

        self.config = config

        fps = self.config.get("video", "fps")
        tickrate = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps=fps, tickrate=tickrate)

        pygame.init()

        self.title = _("Frets on Fire")
        self.restartRequested = False
        self.handlingException = False
        self.video = Video(self.title)
        self.audio = Audio()

        Log.debug("Initializing audio.")
        frequency = self.config.get("audio", "frequency")
        bits = self.config.get("audio", "bits")
        stereo = self.config.get("audio", "stereo")
        bufferSize = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency=frequency,
                            bits=bits,
                            stereo=stereo,
                            bufferSize=bufferSize)
        pygame.init()
        self.audio.open(frequency=frequency,
                        bits=bits,
                        stereo=stereo,
                        bufferSize=bufferSize)

        Log.debug("Initializing video.")
        width, height = [
            int(s) for s in self.config.get("video", "resolution").split("x")
        ]
        fullscreen = self.config.get("video", "fullscreen")
        multisamples = self.config.get("video", "multisamples")
        self.video.setMode((width, height),
                           fullscreen=fullscreen,
                           multisamples=multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        self.svg.setRenderingQuality(self.config.get("opengl", "svgquality"))
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]),
                   int(viewport[3]))

        self.input = Input()
        self.view = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource = Resource(Version.dataPath())
        self.server = None
        self.sessions = []
        self.mainloop = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game",
                           "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl",
                            "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized=False)
        self.addTask(self.input, synchronized=False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized=False)
        self.data = Data(self.resource, self.svg)

        self.input.addKeyListener(FullScreenSwitcher(self), priority=True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer = None
        self.startupLayer = None
        self.loadingScreenShown = False

        Log.debug("Ready.")

    def setStartupLayer(self, startupLayer):
        """
    Set the L{Layer} that will be shown when the all
    the resources have been loaded. See L{Data}

    @param startupLayer:    Startup L{Layer}
    """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
    Show or hide the debug layer.

    @type enabled: bool
    """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
    Toggle between fullscreen and windowed mode.

    @return: True on success
    """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def quit(self):
        self.audio.close()
        Engine.quit(self)

    def resizeScreen(self, width, height):
        """
    Resize the game screen.

    @param width:   New width in pixels
    @param height:  New height in pixels
    """
        self.view.setGeometry((0, 0, width, height))
        self.svg.setGeometry((0, 0, width, height))

    def isServerRunning(self):
        return bool(self.server)

    def startServer(self):
        """Start the game server."""
        if not self.server:
            Log.debug("Starting server.")
            self.server = Server(self)
            self.addTask(self.server, synchronized=False)

    def connect(self, host):
        """
    Connect to a game server.

    @param host:  Name of host to connect to
    @return:      L{Session} connected to remote server
    """
        Log.debug("Connecting to host %s." % host)
        session = ClientSession(self)
        session.connect(host)
        self.addTask(session, synchronized=False)
        self.sessions.append(session)
        return session

    def stopServer(self):
        """Stop the game server."""
        if self.server:
            Log.debug("Stopping server.")
            self.removeTask(self.server)
            self.server = None

    def disconnect(self, session):
        """
    Disconnect a L{Session}

    param session:    L{Session} to disconnect
    """
        if session in self.sessions:
            Log.debug("Disconnecting.")
            self.removeTask(session)
            self.sessions.remove(session)

    def loadSvgDrawing(self, target, name, fileName, textureSize=None):
        """
    Load an SVG drawing synchronously.
    
    @param target:      An object that will own the drawing
    @param name:        The name of the attribute the drawing will be assigned to
    @param fileName:    The name of the file in the data directory
    @param textureSize  Either None or (x, y), in which case the file will
                        be rendered to an x by y texture
    @return:            L{SvgDrawing} instance
    """
        return self.data.loadSvgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""
        done = Engine.run(self)
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.svg.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        # Tune the scheduler priority so that transitions are as smooth as possible
        if self.view.isTransitionInProgress():
            self.boostBackgroundThreads(False)
        else:
            self.boostBackgroundThreads(True)

        done = Engine.run(self)
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        return done

    def run(self):
        try:
            return self.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:

            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            Log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
コード例 #34
0
class World(DirectObject):

    def __init__(self):
        
        self.keyMap = {"left":0, "right":0, "forward":0, "cam-left":0, "cam-right":0}
        base.win.setClearColor(Vec4(0,0,0,1))


        self.speed = 0



        self.font_digital = loader.loadFont('font/SFDigitalReadout-Heavy.ttf')


        # Speedometer
        self.speed_img = OnscreenImage(image="models/speedometer.png", scale=.5, pos=(1.1, 0, -.95))
        self.speed_img.setTransparency(TransparencyAttrib.MAlpha)
        OnscreenText(text="km\n/h", style=1, fg=(1, 1, 1, 1),
                     font=self.font_digital, scale=.07, pos=(1.25, -.92))


        # Display Speed
        self.display_speed = OnscreenText(text=str(self.speed), style=1, fg=(1, 1, 1, 1),
                                          pos=(1.3, -0.95), align=TextNode.ARight, scale=.07, font=self.font_digital)

        # Health Bar

        self.bars = {'H' : 100, 'EH' : 0 ,'A' : 0 }

        # bk_text = "This is my Demo"
        # self.textObject = OnscreenText(text = bk_text, pos = (0.55,-0.05),scale = 0.07,fg=(1,0.5,0.5,1),align=TextNode.ACenter,mayChange=1)

        self.Health_bar = DirectWaitBar(text = "", value = 100, pos = (0.280,0,0.475), barColor= (1,0,0,1), frameSize = (0,.705,.3,.35))

        self.EHealth_bar = DirectWaitBar(text = "", value = 0, pos = (1,0,0.475), barColor= (0,1,0,1), frameSize = (0,.23,.3,.35),range = 50 )

        self.Armour_bar = DirectWaitBar(text = "", value = 0, pos = (.43,0,.593), barColor= (159,0,255,1), frameSize = (0,.8,.3,.35))

        # self.bar = DirectWaitBar(text = "hi",
        #     value = 0,
        #     range = 500,
        #     pos = ( 0,0,0), 
        #     barColor = (0.97,0,0,1), 
        #     frameSize = (-0.3,0.3,0.5,0.8),
        #     text_mayChange = 1,
        #     text_shadow =(0,0,0,0.8),
        #     text_fg = (0.9,0.9,0.9,1),
        #     text_scale = 0.025, 
        #     text_pos = (0,0.01,0))


        def getHealthStatus() :
            return self.bars

        def displayBars() :
            health = getHealthStatus()
            self.Health_bar['value'] = health['H']
            self.EHealth_bar['value'] = health['EH']
            self.Armour_bar['value'] = health['A']


        def armourPickup() :
            self.bars['A'] += 25
            displayBars()

        def healthPickup() :
            self.bars['EH'] += 25
            displayBars()

        def decHealth() :
            self.bars['H'] -= 10
            displayBars()


              


        # Post the instructions
        self.frame = OnscreenImage(image = "models/gframe.png", pos = (0,0,0), scale = (1.25, 1, 1) )
        self.frame.setTransparency(TransparencyAttrib.MAlpha)


        # self.title = addTitle("Panda3D Tutorial: Roaming Ralph (Walking on the Moon)")
        self.inst1 = addInstructions(0.95, "[ESC]: Quit")
        self.inst2 = addInstructions(0.90, "[Left Arrow]: Rotate Ralph Left")
        self.inst3 = addInstructions(0.85, "[Right Arrow]: Rotate Ralph Right")
        self.inst4 = addInstructions(0.80, "[Up Arrow]: Run Ralph Forward")
        self.inst6 = addInstructions(0.70, "[A]: Rotate Camera Left")
        self.inst7 = addInstructions(0.65, "[S]: Rotate Camera Right")
        
        # Set up the environment
        #
        self.environ = loader.loadModel("models/square")      
        self.environ.reparentTo(render)
        self.environ.setPos(0,0,0)
        self.environ.setScale(100,100,1)
        self.moon_tex = loader.loadTexture("models/moon_1k_tex.jpg")
    	self.environ.setTexture(self.moon_tex, 1)
        
        # Create the main character, Ralph

        self.ralph = Actor("models/ralph",
                                 {"run":"models/ralph-run",
                                  "walk":"models/ralph-walk"})
        self.ralph.reparentTo(render)
        self.ralph.setScale(.2)
        self.ralph.setPos(0,0,0)

        # Create a floater object.  We use the "floater" as a temporary
        # variable in a variety of calculations.
        
        self.floater = NodePath(PandaNode("floater"))
        self.floater.reparentTo(render)

        # Accept the control keys for movement and rotation

        self.accept("escape", sys.exit)
        self.accept("arrow_left", self.setKey, ["left",1])
        self.accept("arrow_right", self.setKey, ["right",1])
        self.accept("arrow_up", self.setKey, ["forward",1])
        self.accept("a", self.setKey, ["cam-left",1])
        self.accept("s", self.setKey, ["cam-right",1])
        self.accept("arrow_left-up", self.setKey, ["left",0])
        self.accept("arrow_right-up", self.setKey, ["right",0])
        self.accept("arrow_up-up", self.setKey, ["forward",0])
        self.accept("a-up", self.setKey, ["cam-left",0])
        self.accept("s-up", self.setKey, ["cam-right",0])
        self.accept("h", decHealth)
        self.accept("j", healthPickup)
        self.accept("k", armourPickup)

        taskMgr.add(self.move,"moveTask")

        taskMgr.doMethodLater(.1, self.show_speed, 'updateSpeed')

        # Game state variables
        self.isMoving = False

        # Set up the camera
        
        base.disableMouse()
        base.camera.setPos(self.ralph.getX(),self.ralph.getY()+10,2)
        

        # Create some lighting
        ambientLight = AmbientLight("ambientLight")
        ambientLight.setColor(Vec4(.3, .3, .3, 1))
        directionalLight = DirectionalLight("directionalLight")
        directionalLight.setDirection(Vec3(-5, -5, -5))
        directionalLight.setColor(Vec4(1, 1, 1, 1))
        directionalLight.setSpecularColor(Vec4(1, 1, 1, 1))
        render.setLight(render.attachNewNode(ambientLight))
        render.setLight(render.attachNewNode(directionalLight))



        self.audioManager = Audio(self)
        self.audioManager.startAudioManager()

        self.audioManager.initialiseSound(self.ralph)

        
    def show_speed(self, task):
        # self.speed = str(format(self.ralph.getCurrentSpeedKmHour(), '0.2f'))
        # self.speed = 2
        # print self.speed

        # Update Speed Display
        self.display_speed.destroy()
        self.display_speed = OnscreenText(text=str(self.speed), style=3, fg=(1, 1, 1, 1),
            pos=(1.2, -0.95), align=TextNode.ARight, scale=.15, font=self.font_digital)
        return task.cont


        
    
    #Records the state of the arrow keys
    def setKey(self, key, value):
        self.keyMap[key] = value


    
    

    # Accepts arrow keys to move either the player or the menu cursor,
    # Also deals with grid checking and collision detection
    def move(self, task):

        # If the camera-left key is pressed, move camera left.
        # If the camera-right key is pressed, move camera right.

        base.camera.lookAt(self.ralph)
        if (self.keyMap["cam-left"]!=0):
            base.camera.setX(base.camera, -20 * globalClock.getDt())
        if (self.keyMap["cam-right"]!=0):
            base.camera.setX(base.camera, +20 * globalClock.getDt())

        # save ralph's initial position so that we can restore it,
        # in case he falls off the map or runs into something.

        startpos = self.ralph.getPos()

        # If a move-key is pressed, move ralph in the specified direction.

        if (self.keyMap["left"]!=0):
            self.ralph.setH(self.ralph.getH() + 300 * globalClock.getDt())
        if (self.keyMap["right"]!=0):
            self.ralph.setH(self.ralph.getH() - 300 * globalClock.getDt())
        if (self.keyMap["forward"]!=0):
            self.ralph.setY(self.ralph, -25 * globalClock.getDt())
            # print "walk", self.speed 
            if self.speed < 100 :
                self.speed = self.speed + self.speed/100 + 1
            else :
                self.speed = self.speed + self.speed/200 + 1
                # print self.speed
            # self.audioManager.updateSound()
            self.audioManager.updateSound()

        # If ralph is moving, loop the run animation.
        # If he is standing still, stop the animation.

        if (self.keyMap["forward"]!=0) or (self.keyMap["left"]!=0) or (self.keyMap["right"]!=0):
            if self.isMoving is False:
                self.ralph.loop("run")
                # print "run"
                self.isMoving = True
        else:
            if self.isMoving:
                self.ralph.stop()
                self.speed = 0
                self.ralph.pose("walk",5)
                self.isMoving = False

        # If the camera is too far from ralph, move it closer.
        # If the camera is too close to ralph, move it farther.

        camvec = self.ralph.getPos() - base.camera.getPos()
        camvec.setZ(0)
        camdist = camvec.length()
        camvec.normalize()
        if (camdist > 10.0):
            base.camera.setPos(base.camera.getPos() + camvec*(camdist-10))
            camdist = 10.0
        if (camdist < 5.0):
            base.camera.setPos(base.camera.getPos() - camvec*(5-camdist))
            camdist = 5.0

         
        # The camera should look in ralph's direction,
        # but it should also try to stay horizontal, so look at
        # a floater which hovers above ralph's head.
        
        self.floater.setPos(self.ralph.getPos())
        self.floater.setZ(self.ralph.getZ() + 2.0)
        base.camera.lookAt(self.floater)

        return task.cont
コード例 #35
0
import argparse
from Audio import Audio
import rsa
from Cryptographer import Cryptographer
from BBS import BBS

parser = argparse.ArgumentParser(description='Encryptor parser')
parser.add_argument('-i', type=str, default=r'source.wav')
parser.add_argument('-o', type=str, default=r'audio.wav')
parser.add_argument('-fmsg', type=str, default=None)
parser.add_argument('-msg', type=str, default="Hello world!")
parser.add_argument('-enc', type=str, default="utf-8")
args = parser.parse_args()

if args.fmsg is not None:
    with open(args.fmsg, "r") as read_text:
        msg = read_text.read().replace("\n", "*")
else:
    msg = args.msg

with open("public_key.txt", "r") as pr:
    private_str = pr.read().split(" ")
    public = rsa.PublicKey(int(private_str[0]), int(private_str[1]))

audio_test = Audio(filename=args.i)
audio = Audio(filename=args.i)
encrypter = Cryptographer(audio=audio, algorithm=BBS(), coding=args.enc)
encrypter.encrypt(msg, filename=args.o, publicKey=public)
audio2 = Audio(filename=args.o)
print("Successfully encrypted")
コード例 #36
0
ファイル: Controller.py プロジェクト: Besler/StillSystem
    def __init__(self, cuff_pin, bladder_pin, filename):
        print('Setup')
        self.fsm = FSM(Pin(cuff_pin), Pin(bladder_pin), Audio(filename))
        self.Camera = PiVideoStream().start()

        self._sleep_time = 0.01  # ms
コード例 #37
0
    row = create_example( path[dataset], hyper_params , n*(i-1) + j, ref_speech, pri_speech, sec_speech)
    if row is not None:
      batch.append(row)
  print(i)
  return batch

def save_batch(dataset,data):
  df_path = os.path.join(path[dataset],'data_frame.csv')
  df = pd.read_csv(df_path)
  df_batch = pd.DataFrame(data = data, columns = columns)
  df = df.append(df_batch)
  df.to_csv(df_path,index=False)

columns=['key','ref_speech','pri_speech','sec_speech','input_spec_path','output_spec_path','input_phase_path','output_phase_path','dvector_path']
hyper_params = HyperParams()
audio = Audio(hyper_params)
dataset_path = os.path.join('drive','My Drive','LibriSpeech Dataset')
path = {}
path['dev'] = os.path.join(dataset_path,'LibriSpeech Dev Dataset')
path['test'] = os.path.join(dataset_path,'LibriSpeech Test Dataset')
path['train'] = os.path.join(dataset_path ,'LibriSpeech Train Dataset')

with open(os.path.join(path['dev'],'dev_speeches.data'),'rb') as f:
  dev_speeches = pickle.load(f)
with open(os.path.join(path['test'],'test_speeches.data'),'rb') as f:
  test_speeches = pickle.load(f)
with open(os.path.join(path['train'],'train_speeches.data'),'rb') as f:
  train_speeches = pickle.load(f)

embedder_path = os.path.join(dataset_path,"embedder.pt")
embedder_pt = torch.load(embedder_path,map_location=torch.device('cpu'))
コード例 #38
0
    def __init__(self, config=None):

        Log.debug("GameEngine class init (GameEngine.py)...")
        self.mainMenu = None  #placeholder for main menu object - to prevent reinstantiation

        self.currentScene = None

        self.versionString = version  #stump: other version stuff moved to allow full version string to be retrieved without instantiating GameEngine
        self.uploadVersion = "%s-4.0" % Version.PROGRAM_NAME  #akedrou - the version passed to the upload site.

        self.dataPath = Version.dataPath()
        Log.debug(self.versionString + " starting up...")
        Log.debug("Python version: " + sys.version.split(' ')[0])
        Log.debug("Pygame version: " + str(pygame.version.ver))
        Log.debug("PyOpenGL version: " + OpenGL.__version__)
        Log.debug("Numpy version: " + np.__version__)
        Log.debug("PIL version: " + Image.VERSION)
        Log.debug("sys.argv: " + repr(sys.argv))
        Log.debug("os.name: " + os.name)
        Log.debug("sys.platform: " + sys.platform)
        if os.name == 'nt':
            import win32api
            Log.debug("win32api.GetVersionEx(1): " +
                      repr(win32api.GetVersionEx(1)))
        elif os.name == 'posix':
            Log.debug("os.uname(): " + repr(os.uname()))
        """
        Constructor.
        @param config:  L{Config} instance for settings
        """

        self.tutorialFolder = "tutorials"

        if not config:
            config = Config.load()

        self.config = config

        fps = self.config.get("video", "fps")

        self.tasks = []
        self.frameTasks = []
        self.fps = fps
        self.currentTask = None
        self.paused = []
        self.running = True
        self.clock = pygame.time.Clock()

        self.title = self.versionString
        self.restartRequested = False

        # evilynux - Check if theme icon exists first, then fallback on FoFiX icon.
        themename = self.config.get("coffee", "themename")
        themeicon = os.path.join(Version.dataPath(), "themes", themename,
                                 "icon.png")
        fofixicon = os.path.join(Version.dataPath(), "fofix_icon.png")
        icon = None
        if os.path.exists(themeicon):
            icon = themeicon
        elif os.path.exists(fofixicon):
            icon = fofixicon

        self.video = Video(self.title, icon)
        if self.config.get("video", "disable_screensaver"):
            self.video.disableScreensaver()

        self.audio = Audio()
        self.frames = 0
        self.fpsEstimate = 0
        self.priority = self.config.get("engine", "highpriority")
        self.show_fps = self.config.get("video", "show_fps")
        self.advSettings = self.config.get("game", "adv_settings")
        self.restartRequired = False
        self.quicksetRestart = False
        self.quicksetPerf = self.config.get("quickset", "performance")
        self.scrollRate = self.config.get("game", "scroll_rate")
        self.scrollDelay = self.config.get("game", "scroll_delay")

        Log.debug("Initializing audio.")
        frequency = self.config.get("audio", "frequency")
        bits = self.config.get("audio", "bits")
        stereo = self.config.get("audio", "stereo")
        bufferSize = self.config.get("audio", "buffersize")
        self.audio.open(frequency=frequency,
                        bits=bits,
                        stereo=stereo,
                        bufferSize=bufferSize)

        self.cmdPlay = 0
        self.cmdMode = None
        self.cmdDiff = None
        self.cmdPart = None

        self.gameStarted = False
        self.world = None

        self.audioSpeedFactor = 1.0

        Log.debug("Initializing video.")
        #myfingershurt: ensuring windowed mode starts up in center of the screen instead of cascading positions:
        os.environ['SDL_VIDEO_WINDOW_POS'] = 'center'

        width, height = [
            int(s) for s in self.config.get("video", "resolution").split("x")
        ]
        fullscreen = self.config.get("video", "fullscreen")
        multisamples = self.config.get("video", "multisamples")
        self.video.setMode((width, height),
                           fullscreen=fullscreen,
                           multisamples=multisamples)
        Log.debug("OpenGL version: " + glGetString(GL_VERSION))
        Log.debug("OpenGL vendor: " + glGetString(GL_VENDOR))
        Log.debug("OpenGL renderer: " + glGetString(GL_RENDERER))
        Log.debug("OpenGL extensions: " +
                  ' '.join(sorted(glGetString(GL_EXTENSIONS).split())))

        if self.video.default:
            self.config.set("video", "fullscreen", False)
            self.config.set("video", "resolution", "800x600")

        if self.config.get("video", "shader_use"):
            shaders.set(os.path.join(Version.dataPath(), "shaders"))

        # Enable the high priority timer if configured
        if self.priority:
            Log.debug("Enabling high priority timer.")
            self.fps = 0  # High priority

        # evilynux - This was generating an error on the first pass (at least under
        #            GNU/Linux) as the Viewport was not set yet.
        try:
            viewport = glGetIntegerv(GL_VIEWPORT)
        except:
            viewport = [0, 0, width, height]
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.svg = SvgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]),
                   int(viewport[3]))

        self.startupMessages = self.video.error
        self.input = Input()
        self.view = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource = Resource(Version.dataPath())
        self.mainloop = self.loading
        self.menuMusic = False

        self.setlistMsg = None

        # Load game modifications
        Mod.init(self)
        self.addTask(self.input, synchronized=False)

        self.addTask(self.view, synchronized=False)

        self.addTask(self.resource, synchronized=False)

        self.data = Data(self.resource, self.svg)

        ##MFH: Animated stage folder selection option
        #<themename>\Stages still contains the backgrounds for when stage rotation is off, and practice.png
        #subfolders under Stages\ will each be treated as a separate animated stage set

        self.stageFolders = []
        currentTheme = themename

        stagespath = os.path.join(Version.dataPath(), "themes", currentTheme,
                                  "backgrounds")
        themepath = os.path.join(Version.dataPath(), "themes", currentTheme)
        if os.path.exists(stagespath):
            self.stageFolders = []
            allFolders = os.listdir(
                stagespath
            )  #this also includes all the stage files - so check to see if there is at least one .png file inside each folder to be sure it's an animated stage folder
            for name in allFolders:
                aniStageFolderListing = []
                thisIsAnAnimatedStageFolder = False
                try:
                    aniStageFolderListing = os.listdir(
                        os.path.join(stagespath, name))
                except Exception:
                    thisIsAnAnimatedStageFolder = False
                for aniFile in aniStageFolderListing:
                    if os.path.splitext(
                            aniFile
                    )[1] == ".png" or os.path.splitext(
                            aniFile
                    )[1] == ".jpg" or os.path.splitext(
                            aniFile
                    )[1] == ".jpeg":  #we've found at least one .png file here, chances are this is a valid animated stage folder
                        thisIsAnAnimatedStageFolder = True
                if thisIsAnAnimatedStageFolder:
                    self.stageFolders.append(name)

            i = len(self.stageFolders)
            if i > 0:  #only set default to first animated subfolder if one exists - otherwise use Normal!
                defaultAniStage = str(self.stageFolders[0])
            else:
                defaultAniStage = "Normal"
            Log.debug("Default animated stage for " + currentTheme +
                      " theme = " + defaultAniStage)
            aniStageOptions = dict([(str(self.stageFolders[n]),
                                     self.stageFolders[n])
                                    for n in range(0, i)])
            aniStageOptions.update({"Normal": _("Slideshow")})
            if i > 1:  #only add Random setting if more than one animated stage exists
                aniStageOptions.update({"Random": _("Random")})
            Config.define("game",
                          "animated_stage_folder",
                          str,
                          defaultAniStage,
                          text=_("Animated Stage"),
                          options=aniStageOptions)

            #MFH: here, need to track and check a new ini entry for last theme - so when theme changes we can re-default animated stage to first found
            lastTheme = self.config.get("game", "last_theme")
            if lastTheme == "" or lastTheme != currentTheme:  #MFH - no last theme, and theme just changed:
                self.config.set("game", "animated_stage_folder",
                                defaultAniStage)  #force defaultAniStage
            self.config.set("game", "last_theme", currentTheme)

            selectedAnimatedStage = self.config.get("game",
                                                    "animated_stage_folder")
            if selectedAnimatedStage != "Normal" and selectedAnimatedStage != "Random":
                if not os.path.exists(
                        os.path.join(stagespath, selectedAnimatedStage)):
                    Log.warn("Selected animated stage folder " +
                             selectedAnimatedStage +
                             " does not exist, forcing Normal.")
                    self.config.set(
                        "game", "animated_stage_folder", "Normal"
                    )  #MFH: force "Standard" currently selected animated stage folder is invalid
        else:
            Config.define("game",
                          "animated_stage_folder",
                          str,
                          "None",
                          text=_("Animated Stage"),
                          options=["None", _("None")])
            Log.warn(
                "No stages\ folder found, forcing None setting for Animated Stage."
            )
            self.config.set(
                "game", "animated_stage_folder",
                "None")  #MFH: force "None" when Stages folder can't be found

        try:
            fp, pathname, description = imp.find_module(
                "CustomTheme", [themepath])
            theme = imp.load_module("CustomTheme", fp, pathname, description)
            self.theme = theme.CustomTheme(themepath, themename)
        except ImportError:
            self.theme = Theme(themepath, themename)

        self.addTask(self.theme)

        self.input.addKeyListener(FullScreenSwitcher(self), priority=True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer = None
        self.startupLayer = None
        self.loadingScreenShown = False
        self.graphicMenuShown = False

        Log.debug("Ready.")
コード例 #39
0
class PowerupManager:
    #Max number of each powerup
    MAX_COUNT = 2
    POWERUP_RESET_TIME = 10

    def __init__(self, main, actor):
        self.actor = actor
        self.powerupViews = {}
        self.takenPowers = []
        self.activePowers = []
        self.main = main
        self.cManager = main.cManager
        self.Audio = Audio(self)

        powerupTypes = PowerupTypes()
        self.powerupPositions = PowerupPositions().positions

        pwrKey = 1
        instanceCount = 0
        for posKey in self.powerupPositions.keys():
            if instanceCount >= PowerupManager.MAX_COUNT:
                instanceCount = 0
                pwrKey += 1
            posValue = self.powerupPositions[posKey]
            pwrVal = powerupTypes.list[pwrKey]
            posValue["item"] = pwrVal
            self.powerupPositions[posKey] = posValue
            powerUpView = PowerupIcon(self.main, posValue)
            self.powerupViews[posKey] = powerUpView
            if posKey not in self.activePowers:
                self.activePowers.append(posKey)
            instanceCount += 1
            #print "posValue", posValue

    def createPowerup(self, powerupInfo):
        if (powerupInfo['item']['name'] == "SHIELD"):
            return ShieldPowerup(self, powerupInfo)
        elif(powerupInfo['item']['name'] == "BOOST"):
            return BoostPowerup(self, powerupInfo)
        elif(powerupInfo['item']['name'] == "INVINCIBLE"):
            return InvinciblePowerup(self, powerupInfo)
        elif(powerupInfo['item']['name'] == "HEALTH"):
            return HealthPowerup(self, powerupInfo)
    
    def setActors(self, actors):
        self.actors = actors

    def checkPowerPickup(self, task):
        powerObtain = self.powerPickup(self.main.vehicleContainer, self.main.vehicleContainer.chassisNP.getPos(), 1)#actor.actorRadius)
        
        # if powerObtain != 0:
        #     self.handlePowerups(powerObtain)
        return task.cont

    def obtainPowerups(self, powerObtain):
        #print self.powerupPositions[powerObtain]['item']['name']
        if self.powerupPositions[powerObtain]['item']['name'] == "SHIELD":
            self.actor.props.armor += self.powerupPositions[powerObtain]['item']['rating']
            #print "New Armor: ", self.actor.props.armor
            if self.actor.props.armor > self.actor.props.constants.MAX_ARMOR[self.actor.props.type]:
                self.actor.props.armor = self.actor.props.constants.MAX_ARMOR[self.actor.props.type]
            self.main.cManager.sendRequest(Constants.CMSG_HEALTH, self.actor.props.getHitPoint())

        if self.powerupPositions[powerObtain]['item']['name'] == "HEALTH":
            self.actor.props.health += self.powerupPositions[powerObtain]['item']['rating']
            #print "New Health: ", self.actor.props.health
            if self.actor.props.health > self.actor.props.constants.MAX_HEALTH[self.actor.props.type]:
                self.actor.props.health = self.actor.props.constants.MAX_HEALTH[self.actor.props.type]
            self.main.cManager.sendRequest(Constants.CMSG_HEALTH, self.actor.props.getHitPoint())

        if self.powerupPositions[powerObtain]['item']['name'] == "BOOST":
            if self.actor.boostCount < 3:
                self.actor.boostCount += 1

        if self.powerupPositions[powerObtain]['item']['name'] == "INVINCIBLE":
            #print "INVINCIBLE"
            self.actor.props.isInvincible = True
            killInvinsibility = threading.Thread(target=self.resetInvinsibility, args=(powerObtain,))
            killInvinsibility.start()

    def powerPickup(self, actor, actorPos, actorRadius):
        powerObtained = 0
        for posKey in self.powerupPositions.keys():
            powerUp = self.powerupPositions[posKey]
            if (math.pow((actorPos.x - powerUp['x']), 2) + math.pow((actorPos.y - powerUp['y']), 2) + math.pow((actorPos.z - powerUp['z']), 2)
                    <= math.pow(actorRadius, 2)):
                powerObtained = powerUp['id']
                if powerObtained in self.activePowers:
                    self.activePowers.remove(powerObtained)
                    if powerObtained not in self.takenPowers:
                        self.takenPowers.append(powerObtained)
                    self.cManager.sendRequest(Constants.CMSG_POWER_UP, powerUp['id'])
                    self.Audio.play_powerup()
                    # print "powerObtained: ", powerObtained
                    self.resetPowerupsTask(powerObtained)
                break

        return powerObtained

    def resetPowerupsTask(self, powerupId, pickup=False):
        processThread = threading.Thread(target=self.resetPowerup, args=(powerupId,))
        #Remove powerup from available list and add to taken list
        if powerupId in self.activePowers:
            self.activePowers.remove(powerupId)
        if powerupId not in self.takenPowers:
            self.takenPowers.append(powerupId)
        powerView = self.powerupViews[powerupId]
        powerView.removeFromField()
        processThread.start()
        if pickup:
            self.obtainPowerups(powerupId)

    def resetPowerup(self, powerupId):
        time.sleep(PowerupManager.POWERUP_RESET_TIME)
        #print self.takenPowers.get(powerupId)
        if powerupId not in self.activePowers:
            self.activePowers.append(powerupId)
        if powerupId in self.takenPowers:
            self.takenPowers.remove(powerupId)
        powerView = self.powerupViews[powerupId]
        powerView.returnToField()
        #print self.activePowers
        #print self.takenPowers

    def resetInvinsibility(self, powerupId):
        time.sleep(self.powerupPositions[powerupId]['item']['time'])
        self.actor.props.isInvincible = False
コード例 #40
0
"""Beo's famous dance"""
from time import sleep
from Movements import Movements
from Eyes import Eyes
from Audio import Audio
from SensorTouch import SensorTouch

SENSORTOUCH = SensorTouch()
AUDIO = Audio()
EYES = Eyes()
MOVEMENTS = Movements()


def update_touch(dancing):
    """Checks to see if the sensor is being touched"""
    SENSORTOUCH.update_status()
    status = SENSORTOUCH.get_status()
    if status == 1:
        if dancing:
            return False
        else:
            return True
    else:
        return False


DANCING = False
while True:

    DANCING = update_touch(DANCING)
    if DANCING:
コード例 #41
0
 def testOpen(self):
   a = Audio()
   assert a.open()
   a.close()
コード例 #42
0
ファイル: main-4.py プロジェクト: ustc-mbit/time
# 加个trackbar方便快进或快退到某一位置


def nothing(x):
    pass


cv2.createTrackbar('z', 'projector_1', 0, 255, nothing)
while 1:
    frame = cv2.imread(r'C:\Users\Administrator\Desktop\image1\%s.png' % n)
    pro.image3 = cv2.imread(r'C:\Users\Administrator\Desktop\image3\%s.png' % n)
    pro.image5 = cv2.imread(r'C:\Users\Administrator\Desktop\image5\%s.png' % n)
    pro.addimage(frame)
    pro.showimage()
    # path2 = r'C:\Users\Administrator\Desktop\recording\%s.wav' % n
    # Audio.play_audio(path2)
    # waitkey的时间决定了播放的帧率 waitkey 时间越短,放的越快
    print('n=', n)
    z = cv2.getTrackbarPos('z', 'projector_1')
    n += 1
    k = cv2.waitKey(10) & 0xFF
    if k == ord(' '):
        cv2.waitKey()
    if k == ord('z'):
        # n = int(input())
        n = z
    # 修改读哪个音频
    if n == 55 or n == 74:
        path2 = r'C:\Users\Administrator\Desktop\recording\%s.wav' % n
        Audio.play_audio(path2)