def createWave(self):
        """
        Create the wave, using whatever starting point (basic, copy, function, etc) is necessary.
        """

        # Check if the wave is unique in the application
        if not self._app.waves().goodWaveName(Util.getWidgetValue(self._ui.createWave_waveName)):
            warningMessage = QMessageBox()
            warningMessage.setWindowTitle("Error!")
            warningMessage.setText("The name you chose has already been used. Please enter a new name.")
            warningMessage.setIcon(QMessageBox.Critical)
            warningMessage.setStandardButtons(QMessageBox.Ok)
            warningMessage.setDefaultButton(QMessageBox.Ok)
            result = warningMessage.exec_()
            return False

        wave = Wave(
            Util.getWidgetValue(self._ui.createWave_waveName), Util.getWidgetValue(self._ui.createWave_dataType)
        )

        # Check how the wave should be initially populated
        initialWaveDataTab = self._ui.waveDataStack.currentWidget().objectName()

        if initialWaveDataTab == "basicTab":
            # Basic wave. Need to determine the type
            basicWaveType = Util.getWidgetValue(self._ui.basicWaveType)
            if basicWaveType == "Blank":
                pass
            elif basicWaveType == "Index (starting at 0)":
                basicWaveLength = Util.getWidgetValue(self._ui.basicWaveLength)
                wave.extend(range(0, basicWaveLength))
            elif basicWaveType == "Index (starting at 1)":
                basicWaveLength = Util.getWidgetValue(self._ui.basicWaveLength)
                wave.extend(range(1, basicWaveLength + 1))

        elif initialWaveDataTab == "copyTab":
            # Copy the data from another wave
            originalWave = (
                self._ui.copyWaveOriginalWave.model()
                .index(self._ui.copyWaveOriginalWave.currentIndex(), 0)
                .internalPointer()
            )
            startingIndex = Util.getWidgetValue(self._ui.copyWaveStartingIndex)
            endingIndex = Util.getWidgetValue(self._ui.copyWaveEndingIndex)
            wave.extend(originalWave.data(startingIndex, endingIndex))

        elif initialWaveDataTab == "functionTab":
            waveLength = Util.getWidgetValue(self._ui.functionWaveLength)
            functionString = Util.getWidgetValue(self._ui.functionEquation)
            data = self.parseFunction(waveLength, functionString)
            wave.extend(data)

        # Add wave to application
        self._app.waves().addWave(wave)

        # Reset certain ui fields
        self._ui.copyWaveOriginalWave.setCurrentIndex(0)
        self._ui.functionInsertWave.setCurrentIndex(0)
Beispiel #2
8
    def importData(self):
        """Import data into the application as waves."""
        
        # Check if the proposed wave name is acceptable
        validatedWaveName = Wave.validateWaveName(Util.getWidgetValue(self._ui.waveName))
        if not self._app.waves().goodWaveName(validatedWaveName):
            badWaveNameMessage = QMessageBox()
            badWaveNameMessage.setText("Wave name is not allowed or already in use.  Please change the wave name.")
            badWaveNameMessage.exec_()
            return False

        # Get data type and size
        uiDataType = Util.getWidgetValue(self._ui.dataType)
        uiByteOrder = Util.getWidgetValue(self._ui.byteOrder)
        dataType = self.dataTypes[uiDataType]['dtype']
        dataTypeChar = self.dataTypes[uiDataType]['char']
        numBytes = self.dataTypes[uiDataType]['numbytes']
        byteOrder = self.byteOrders[uiByteOrder]

        # Load data
        fileName = Util.getWidgetValue(self._ui.fileName)
        if os.path.isfile(fileName):
            data = []
            wave = Wave(str(validatedWaveName), dataType)
            self._app.waves().addWave(wave)

            fh = open(fileName, 'rb')
            binDatum = fh.read(numBytes)
            while binDatum != "":
                try:
                    datum = struct.unpack(byteOrder + dataTypeChar, binDatum)
                    wave.push(datum[0])
                except:
                    pass
                binDatum = fh.read(numBytes)

            




#            data = array.array(dataTypeChar)
#            numDataPoints = os.path.getsize(fileName) / data.itemsize
#            fh = open(fileName, 'rb')
#            data.fromfile(fh, numDataPoints)
#
#            wave = Wave(str(validatedWaveName), dataType)
#            wave.replaceData(data)
#            self._app.waves().addWave(wave)

        # Close window
        self.window.hide()
Beispiel #3
0
	def __init__(self):
		# pygame initializations
		pygame.init()
		self.screen = pygame.display.set_mode(s.SCREEN_SIZE)
		pygame.display.set_caption('Blasteroids')
		self.clock = pygame.time.Clock()
		self.volume = .1
		Sounds.set_se_volume(self.volume)
		self.wave_font = pygame.font.SysFont('arialblack', 35)
		self.score_font = pygame.font.SysFont('arialblack', 17)

		# background and cursor surfaces
		self.surfaces = {'background': pygame.image.load('assets/background.png').convert(),
		                 'cursor': pygame.image.load('assets/cursor.png').convert_alpha(),
		                 'tower': pygame.image.load('assets/tower.png').convert_alpha(),
		                 'hp_outline': pygame.image.load('assets/health_bar_outline.png').convert_alpha()}

		# game's main variables
		self.health = 100
		self.inv = Inventory()
		self.current_weapon = self.inv.armory['cannon']
		self.wave = Wave()
		self.score = 0

		self.firing = False
		self.auto_fire = False
Beispiel #4
0
 def goodWaveName(self, name):
     """
     Determine if name is a good Wave name for this Waves object.  Returns False if name is an empty string.  Returns True if name is not an empty string and is unique.
     """
     
     name = Wave.validateWaveName(name)
     if name == "":
         return False
     return self.uniqueWaveName(name)
Beispiel #5
0
    def importData(self):
        """Import data into the application as waves."""
        
        dataTable = self._ui.data
        
        # Loop through all waves
        for col in range(dataTable.columnCount()):
            dataType = Util.getWidgetValue(dataTable.cellWidget(0, col))
            wave = Wave(str(dataTable.item(1, col).text()), dataType)
            for row in range(2, dataTable.rowCount()):
                if dataTable.item(row, col):
                    wave.push(str(dataTable.item(row, col).text()))
                else:
                    wave.push('')
            self._app.waves().addWave(wave)

        # Close window
        self.clearTable()
        self.window.hide()
Beispiel #6
0
    def validateWaveNames(self):
        """
        Run Wave.validateWaveName on all potential wave names.
        """

        dataTable = self._ui.data

        for col in range(dataTable.columnCount()):
            if dataTable.item(1, col):
                dataTable.setItem(1, col, QTableWidgetItem(Wave.validateWaveName(str(dataTable.item(1, col).text()))))
Beispiel #7
0
class LilypondNotePlayer:

    def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate = 44100):
        self.note = note
        self.volume = 1 # Full colume for starters
        self.samplingRate = samplingRate
        # How many samples will I have to play?
        self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute))
        if self.note.times != None:
            self.totalSamples /= self.note.times
        if note.dots:
            self.totalSamples = int(self.totalSamples * ( 2.0 - pow(2, - note.dots)))
        self.wave = Wave(tuningSystem.getFrequency(note), samplingRate)
        self.counter = 0
        self.volumeRate = None
        self.tied = False
        
    def getNextValue(self):
        self.counter+=1

        # Do we have to lower the volume?
        if not self.tied and self.totalSamples - self.counter <= self.samplingRate * 0.05: # 5 hundredths of a second
            # Have to calculate a volume rate
            if self.totalSamples <= self.counter:
                self.volumeRate = 0
            else:
                self.volumeRate = math.exp(math.log(0.01) / (self.totalSamples - self.counter))
            sys.stderr.flush()
        if self.volumeRate != None:
            self.wave.setVolume(self.volume * self.volumeRate)

        return self.wave.getNextValue()
    
    def setTied(self, value):
        self.tied = value
    
    def isTied(self):
        return self.tied

    def isFinished(self):
        return self.counter >= self.totalSamples
    
    def setNewDuration(self, totalSamples):
        self.counter = 0
        self.totalSamples = totalSamples
    
    def getAngle(self):
        return self.wave.getAngle()
    
    def setAngle(self, angle):
        self.wave.setAngle(angle)
    
    def getFrequency(self):
        return self.wave.getFrequency()
Beispiel #8
0
 def __init__(self, beatsPerMinute, beatUnit, tuningSystem, note, samplingRate = 44100):
     self.note = note
     self.volume = 1 # Full colume for starters
     self.samplingRate = samplingRate
     # How many samples will I have to play?
     self.totalSamples = int(beatUnit * samplingRate * 60 / (note.duration * beatsPerMinute))
     if self.note.times != None:
         self.totalSamples /= self.note.times
     if note.dots:
         self.totalSamples = int(self.totalSamples * ( 2.0 - pow(2, - note.dots)))
     self.wave = Wave(tuningSystem.getFrequency(note), samplingRate)
     self.counter = 0
     self.volumeRate = None
     self.tied = False
Beispiel #9
0
class TrackPlayer:
    """
    Will play a note that's provided to it
    """

    def __init__(self, system, samplingRate = 44100):
        self.system = system
        self.wave = None
        self.samplingRate = samplingRate

        self.samplesToMute = None

    def play(self, musicalNote):
        if musicalNote == None:
            self.mute()
        else:
            self.wave = Wave(self.system.getFrequency(musicalNote), self.samplingRate)
            self.samplesToMute = None

    def mute(self, samplesToMute = None):
        if samplesToMute == None:
            # mute inmediately
            self.volume=0
            if self.wave != None:
                self.wave.setVolume(0)
        else:
            self.samplesToMute = samplesToMute
            # What is the rate for each volume decrease to apply?
            self.volume=1
            self.decrementRate = math.exp(math.log(0.01) / samplesToMute)

    def getNextValue(self):
        if self.wave == None:
            return 0
        if self.samplesToMute != None:
            self.samplesToMute -= 1
            # The volume?
            self.volume*=self.decrementRate
            self.wave.setVolume(self.volume)
        return self.wave.getNextValue()

    def getFrequency(self):
        if self.wave == None:
            return None
        else:
            return self.wave.getFrequency()
Beispiel #10
0
        self.pcm = pcm
        self.data = data

    def run(self):
        self.pcm.write(self.data)

if __name__ == "__main__":
    import math
    import sys
    argc = len(sys.argv)
    leftChannel = None
    rightChannel = None
    if argc == 1:
        print "Have to provide either a single frequency to play or a frequency for each channel (left channel first)"
        sys.exit(1)
    elif argc == 2:
        # Provided a single frequency for both channels
        leftChannel = Wave(float(sys.argv[1]), 11025)
    else:
        leftChannel = Wave(float(sys.argv[1]), 11025)
        rightChannel = Wave(float(sys.argv[2]), 11025)
    
    player = WavePlayer(11025)
    while True:
        leftHeight = leftChannel.getNextValue()
        if rightChannel == None:
            rightHeight = leftHeight
        else:
            rightHeight = rightChannel.getNextValue()
        player.play(leftHeight, rightHeight)
Beispiel #11
0
    def __init__(self, pcm, data):
        Thread.__init__(self)
        self.pcm = pcm
        self.data = data

    def run(self):
        self.pcm.write(self.data)

if __name__ == "__main__":
    import math
    import sys
    argc = len(sys.argv)
    channel = None
    frequencies = list()
    if argc == 1:
        print "Have to provide frequencies to play during a second each"
        sys.exit(1)
    for i in range(1, argc):
        frequencies.append(float(sys.argv[i]))
    
    player = WavePlayer(11025)
    channel = Wave(frequencies[0], 11025)
    for i in frequencies:
        sys.stderr.write("Playing frequency " + str(i) + "\n")
        sys.stderr.flush()
        channel.setFrequency(i)
        for j in range(0, 11025):
            height = channel.getNextValue()
            player.play(height)
Beispiel #12
0
 def play(self, musicalNote):
     if musicalNote == None:
         self.mute()
     else:
         self.wave = Wave(self.system.getFrequency(musicalNote), self.samplingRate)
         self.samplesToMute = None
Beispiel #13
0
class Game:
	def __init__(self):
		# pygame initializations
		pygame.init()
		self.screen = pygame.display.set_mode(s.SCREEN_SIZE)
		pygame.display.set_caption('Blasteroids')
		self.clock = pygame.time.Clock()
		self.volume = .1
		Sounds.set_se_volume(self.volume)
		self.wave_font = pygame.font.SysFont('arialblack', 35)
		self.score_font = pygame.font.SysFont('arialblack', 17)

		# background and cursor surfaces
		self.surfaces = {'background': pygame.image.load('assets/background.png').convert(),
		                 'cursor': pygame.image.load('assets/cursor.png').convert_alpha(),
		                 'tower': pygame.image.load('assets/tower.png').convert_alpha(),
		                 'hp_outline': pygame.image.load('assets/health_bar_outline.png').convert_alpha()}

		# game's main variables
		self.health = 100
		self.inv = Inventory()
		self.current_weapon = self.inv.armory['cannon']
		self.wave = Wave()
		self.score = 0

		self.firing = False
		self.auto_fire = False

	def play(self):
		# Show title splash screen, start main game loop once title is closed
		title_splash = TitleScreen(self.screen)
		title_splash.play_screen()
		Sounds.play_music(Sounds.MAIN_MUSIC)
		# main loop
		while 1:
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					pygame.quit()
					quit()
				# Shoot stuff (toggle auto-fire):
				elif event.type == pygame.MOUSEBUTTONDOWN:
					self.firing = True
				elif event.type == pygame.MOUSEBUTTONUP:
					self.firing = False
				# Keyboard press events:
				elif event.type is pygame.KEYDOWN:
					if event.key == pygame.K_ESCAPE:
						pygame.quit()
						quit()
					# Toggle full screen with 'f' key:
					elif event.key == pygame.K_f:
						self._toggle_full_screen()
					# Toggle sound effects with ''n' key:
					elif event.key == pygame.K_n:
						if Sounds.get_se_volume() == 0:
							Sounds.set_se_volume(self.volume)
						else:
							Sounds.set_se_volume(0)
					# Toggle music with 'm' key:
					elif event.key == pygame.K_m:
						if Sounds.get_music_volume() == 0:
							Sounds.set_music_volume(self.volume)
						else:
							Sounds.set_music_volume(0)
					# Toggle auto fire with 'r' key:
					elif event.key == pygame.K_r:
						if not self.auto_fire:
							self.auto_fire = True
						else:
							self.auto_fire = False
					# Switch weapons with '1' or '2' keys:
					elif event.key == pygame.K_1:
						self.switch_weapons('cannon')
					elif event.key == pygame.K_2:
						self.switch_weapons('laser gun')

			# check for game over instance
			if self.health <= 0:
				Sounds.stop_music()
				pygame.mouse.set_visible(True)
				go = GameOverScreen(self.screen)
				go.play_screen()
				self._reset()

			# enable rapid fire when holding down the mouse:
			if self.firing or self.auto_fire:
				self.current_weapon.fire(pygame.mouse.get_pos())

			# blit most background images and update their positions
			self.display_and_update()

			# collision handlers
			self.collision_handler()
			self.remove_excess_sprites()
			self.check_damage_dealt()
			self.blit_health()

			# wave mechanics
			if self.wave.is_wave_intermission():
				# if new wave just started (5 seconds ago or less), just show wave text:
				self.blit_wave_text()
			elif not self.wave.wave_is_over():
				# wave ongoing, add asteroids:
				self.wave.add_asteroids()
			else:   # wave ended, start new wave
				self.wave.start_new_wave()

			pygame.display.update()
			self.clock.tick(s.FPS)

	def switch_weapons(self, new_weapon):
		if self.current_weapon != self.inv.armory[new_weapon]:
			self.inv.armory[new_weapon].projectile_group.add(
				self.current_weapon.projectile_group
			)
			self.current_weapon.projectile_group.empty()
			self.current_weapon = self.inv.armory[new_weapon]

	# blit backgrounds, projectiles, asteroids, score
	# update asteroid and projectile positions
	def display_and_update(self):
		self.screen.blit(self.surfaces['background'], (0, 0))
		self.blit_projectiles()
		self.screen.blit(self.surfaces['tower'], s.TOWER_POS)
		self.blit_asteroids()
		score_text = self.score_font.render(str(self.score), 1, s.WHITE)
		self.screen.blit(score_text, s.SCORE_TEXT_POS)

		# display cross hair as mouse cursor
		x, y = pygame.mouse.get_pos()
		self.screen.blit(self.surfaces['cursor'], (x - 9, y - 9))

	def collision_handler(self):
		for shot in self.current_weapon.projectile_group:
			for asteroid in self.wave.asteroid_group:
				# upon collision, destroy projectile and subtract asteroid health
				if pygame.sprite.collide_mask(shot, asteroid):
					self.current_weapon.projectile_group.remove(shot)
					asteroid.health -= self.current_weapon.damage
					if asteroid.health <= 0:    # destroy asteroid
						if asteroid.type == 'large':
							self.wave.asteroid_group.add(asteroid.spawn_children())
						self.score += asteroid.score
						self.wave.asteroid_group.remove(asteroid)
						Sounds.EXPLOSION.play()
					return

	def remove_excess_sprites(self):
		# remove projectiles falling outside of screen
		for p in self.current_weapon.projectile_group:
			if (p.position[0] < 0 or p.position[0] > s.SCREEN_WIDTH
						or p.position[1] < 0 or p.position[1] > s.SCREEN_HEIGHT):
				self.current_weapon.projectile_group.remove(p)

	def check_damage_dealt(self):
		# if an asteroid reaches its destination, deal damage to player and remove
		for a in self.wave.asteroid_group:
			if a.position[1] >= a.destination[1]:
				self.health -= a.damage
				self.wave.asteroid_group.remove(a)
				Sounds.HEALTH_LOSS.play()

	def blit_projectiles(self):
			self.current_weapon.projectile_group.update()
			self.current_weapon.projectile_group.draw(self.screen)

	def blit_asteroids(self):
			self.wave.asteroid_group.update()
			self.wave.asteroid_group.draw(self.screen)

	def blit_wave_text(self):
		wave_text = self.wave_font.render('W A V E  ' + str(self.wave.wave_number + 1), 1, s.YELLOW)
		self.screen.blit(wave_text, s.WAVE_TEXT_POS)

	def blit_health(self):
		self.screen.blit(self.surfaces['hp_outline'], s.HEALTH_BAR_OUTLINE)
		remaining_health = self.health / 100.0
		if self.health > 0:
			pygame.draw.rect(self.screen, s.RED,
			                 (s.HP_BAR_X, s.HP_BAR_Y, s.HP_BAR_LENGTH * remaining_health, s.HP_BAR_HEIGHT))

	def _toggle_full_screen(self):
		if pygame.display.get_driver() == 'x11':
			pygame.display.toggle_fullscreen()
		else:
			if s.FULL_SCREEN:
				self.screen = pygame.display.set_mode(s.SCREEN_SIZE)
			else:
				self.screen = pygame.display.set_mode(s.SCREEN_SIZE, pygame.FULLSCREEN)
				s.FULL_SCREEN = not s.FULL_SCREEN
				self.screen.blit(self.screen.copy(), (0, 0))
				pygame.display.update()

	def _reset(self):
		self.health = 100
		self.inv = Inventory()
		self.current_weapon = self.inv.armory['cannon']
		self.wave = Wave()
		self.score = 0
Beispiel #14
0
	def _reset(self):
		self.health = 100
		self.inv = Inventory()
		self.current_weapon = self.inv.armory['cannon']
		self.wave = Wave()
		self.score = 0