コード例 #1
0
 def load_sounds(self):
     self.menu_click = Sound()
     self.menu_click.load("click.ogg", False)
     self.menu_click.loop(False)
     self.main_menu_music = Sound()
     self.main_menu_music.load("mainMenuMusic.ogg", True)
     self.main_menu_music.loop(True)
     self.fs_wood = [Sound() for x in range(10)]
     r = 0
     while r < 10:
         self.fs_wood[r].load("fs_wood_" + str(r + 1) + ".ogg", False)
         self.fs_wood[r].loop(False)
         r += 1
コード例 #2
0
ファイル: BB8.py プロジェクト: curtisblack/BB8
    def __init__(self):
        logging.basicConfig(format="%(levelname)s (%(asctime)s): %(message)s",
                            datefmt="%I:%M:%S %p",
                            level=logging.WARNING,
                            filename="/var/tmp/BB8.log")
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        #atexit.register(self.Exit)

        #self.Network = Network()
        self.strip = Adafruit_NeoPixel(3 + 3 + 3 + 7, 13, channel=1)
        #atexit.register(self.Exit)
        #print atexit._exithandlers
        self.strip.begin()

        atexit.register(self.Exit)

        self.Network = Network()
        self.Eye = Eye()
        self.ProcessStateIndicator = ProcessStateIndicator(self)
        self.FrontTopLogicDisplay = FrontTopLogicDisplay(self.strip)
        self.FrontBottomLogicDisplay = FrontBottomLogicDisplay(self.strip)
        self.SideLogicDisplay = SideLogicDisplay(self.strip)
        self.HoloProjector = HoloProjector(self, self.strip)
        self.StatusDisplay = StatusDisplay(self)
        self.Sound = Sound()
コード例 #3
0
def makeEmptySoundBySeconds(seconds, samplingRate=Sound.SAMPLE_RATE):
    if seconds <= 0 or samplingRate <= 0:
        print "makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0"
        raise ValueError
    if seconds > 600:
        print "makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds"
        raise ValueError
    return Sound(seconds * samplingRate, samplingRate)
コード例 #4
0
def makeSound(filename):
    global mediaFolder
    if not os.path.isabs(filename):
        filename = mediaFolder + filename
    if not os.path.isfile(filename):
        print "There is no file at " + filename
        raise ValueError
    return Sound(filename)
コード例 #5
0
def openSoundTool(sound):
    import SoundExplorer
    thecopy = Sound(sound)
    viewer = SoundExplorer(thecopy, 0)
    try:
        viewer.setTitle(getShortPath(sound.getFileName()))
    except:
        viewer.setTitle("No File Name")
コード例 #6
0
ファイル: Game.py プロジェクト: yan0909/2020_script
    def __init__(self):
        self.window = Tk()
        self.window.title("Dori")
        self.window.geometry("800x600")
        self.window.configure(bg="green")

        self.fontstyle = font.Font(self.window,
                                   size=24,
                                   weight='bold',
                                   family='Consolas')
        self.fontstyle2 = font.Font(self.window,
                                    size=15,
                                    weight='bold',
                                    family='Consolas')
        self.fontstyle3 = font.Font(self.window,
                                    size=11,
                                    weight='bold',
                                    family='Consolas')

        self.sound = Sound()

        # 카드 이미지 + 월 + 조합 + 승패
        self.images = {}
        for i in range(10):
            for j in range(2):
                self.images[str(i + 1) + '.' + str(j + 1)] = PhotoImage(
                    file='resource/doriCards/' + str(i + 1) + '.' +
                    str(j + 1) + '.gif')
        self.images['back'] = PhotoImage(
            file='resource/doriCards/cardback.gif')

        self.dealer = Player("dealer")
        self.players = []
        self.players.append(Player("player1"))
        self.players.append(Player("player2"))
        self.players.append(Player("player3"))
        self.money = 1000

        self.SetupGUI()
        self.Initialize()

        l = []
        l.append(Card(16, isVisible=True))
        l.append(Card(18, isVisible=True))
        l.append(Card(0, isVisible=True))
        l.append(Card(3, isVisible=True))
        l.append(Card(7, isVisible=True))
        combos = self.GetCombos(l)
        print(combos)

        for combo in combos:
            print(self.GetComboString(combo))

        combos.sort(key=lambda x: x['power'], reverse=False)
        print(self.GetComboString(combos[0]))

        self.window.mainloop()
コード例 #7
0
ファイル: SoundMgr.py プロジェクト: PlumpMath/RedPanda-1
    def addNewSound(self, name, asset):
        if name in self.sounds:
            name = self.makeNameUnique(name)

        soundObj = Sound(name, asset)
        self.sounds[name] = soundObj
        asset.incSceneCount()

        return soundObj
コード例 #8
0
 def __init__(self, nbPlayer):
     super().__init__()
     # Initialise le nombre de joueur, la map, persos,une listes qui contiendra les bombes, le renderArea et les sons
     self.nbPlayer = nbPlayer
     self.map = Map(nbPlayer)
     self.initCharacter(nbPlayer)
     self.bombs = []
     self.renderArea = RenderArea(self.map, nbPlayer, self.character1,
                                  self.character2, self.character3,
                                  self.character4, self.bombs)
     self.sound = Sound()
コード例 #9
0
ファイル: _Brew.py プロジェクト: neoquinty/brew3.0
 def __init__(self, filepath, t=1, h=1, w=1):
     self.filepath = filepath
     ## initialize T probe
     if t:
         self.probe_T = Temp.Temp()
     ## initialize heat
     if h:
         self.heat = Relay.Relay(21)
     ## initialize sound
     if w:
         self.warning = Sound.Sound()
コード例 #10
0
    def __init__(self,
                 screen,
                 width,
                 height,
                 master_name='Master Example',
                 character_path='../characters/sprites/ordan.png'):

        self.mouse_pos_right_click = None

        self.width = width
        self.height = height

        self.clock = pygame.time.Clock()
        self.frame = Screen.Screen(screen, width, height)
        self.txt = self.frame.txt

        self.sound = Sound.Sound()

        self.arrow_states = {
            K_UP: [False, -1],
            K_DOWN: [False, 1],
            K_LEFT: [False, -1],
            K_RIGHT: [False, 1],
        }

        self.arrow = [0, 0]

        self.sun = Sun.Sun()

        self.p = Person.Person.getNewPlayer(733, 896, master_name,
                                            character_path)

        Person.Person.setMaster(self.p.getId())
        self.path_deque = deque()

        # Bot.BotController.putNewBot((1700, 1700), '../characters/skeleton.png')
        Bot.BotController.putNewBot((912, 482),
                                    '../characters/sprites/black_man.png')

        Bot.BotController.putNewBot((739, 498),
                                    '../characters/sprites/blond_man.png')
        Bot.BotController.putNewBot((935, 602),
                                    '../characters/sprites/dumb_woman.png')
        Bot.BotController.putNewBot((981, 633),
                                    '../characters/sprites/blond_man.png')
        Bot.BotController.putNewBot((975, 597),
                                    '../characters/sprites/blond_woman.png')
        Bot.BotController.putNewBot((1029, 622),
                                    '../characters/sprites/brunette_woman.png')

        # Bot.BotController.putNewBot((600, 800))
        # Bot.BotController.putNewBot((1000, 2000))
        """ self.client = ClientSocket.ClientSocket() """
コード例 #11
0
ファイル: SoundHandler.py プロジェクト: thinkJD/OctoBla
    def __load_sounds__(self, base_path):
        """Load sounds from a given directory use the filename without extension as ID."""
        if not os.path.isdir(base_path):
            print "Error in load_sounds: Path %s is not a directory" % base_path
            return None

        old_dir = os.getcwd()
        os.chdir(base_path)
        # todo pyglet can handle much more filetypes as wave. Implement all formats
        for sound_file in glob.glob("*.MP3"):
            sound_id = sound_file.split('.')[0]
            sound = pyglet.media.load(os.path.join(base_path, sound_file),
                                      streaming=True)
            self.sounds[sound_id] = Sound.Sound(sound_id=sound_id, sound=sound)
        os.chdir(old_dir)
コード例 #12
0
    def moveTir(self, idt, canvas):
        """
        Boucle threadée du deplacement du tir
        Gere aussi l'evenement de collision

        @param idt: id tkinter de l'image
        @param canvas: canvas contenant l'image
        """
        # La pause arrete tout déplacement
        if pause:
            canvas.after(10, lambda: self.moveTir(idt, canvas))
        else:
            # Si l'élément est toujours dans le canvas on continue le traitement sinon le thread se ferme
            if len(canvas.find_withtag(idt)) == 1:
                # Déplacement de l'objet
                canvas.move(idt, 10 + self.vague * 5, 0)
                # Récupération des coordonnées de l'image
                x, y = canvas.coords(idt)
                # Suppression de l'image a partir d'un point
                if x > canvas.winfo_width() - 250:
                    canvas.delete(idt)
                # tpl contient la liste de tous les éléments en collision dans le rectangle x,y/x,y+130
                tpl = canvas.find_overlapping(x, y, x, y + 130)

                # Vérifie si dans cette liste on retrouve un projectile et un ennemi
                if tagged("bullet", tpl, canvas) and tagged(
                        "uni", tpl, canvas):
                    # Actionnement du son d'un ennemi qui meurt
                    Sound("deaduni2.mp3", True).start()
                    # Change le tag de l'ennemi pour eviter d'autre collision
                    canvas.itemconfig(getIDfromTag("uni", tpl, canvas),
                                      image=dead,
                                      tags="dead")
                    # Suppression du projectile
                    canvas.delete(getIDfromTag("bullet", tpl, canvas))
                    # Mise à jour des PV
                    self.updatePV(1)
                    # Augmentation du score
                    self.hero.setScore(self.hero.getScore() + self.vague)
                    # Affichage du score
                    self.printScore()
                    # Mise à jour du nombre d'ennemis
                    self.updateEnnemies()

                else:
                    # Relance la fonction dans un thread toutes les 10ms
                    canvas.after(10, lambda: self.moveTir(idt, canvas))
コード例 #13
0
ファイル: main.py プロジェクト: otaviocap/PlataformerGame
 def __init__(self):
     pygame.init()
     pygame.font.init()
     pygame.mixer.init()
     self.sounds = Sound()
     self.sounds.playMusic()
     self.font = pygame.font.Font(None, 50)
     self.screenSize = SCREEN_SIZE
     self.fps = FPS
     self.screen = pygame.display.set_mode(self.screenSize)
     self.screen.set_alpha(128)
     pygame.display.set_caption(SCREEN_TITLE)
     self.clock = pygame.time.Clock()
     self.time = pygame.time.get_ticks()
     self.timeTimer = pygame.time.get_ticks()
     self.timer = 25
     self.points = 0
     self.gameOver = False
コード例 #14
0
ファイル: R2D2.py プロジェクト: curtisblack/R2D2
    def __init__(self):
        logging.basicConfig(format="%(levelname)s (%(asctime)s): %(message)s", datefmt="%I:%M:%S %p", level=logging.INFO, filename="/var/tmp/R2D2.log")        
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        atexit.register(self.Exit)
        self.MCP3008 = MCP3008(spi=SPI.SpiDev(0, 0))
        self.Voltage = VoltageDivider(self.MCP3008, 0, 984.0, 101.0)
        self.Current = ACS711EX(self.MCP3008, 1)
        self.BrightnessControl = Potentiometer(self.MCP3008, 2)
        self.Battery = LiPo(self.Voltage, self.Current, 6, 10)
        
        self.DomeLightsRelay = self.Relay1 = Relay(16)
        self.DomeServosRelay = self.Relay2 = Relay(17)
        self.DomeMotorRelay = self.Relay3 = Relay(18)
        self.Relay4 = Relay(19)
        self.Relay5 = Relay(20)
        self.SoundRelay = self.Relay6 = Relay(21)
        self.BodyServosRelay = self.Relay7 = Relay(22)
        self.BodyLightsRelay = self.Relay8 = Relay(23)
        self.Relay9 = Relay(24)
        self.Relay10 = Relay(25)
        self.Relay11 = Relay(26)
        self.Relay12 = Relay(27)

        self.Network = Network()
        
        self.Head = HeadMotor(self.DomeMotorRelay)
        self.Sound = Sound()
        self.StatusDisplay = StatusDisplay(self)

        self.FrontLogicDisplay = FrontLogicDisplay(self.DomeLightsRelay)
        self.RearLogicDisplay = RearLogicDisplay(self.DomeLightsRelay)
        self.FrontProcessStateIndicator = FrontProcessStateIndicator(self.DomeLightsRelay)
        self.RearProcessStateIndicator = RearProcessStateIndicator(self.DomeLightsRelay)
        self.FrontHoloProjector = FrontHoloProjector(self.DomeLightsRelay)
        self.TopHoloProjector = TopHoloProjector(self.DomeLightsRelay)
        self.RearHoloProjector = RearHoloProjector(self.DomeLightsRelay)
        self.MagicPanel = MagicPanel(self.DomeLightsRelay)
        self.LifeFormScanner = LifeFormScanner(self.DomeServosRelay)
        self.DomePanels = Panels()
        
        self.BodyServos = Maestro("00126418")
        self.LeftUtilityArm = MaestroServo(self.BodyServos, 16, 2390, 1520, 20, 1)
        self.RightUtilityArm = MaestroServo(self.BodyServos, 17, 2390, 1520, 20, 1)
コード例 #15
0
	def __init__(self, screen_size, fps):
		self._tmx_root = None  # Will be used to store the currently loaded tmx-file:
		self._fps = fps # Save fps
		self._CLOCK = pygame.time.Clock() # Create pygame.Clock for fps-control
		self._draw_tile_ids = False # DEBUG: Draw all ids:

		# Create instance of Graphics-Engine:
		self.graphics = Graphics(self,screen_size)
		# Create instance of World:
		self.world = World(self)
		# Create instance of input-engine
		self.input = Input(self)
		# Create actors-controller
		self.actors = GameActorController(self)
		# Create sound-controller (not jet programmed...)
		self.sound = Sound(self)

		# Finally, first map (temporary):
		self._load_tmx("Forest_N1_1.tmx")

		# Var changed by self.load_new_level. If not false, in the next update cycle, the level gets loaded.
		self._load_new_level = False
コード例 #16
0
    def moveEnnemy(self, idlic, canvas):
        """
        Boucle threadée déplaçant les ennemis
        @param idlic: id de l'objet tkinter
        @param canvas: canvas contenant l'objet tkinter
        @return:
        """
        # La pause arrete tout déplacement
        if pause:
            canvas.after(75, lambda: self.moveEnnemy(idlic, canvas))
        else:
            # Vérifie si le canvas contient toujours l'élémént sinon le thread se ferme
            if len(canvas.find_withtag(idlic)) == 1:
                # Si le joueur est mort, les enemis sont tués
                if self.hero.getPV() == 0:
                    canvas.delete(idlic)
                else:
                    # Déplacement selon la vague. Qaund la vague augmente le deplacement aussi
                    canvas.move(idlic, -30 - self.vague * 10, 0)

                    # Verifie si l'ennemi à dépassé la limite
                    x1, y = canvas.coords(idlic)
                    if x1 <= unicorn[0].width() / 2 + 20:
                        # Suppression de l'élément
                        canvas.delete(idlic)
                        # Mise à jour des PV
                        self.updatePV(-10)
                        # Activation du son d'un ennemi mort mais vainqueur
                        Sound("deaduni.mp3", stop=True).start()
                        # Mise à jour du compteur d'ennemis
                        self.updateEnnemies()

                    else:
                        # Commence le thread
                        canvas.after(75,
                                     lambda: self.moveEnnemy(idlic, canvas))
コード例 #17
0
ファイル: troop.py プロジェクト: NiltonDuarte/WoT
class Troop:
    """This class defines all attributes and functions
	of a troop
	"""
    troopDict = {}
    deathSound = Sound("../sounds/troopFire.wav")
    deathSound.setVolume(0.5)

    def __init__(self, sourceTower, troopType, confFile="troop.xml"):
        self.name = "TroopClass"
        self.ID = str(uuid.uuid4())
        Troop.troopDict[self.ID] = self
        self.sourceTower = sourceTower

        #Getting configuration
        self.modelType = troopType
        self.typ = None
        self.cfTree = ET.parse(confFile)
        self.cfRoot = self.cfTree.getroot()
        for element in self.cfRoot.findall('troop'):
            if (element.get('type') == troopType):
                self.typ = element
        if self.typ == None:
            print "Troop Type do not exist"
            return

        #Getting model configuration
        self.modelTag = self.typ.find('model')

        #Life of a troop
        self.lifeTag = self.typ.find('life')
        self.life = 0
        self.lifeMin = int(self.lifeTag.find('Min').text)
        self.lifeMax = int(self.lifeTag.find('Max').text)
        self.listLife = [self.life, self.lifeMax, self.lifeMin]

        #Speed of a troop
        self.speedTag = self.typ.find('speed')
        self.speed = 0
        self.speedMin = int(self.speedTag.find('Min').text)
        self.speedMax = int(self.speedTag.find('Max').text)
        self.listSpeed = [self.speed, self.speedMax, self.speedMin]

        #Resistence of a troop
        self.resistenceTag = self.typ.find('resistence')
        self.resistence = 0
        self.resistenceMin = int(self.resistenceTag.find('Min').text)
        self.resistenceMax = int(self.resistenceTag.find('Max').text)
        self.listResistence = [
            self.resistence, self.resistenceMax, self.resistenceMin
        ]

        self.listAttributes = [
            self.listLife, self.listSpeed, self.listResistence
        ]

        #troop currency reward
        self.reward = 10

        #Position of the troop
        self.position = sourceTower.position
        self.prevPosition = self.position

        self.initialPoints = int(self.typ.find('initialPoints').text)
        #Graphical part------------------
        self.color = [0, 0, 0]
        self.troopModel = None
        self.artPath = self.typ.find('artPath').text

        #----------------------------------
        #Game engine part------------------
        self.isDead = False
        #----------------------------------

    def defineParameters(self, listParam):
        """Gets the values of listParam and puts them in this order
		[@lifeMin, @lifeMax, 
		@speedMin, @speedMax,
		@resistenceMin, @resistenceMax]
		"""
        if len(listParam) != 6:
            print "Error with the parameters of listParam of the troop"
            return
        self.lifeMin = listParam[0]
        self.lifeMax = listParam[1]
        self.speedMin = listParam[2]
        self.speedMax = listParam[3]
        self.resistenceMin = listParam[4]
        self.resistenceMax = listParam[5]

    def initTroop(self):
        """Initialize the troop with random values inside a interval, **based on tower's attributes**"""
        if (self.initialPoints >= \
        (self.lifeMin + self.speedMin + self.resistenceMin) \
        and self.initialPoints <= \
        (self.lifeMax + self.speedMax + self.resistenceMax)):

            #Attributing the minimum values
            self.listLife[MIN] = self.lifeMin
            self.listSpeed[MIN] = self.speedMin
            self.listResistence[MIN] = self.resistenceMin

            #Attributing the maximum values
            self.listLife[MAX] = self.lifeMax
            self.listSpeed[MAX] = self.speedMax
            self.listResistence[MAX] = self.resistenceMax

            #Attributing random values
            startRandomAttributes(self.listAttributes, self.initialPoints)

            self.initModel(self.position)
            self.initCollisionNode()

            pathFollowList = navigationMesh.getPointsSequence(
                navigationMesh.A_Star_Algorithm(
                    self.position[0], self.position[1],
                    self.sourceTower.sourcePlayer.enemyTarget[0],
                    self.sourceTower.sourcePlayer.enemyTarget[1]))
            velocityCap = self.listSpeed[VALUE]

            AI.Ai.addCharAI(self.troopModel.troopInstance, "troop",
                            [100, 2, velocityCap], pathFollowList)

        else:
            print "Error with the number of initial points of the tower"

    def setInitialPoints(self, points):
        self.initialPoints = points

    def initModel(self, position):
        self.troopModel = TroopModel(self, position, self.modelType,
                                     self.modelTag)

    def moveTroop(self, position):
        self.position = position
        self.troopModel.moveTroopModel(position)

    def initCollisionNode(self):
        self.troopModel.setCollisionNode(self.name, self.ID)

    def updatePosition(self, newPosition):
        self.prevPosition = self.position
        self.position = newPosition

    def updateLife(self, value):
        self.listLife[0] += value
        if self.listLife[0] <= 0:
            self.killTroop()

    def killTroop(self):
        self.listLife[0] = 0
        self.isDead = True
        if self.troopModel.troopColliderNP.node().getNumSolids() > 0:
            self.troopModel.troopColliderNP.node().removeSolid(0)
        self.troopModel.troopInstance.removeNode()
        self.troopModel.loadDeadTroop(self.position)
        #Creating particle system for death animation
        #print "self.troopModel.deadTroopModel = ",self.troopModel.deadTroopModel.__class__
        particleSystem = ParticleSystem(self.position,
                                        self.troopModel.deadTroopModel)
        #Getting the sound effects for troop
        Troop.deathSound.play()

    def isAnimationFinished(self):
        numFrames = self.troopModel.deadTroopModel.getNumFrames('death')
        currFrame = self.troopModel.deadTroopModel.getCurrentFrame('death')

        if (currFrame == numFrames - 1):
            self.troopModel.deadTroopModel.cleanup()
            self.troopModel.deadTroopModel.removeNode()
            return True
        else:
            return False
コード例 #18
0
 def addSoundFromPath(self,name):
   sound = Sound(self,name)
   self.sounds.append(sound)
コード例 #19
0
 def scanSound(self,ext = "wav",isNoise = False):
     for filename in os.listdir(self.getPath()):
         if(os.path.isfile(os.path.join(self.path,filename)) and filename.split(".")[-1] == ext ):#and isNoise == False or ("noise" in filename and "RVB2014" in filename )):
             sound = Sound(self,filename)
             self.sounds.append(sound)
     self.sounds.sort(key = lambda x: x.filename)
コード例 #20
0
ファイル: _ultimate.py プロジェクト: neoquinty/brew3.0
    def start_brew(self):
        ##initialize sound for acoustic warnings
        self.sound = Sound.Sound()
        ##initialize temperature probe
        self.temperature = Temp.Temp()
        ##initialize relay for heat
        self.heat = Relay.Relay(21)

        self.notification = push.Push()

        ##TODO - plotting -
        thread.start_new_thread(self.plot_data, ())

        self.status = "heating to mash"
        self.notification.sendString(self.TITLE, self.status)
        ##TODO - telegram -
        thread.start_new_thread(self.telegramchat, ())
        ##increase to mash temperature
        #        elapsed_time_tmash=self.temperature.increase_to(self.mash_temp, self.heat)
        ##acoustic warning -insertgrain-
        self.notification.sendString(self.TITLE, self.INSERTGRAIN)
        self.status = "mash"
        ##keep tmash constant for mash_time taken from recipe
        #        self.temperature.keep_constant(self.mash_temp, self.mash_time, self.heat)
        ##acoustic warning -removegrain-
        ##self.sound.play(self.REMOVEGRAIN)
        self.notification.sendString(self.TITLE, self.REMOVEGRAIN)
        self.status = "heating to boil"
        ##increase temperature for boiling
        elapsed_time_tboil = self.temperature.increase_to(
            self.boil_temp, self.heat)
        ##start timers
        ##end of boiling - timer -
        timer_end = Timer.Timer(self.boil_time * 60, self.notification,
                                self.BOILEND)
        ##insert cooling element -timer-
        timer_coolinginsert = Timer.Timer(
            (self.boil_time - 15) * 60, self.notification, self.COOLINGINSERT)
        timer_end.start()
        timer_coolinginsert.start()
        if self.hop_bitter:
            ##timer for inserting hops for bittering
            timer_hop_bitter = Timer.Timer(
                (self.boil_time - self.hop_bitter.boil_time) * 60,
                self.notification, self.HOPBITTER)
            timer_hop_bitter.start()
        if self.hop_taste:
            if (self.hop_taste.boil_time > 0):
                ##timer for inserting hops for taste
                timer_hop_taste = Timer.Timer(
                    (self.boil_time - self.hop_taste.boil_time) * 60,
                    self.notification, self.HOPTASTE)
                timer_hop_taste.start()
        if self.hop_flav:
            if (self.hop_flav.boil_time > 0):
                ##timer for inserting hops for flavour
                timer_hop_flav = Timer.Timer(
                    (self.boil_time - self.hop_flav.boil_time) * 60,
                    self.notification, self.HOPFLAV)
                timer_hop_flav.start()

        ##boil -> keep resistance always on for boil time
##start boiling for boil time -heat always on-
        self.status = "boil"
        self.notification.sendString(self.TITLE, self.status)
        self.temperature.boil(self.boil_time, self.heat)

        ##boil end
        ##switch off heat
        self.status = "end"
        self.heat.off()
        self.notification.sendString(self.TITLE, self.BOILEND)
        print "BREW END"
        self.plot = 1
        self.chat = 1

        self.save_data()
        print "data saved!"
        print ""
コード例 #21
0
    def gameInit(self):
        self.sounds = Sound.Sound()
        self.building = Building.Building(self.screen, self.screenSize)
        if self.rainEffect:
            self.weather = []
            for columnNumber in range(1,
                                      self.building.leftWallX // Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.floorY))
            for columnNumber in range(self.building.leftWallX // Weather.SIZE,
                                      self.building.rightWallX //
                                      Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.leftWallX))
            for columnNumber in range(self.building.rightWallX // Weather.SIZE,
                                      self.screenWidth // Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.floorY))
        self.sky = Weather.Sky(self.screen, self.screenWidth,
                               self.screenHeight, self.building.leftWallX,
                               self.building.rightWallX,
                               self.building.ceilingY, self.sounds)

        # RANDOMLY SPAWNED
        self.hero = Character.Player(self.screen, self.building,
                                     self.screenWidth, self.screenHeight)

        self.cultist = Trash.Cultist(self.screen, self.building)
        self.enemiesToSpawn.append(self.cultist)
        self.cultist2 = Trash.Cultist(self.screen, self.building)
        self.enemiesToSpawn.append(self.cultist2)

        self.angel = Trash.Angel(self.screen, self.building)
        #self.enemies.append(self.angel)
        #self.angel.spawn()
        self.enemiesToSpawn.append(self.angel)

        self.skeleton = Trash.Skeleton(self.screen, self.building)
        self.enemiesToSpawn.append(self.skeleton)
        self.skeleton2 = Trash.Skeleton(self.screen, self.building)
        self.enemiesToSpawn.append(self.skeleton2)

        self.bomb = Equipment.Bomb(self.screen, self.building)
        self.equipmentToSpawn.append(self.bomb)
        self.bomb2 = Equipment.Bomb(self.screen, self.building)
        self.equipmentToSpawn.append(self.bomb2)
        self.garlic = Equipment.Garlic(self.screen, self.building)
        self.equipmentToSpawn.append(self.garlic)
        self.garlic2 = Equipment.Garlic(self.screen, self.building)
        self.equipmentToSpawn.append(self.garlic2)
        self.flute = Equipment.Flute(self.screen, self.building)
        self.equipmentToSpawn.append(self.flute)
        self.flute2 = Equipment.Flute(self.screen, self.building)
        self.equipmentToSpawn.append(self.flute2)
        self.rune = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune)
        self.rune2 = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune2)
        self.rune3 = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune3)
        self.sword = Equipment.Sword(self.screen, self.building)
        self.equipmentToSpawn.append(self.sword)
        self.whip = Equipment.Whip(self.screen, self.building)
        self.equipmentToSpawn.append(self.whip)
        self.shield = Equipment.Shield(self.screen, self.building)
        self.equipmentToSpawn.append(self.shield)
コード例 #22
0
ファイル: main.py プロジェクト: eggplantbren/Sounds
from Sound import *

import numpy as np
import matplotlib.pyplot as plt

# Make a middle C
fundamental = 110. * 2.**(3. / 12)
harmonics = np.arange(1, 50)
amplitudes = np.exp(-(harmonics - 2)**2 / 20.**2)

# Supposedly the I vowel (en.wikipedia.org/wiki/Formant)
formant = Formant([240., 2400.], [1., 1.], [100., 100.])

# Make the sound
s = Sound(fundamental, amplitudes)

plt.plot(fundamental * harmonics, s.amplitudes, 'bo-', label='Input Source')
plt.xlabel('Harmonic')
plt.ylabel('Amplitude')

f = fundamental * np.linspace(1., harmonics.max(), 10001)
plt.plot(f, formant.evaluate(f), 'r', label='Formant')

# Apply the formant
s.apply_formant(formant)
s.make_wave_file()

plt.plot(fundamental * harmonics, s.amplitudes, 'go-', label='With Formant')
plt.legend()
plt.show()
コード例 #23
0
 def end(self):
     Sound.Sound().play(self.sound_path)
     self.exit = 1
コード例 #24
0
def handle_full_lines(playground, points, sound: Sound.Sound):
    line_numbers = playground.fullrow()
    line_count = len(line_numbers)

    if line_count > 0:
        playground.delete_line(line_numbers)
        points.lines(line_count)
        sound.play_sound_for_lines(line_count)
    return line_count


pygame.init()
background_colour = (255, 255, 255)
(width, height) = (300, 200)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Tutorial 1')
screen.fill(background_colour)
pygame.display.flip()

clock = pygame.time.Clock()
leonardo = LED_Matrix_Maler.Painter()
tetrisblock = Tetrisblock.Tetrisblock
playground = Playground.Playground(10, 20)
controller = Control_feedback.Controller()
painter = Ws2812Painter.Ws2812Painter()
sound = Sound.Sound()

while True:
    start_screen(playground, painter, controller)
    play_game(playground, clock, painter, leonardo, controller, sound)
コード例 #25
0
ファイル: GameDisplay.py プロジェクト: Garage-at-EEE/ENITIO18
class GameDisplay:
    morser = MorseCode()
    sound = Sound()
    scanner = CardReader()
    dialogue = Dialogue()
    next_Location_Hint = pyqrcode.create(
        'http://maps.ntu.edu.sg/m?q=Lee%20Kong%20Chian%20Lecture%20Theatre&fs=m'
    )
    next_Location_Hint.png('code.png',
                           scale=6,
                           module_color=[0, 0, 0, 128],
                           background=[0xff, 0xff, 0xcc])
    clue1 = 'res/clue1.wav'
    clue2 = 'res/clue2.wav'
    clue_HE = 'res/Clue - HE.mp3'
    clue_IS = 'res/Clue - IS.mp3'
    clue_NO = 'res/Clue - NO.mp3'
    clue_LONGER = 'res/Clue - LONGER.mp3'
    clue_THE = 'res/Clue - THE.mp3'
    clue_SAME = 'res/Clue - SAME.mp3'

    bgMusic = 'res/Basement Floor.mpeg'
    bgImage = 'res/Background.jpg'
    dud1 = "res/Troll Song.wav"
    dud2 = "res/My Heart Will Go On - Recorder By Candlelight by Matt Mulholland.wav"
    dud3 = "res/Rick Astley - Never Gonna Give You Up.wav"
    dud4 = "res/X - Men.wav"

    code_TextBox_Intro = "Welcome to the Morse Code user interface. Fill this textBox with morse code and press " \
                         "the decode button to decode the morse code into words in the textbox below." \
                         "Input '-' for long beep, and '.' for short beep. \n" \
                            "Add a single space between each character and 2 spaces between each word\n" \
                            "DO NOT END WITH >=2 SPACES"
    string_TextBox_Intro = "Fill this box with your message in words, and press the encode button to encode to message" \
                           " to morse code. Press the play button to play the morse code you have written in the textbox" \
                           " above. Press the 'click to scan' button to scan cards placed on the reader"

    def __init__(self, master):
        self.master = master
        self.label = Label(master, bg='black')
        self.master.geometry('600x600')
        self.master.title("Revelations")
        self.label.pack(fill=BOTH, expand=True)

        #   creating necessary frames
        self.frame = Frame(self.label, bg='#212733')
        self.frame.place(relx=0.5, rely=0.5, anchor=CENTER)
        self.subFrame = Frame(self.frame)
        self.subFrame2 = Frame(self.frame)

        #   Adding background image/gif to the main frame
        self.image = Image.open(self.bgImage)
        self.image_copy = self.image.copy()
        self.backgroundImage = ImageTk.PhotoImage(self.image)

        self.label.config(image=self.backgroundImage)
        self.label.bind('<Configure>', self.resize_img)

        #   Creating labels
        self.encodeLabel = Label(self.frame,
                                 text="Encoded Morse Code:",
                                 bg="#212733",
                                 fg="white",
                                 font="none 12 bold")
        self.decodeLabel = Label(self.frame,
                                 text="\nDecoded String:",
                                 bg="#212733",
                                 fg="white",
                                 font="none 12 bold")
        self.submitLabel = Label(self.frame,
                                 text="\nclick to submit decoded message:",
                                 bg="#212733",
                                 fg="white",
                                 font="none 12 bold")

        #   Creating text boxes
        self.codeTextBox = Text(self.frame,
                                width=75,
                                height=6,
                                wrap=WORD,
                                background="white")
        self.stringTextBox = Text(self.frame,
                                  width=75,
                                  height=6,
                                  wrap=WORD,
                                  background="white")

        #   Creating buttons
        self.decodeBtn = Button(self.master,
                                text="DECODE",
                                width=6,
                                command=self.decode)
        self.encodeBtn = Button(self.master,
                                text="ENCODE",
                                width=6,
                                command=self.encode)
        self.clearBtn = Button(self.subFrame2,
                               text="Clear",
                               width=6,
                               command=self.clear_text)
        self.playBtn = Button(self.master,
                              text="Play",
                              width=6,
                              command=self.playCode)
        self.submitBtn = Button(self.frame,
                                text="Submit",
                                width=6,
                                command=self.close_window)
        self.scanBtn = Button(self.subFrame2,
                              text='Click to scan',
                              command=self.create_window)

        #   Arranging the layout
        Label(self.frame,
              text='Morse Decoder User Interface',
              bg='#212733',
              fg='white',
              font='none 24 bold').pack()

        self.encodeLabel.pack()
        self.codeTextBox.pack()

        self.subFrame.pack(anchor=CENTER)
        self.encodeBtn.pack(in_=self.subFrame, side=LEFT)
        self.decodeBtn.pack(in_=self.subFrame, side=LEFT)
        self.playBtn.pack(in_=self.subFrame, side=LEFT)
        Button(self.frame, text='Intro message',
               command=self.intro).pack(in_=self.subFrame, side=LEFT)

        self.subFrame2.pack(anchor=CENTER)
        self.scanBtn.pack(side=LEFT)
        self.clearBtn.pack(side=LEFT)
        self.decodeLabel.pack()
        self.stringTextBox.pack()
        self.submitLabel.pack()
        self.submitBtn.pack()

        self.stringTextBox.insert(1.0, self.string_TextBox_Intro)
        self.codeTextBox.insert(1.0, self.code_TextBox_Intro)

        #   start off with background music on endless loop
        self.sound.playEndlessLoop(self.bgMusic)
        print("playing bg")

    def resize_img(self, event):
        new_width = event.width
        new_height = event.height

        self.image = self.image_copy.resize((new_width, new_height))

        self.background_image = ImageTk.PhotoImage(self.image)
        self.label.configure(image=self.background_image)

    # key down function
    def playtest(self):
        self.sound.playSound('res/clue1.mp3')

    def playCode(self):
        code = self.codeTextBox.get(1.0, 'end-1c')
        self.sound.playMorse(code)

    def decode(self):
        try:
            code = self.codeTextBox.get(1.0, 'end-1c')
            self.decodedString = self.morser.decrypt(code)
        except ValueError:
            self.decodedString = "Invalid morse code. Input '-' for long beep, and '.' for short beep. \n" \
                            "Add a single space between each character and 2 spaces between each word\n" \
                            "DO NOT END WITH >=2 SPACES"
        self.stringTextBox.delete(1.0, END)
        self.stringTextBox.insert(1.0, self.decodedString)

    def encode(self):
        try:
            self.decodedString = self.stringTextBox.get(1.0, 'end-1c')
            code = self.morser.encrypt(self.decodedString)[:-1]
        except KeyError:
            code = "Invalid string. Do not include special symbols like '@#$%^&*' "
        self.codeTextBox.delete(1.0, END)
        self.codeTextBox.insert(1.0, code)

    def clear_text(self):
        self.codeTextBox.delete(1.0, END)
        self.stringTextBox.delete(1.0, END)

    def intro(self):
        self.clear_text()
        self.stringTextBox.insert(1.0, self.string_TextBox_Intro)
        self.codeTextBox.insert(1.0, self.code_TextBox_Intro)

    def create_window(self):
        clue = self.scanner.getClueNum()
        print(clue[0:15])
        if (clue[0:7] == 'Clue_HE'):
            self.sound.playSound(self.clue_HE)
            print('playing clue "HE"')
        elif (clue[0:7] == 'Clue_IS'):
            self.sound.playSound(self.clue_IS)
            print('playing clue "IS"')
        elif (clue[0:7] == 'Clue_NO'):
            self.sound.playSound(self.clue_NO)
            print('playing clue "NO"')
        elif (clue[0:11] == 'Clue_LONGER'):
            self.sound.playSound(self.clue_LONGER)
            print('playing clue "LONGER"')
        elif (clue[0:8] == 'Clue_THE'):
            self.sound.playSound(self.clue_THE)
            print('playing clue "THE"')
        elif (clue[0:9] == 'Clue_SAME'):
            self.sound.playSound(self.clue_SAME)
            print('playing clue "SAME"')
        elif (clue[0:4] == 'Dud1'):
            self.sound.playSound(self.dud1)
        elif (clue[0:4] == 'Dud2'):
            self.sound.playSound(self.dud2)
        elif (clue[0:4] == 'Dud3'):
            self.sound.playSound(self.dud3)
        elif (clue[0:4] == 'Dud4'):
            self.sound.playSound(self.dud4)

    def create_info(self):
        tkinter.messagebox.showinfo(
            'SCANNING MODE', 'You may now place the card on the scanner')

    def close_window(self):
        self.decodedString = self.stringTextBox.get(1.0, 'end-1c').upper()
        if (self.decodedString == 'HE IS NO LONGER THE SAME'):
            self.next_Location_Hint.show()
            self.dialogue.create_first_dialog()
コード例 #26
0
#Vec2 and Vec3 will help positioning the objects
from panda3d.core import Vec2, Vec3
from panda3d.core import Point2, Point3, CardMaker

from direct.gui.DirectGui import *
#This is used to set the color of lifebar and other objects
from panda3d.core import ColorAttrib

#hudTexts is the node that will hold all text nodes of the game
hudTexts = render2d.attachNewNode("HUD Texts")

#HUD_models holds all the models that HUD will use
HUD_models = aspect2d.attachNewNode("HUD Models")

#Getting the sound effects
clickButtonSound = Sound("../sounds/buttonClick.wav")
clickButtonSound.setVolume(0.5)
turnPass_Sound = Sound("../sounds/changeTurn.wav")
turnPass_Sound.setVolume(0.5)
error_Sound = Sound("../sounds/Error.wav")
error_Sound.setVolume(0.5)


class PlayScreenHUD(DirectObject):
    def __init__(self, gameScreenFSM, mousePicking):
        self.gameScreenFSM = gameScreenFSM
        self.mousePicking = mousePicking
        self.playScreenFrame = None
        self.isoScale = 3.2
        self.scale = (self.isoScale, 1, self.isoScale)
        self.artImage = None
コード例 #27
0
    def updategif(self,
                  idimg,
                  canvas,
                  img,
                  img_offset=-1,
                  time=-1,
                  looptime=200,
                  noloop=False):
        """
        Animation des gifs

        @param idimg: id tkinter de l'image
        @param canvas: canvas contenant l'image
        @param img: PhotoImage
        @param img_offset: image de dpart de l'animation
        @param time: si > 0 defini le nombre de boucle avant la destruction de l'image
        @param looptime: temps avant de realancer la boucle
        @param noloop: pas de boucle sur les image, l'image la plus "grande" est la derniere
        """
        # La pause bloque l'animation des gifs
        if pause:
            canvas.after(
                75, lambda: self.updategif(idimg,
                                           canvas,
                                           img,
                                           img_offset=img_offset,
                                           time=time,
                                           looptime=looptime,
                                           noloop=noloop))
        else:
            if "dead" in canvas.gettags(idimg):
                if time == 10:
                    canvas.after(
                        looptime,
                        lambda: self.updategif(idimg, canvas, dead, time + 1))
                else:
                    canvas.delete(idimg)
            elif len(canvas.find_withtag(idimg)) != 0:
                if img_offset == -1:
                    img_offset = randint(0, len(img) - 1)

                elif img_offset >= len(img) and noloop:
                    img_offset = img_offset - 1

                elif img_offset >= len(img):
                    img_offset = 0
                canvas.itemconfig(idimg, image=img[img_offset])

                if not noloop:
                    canvas.after(
                        looptime, lambda: self.updategif(idimg,
                                                         canvas,
                                                         img,
                                                         img_offset + 1,
                                                         looptime=looptime))
                else:
                    Sound("bulletsound.mp3", stop=True).start()
                    canvas.after(
                        looptime, lambda: self.updategif(idimg,
                                                         canvas,
                                                         img,
                                                         img_offset + 1,
                                                         looptime=looptime,
                                                         noloop=True))
コード例 #28
0
def play_game(playground, clock, painter, leonardo,
              controller: Control_feedback.Controller, sound):
    objekt = RandomBlock.RandomBlock()
    current_block = objekt.get_random_block()
    next_block = objekt.get_random_block()
    points = Points.Points()
    sounds = Sound.Sound()
    walkman = Music.Music(0.3)
    walkman.start()
    playground.put_block(current_block)
    game_over = False
    in_pause = False
    action_counter = 0
    while not game_over:
        actions = controller.pressed()
        if in_pause is False and "Pause" in actions:
            in_pause = True
        else:
            if "Pause" in actions:
                in_pause = False

        if not in_pause:
            leonardo.draw(str(points.points), next_block)
            for action in actions:
                future_block = get_block_after_action(current_block, action)
                executable = not playground.collieds(future_block)
                if action == "down":
                    if executable:
                        current_block = future_block

                    else:
                        playground.put_block(current_block)
                        full_line_count = handle_full_lines(
                            playground, points, sound)
                        if current_block.y + full_line_count < 0:
                            game_over = True
                            sounds.game_over()
                        else:
                            if current_block.y < 5:
                                sound.warning()
                            else:
                                sound.reached_limit()
                            current_block, next_block = switch_blocks(
                                next_block, points)

                else:
                    if executable:
                        current_block = future_block
            draw(current_block, painter, playground)
            clock.tick((16.5 / 10000) * points.points + 3.5)

            action_counter += 1
            if action_counter == 4:
                controller.add_action("down")
                action_counter = 0
        else:
            leonardo.write_text("Pause...")
            pygame.time.delay(200)

    walkman.stop()

    game_over_screen(playground, leonardo, points, sounds, controller)
コード例 #29
0
 def init_sound(self):
     """
     Lance le thread de la musique de fond
     @return:
     """
     Sound("testjeu.mp3").start()
コード例 #30
0
def duplicateSound(sound):
    if not isinstance(sound, Sound):
        print "duplicateSound(sound): Input is not a sound"
        raise ValueError
    return Sound(sound)