Example #1
0
 def notes_in_audio(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Detect Notes in a Audio file')
     audio_file = input('Enter the path for audio file: ')
     music = Music()
     print('Notes in your audio file: {}'.format(
         music.audio_note_detect(audio_file)))
Example #2
0
 def play_audio(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Play Audio from a file')
     audio_file = input('Enter the path for audio file: ')
     music = Music()
     print('Playing Audio...')
     music.play_audio_file(audio_file)
Example #3
0
 def play_mp3(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Play MP3 Audio')
     audio_dir = input('Enter the path for mp3 audio file: ') + '\\'
     mp3_audio_file = input('Enter the name of mp3 audio file: ') + '.mp3'
     music = Music()
     print('Playing Audio...')
     music.play_mp3(audio_dir, mp3_audio_file)
Example #4
0
class StartBoo(StartListener):
    def __init__(self):
        with open(GameController.SETTINGS, "r") as file:
            jsonFile = json.loads(file.read())
            self.__song = jsonFile["booSound"]
            folder = jsonFile["musicFolder"]
        self.__music = Music(folder)

    def start(self):
        self.__music.play(self.__song)
Example #5
0
    def __init__(self, game):
        Game.VisitorGoal.__init__(self, game)
        #Default
        musicFolder = "Music"
        if os.path.exists(GameController.SETTINGS):
            with open(GameController.SETTINGS, "r") as file:
                jsonFile = json.loads(file.read())
                musicFolder = jsonFile["musicFolder"]
                self.finSong = jsonFile['restartSound']

        self.music = Music(musicFolder)
Example #6
0
    def __init__(self, game):
        Game.StopGame.__init__(self, game)
        #Default
        musicFolder = "Music"
        self.__stopSound = "restart.mp3"
        if os.path.exists(GameController.SETTINGS):
            with open(GameController.SETTINGS, "r") as file:
                jsonFile = json.loads(file.read())
                musicFolder = jsonFile["musicFolder"]
                self.__stopSound = jsonFile["powerOffSound"]

        self.__music = Music(musicFolder)
Example #7
0
 def play_tone(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Play Tone Based on Note')
     note = self.__valid_input('Note')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             music.note_beep(note)
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #8
0
 def __init__(self, width, height):
     pygame.init()
     self.width = width
     self.height = height
     self.__set_screen_up()
     self.ladybugs = []
     self.player = Player((self.width - 30) / 2, (self.height - 30) / 2, 0,
                          0)
     self.FPS = config.fps
     self.clock = pygame.time.Clock()
     self.highscores = File(config.highscores_filename)
     self.mixer = Music('Objects/music/MoonlightSonata.mp3')
Example #9
0
    def onClickMusic(self):

        self.changeTab()

        self.musicBtn.setIcon(QIcon("src/menu/music-pressed.png"))

        if self.music == None:
            self.music = Music(self.widget)
        else:
            self.music.show()

        self.current = self.music
        self.currentBtn = self.musicBtn
Example #10
0
 def relative_minor_major(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Relative Minor / Major')
     scl = input('1. Relative Major\n2. Relative Minor\nChoice: ')
     if int(scl) == 1:
         note = self.__valid_input('Minor Note')
         music = Music(note)
         if music.valid_note(note)[1]:
             if music != None:
                 result = music.relative_major(note)
                 print("Relative Major of {}m is: {}".format(note, result))
             else:
                 self.Study_Music_Theory()
         else:
             self.Study_Music()
     elif int(scl) == 2:
         note = self.__valid_input('Minor Note')
         music = Music(note)
         if music.valid_note(note)[1]:
             if music != None:
                 result = music.relative_minor(note)
                 print("Relative Minor of {} is: {}".format(note, result))
             else:
                 self.Study_Music_Theory()
         else:
             self.Study_Music()
Example #11
0
 def major_chord(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Minor Chord')
     note = self.__valid_input('Note')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             result = music.major_chord()
             print("Major Chord Progression for {} Major Scale: ".format(
                 note) + ' '.join(result))
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #12
0
 def chords_in_major_scale(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Notes in Major Scale')
     note = self.__valid_input('Note')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             result = music.chords_in_major_scale()
             print("Notes in {} Major Scale: ".format(note) +
                   ' '.join(result))
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #13
0
 def note_in_major_scales(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Note in Major Scales')
     note = self.__valid_input('Note')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             result = music.note_in_major_scales()
             print("{} Major Note is present in Scales: {}".format(
                 note, ' '.join(result)))
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #14
0
 def note_shift_with_capo_position(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Note in Major Scales')
     note = self.__valid_input('Note')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             capo_position = int(self.__valid_input('Capo on Fret Number'))
             result = music.capo_pos_note_shift(capo_position)
             print("Result Note for {} with Capo at {}: {}".format(
                 note, capo_position, result))
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #15
0
 def __init__(self,
              port,
              mus_dir,
              init_vol=75,
              init_paused=True,
              queue_size=5):
     self.host = guavacado.WebHost()
     self.host.add_addr(port=port)
     self.queue_size = queue_size
     self.music = Music.Music(mus_dir=mus_dir,
                              init_vol=init_vol,
                              init_paused=init_paused)
     self.web_interface = guavacado.WebInterface(host=self.host)
     self.web_files = guavacado.WebFileInterface(host=self.host,
                                                 staticdir='static')
     self.web_interface.connect('/songs/', self.GET_SONGS, 'GET')
     self.web_interface.connect('/add_song/:song', self.ADD_SONG, 'GET')
     self.web_interface.connect('/add_song/:song/:pos', self.ADD_SONG_POS,
                                'GET')
     self.web_interface.connect('/del_song/:song', self.DEL_SONG, 'GET')
     self.web_interface.connect('/set_vol/:vol', self.SET_VOL, 'GET')
     self.web_interface.connect('/skip_song/', self.DEL_TOP_SONG, 'GET')
     self.web_interface.connect('/clear_playlist/', self.CLEAR_SONGS, 'GET')
     self.web_interface.connect('/avail_songs/', self.GET_AVAIL_SONGS,
                                'GET')
     self.web_interface.connect('/song_info/:song', self.GET_SONG_INFO,
                                'GET')
     self.web_interface.connect('/song_info/', self.GET_ALL_SONG_INFO,
                                'GET')
     self.web_interface.connect('/pause/', self.PAUSE, 'GET')
     self.web_interface.connect('/unpause/', self.UNPAUSE, 'GET')
Example #16
0
 def __init__(self, x, y):
     RelativeSprite.__init__(self)
     #self.tilewidth = tilewidth
     self.health = ethunterone.maxHealth
     self.aware = Config['PIXELS_PER_TILE']*8
     #self.id = id
     self.speed = 3
     self.musica = Music()
     
     self.clientUpdate = False
     
     if not ethunterone.images:
         ss = Spritesheet('tiles-bottom.png')
         ethunterone.images['idle'] = []
         ethunterone.images['idle'].append(ss.image_at(Rect(5*45, 6*45, 45, 45)))
         ethunterone.images['idle'].append(ss.image_at(Rect(6*45, 6*45, 45, 45)))
         ethunterone.images['idle'].append(ss.image_at(Rect(0*45, 5*45, 45, 45)))
         ethunterone.images['dead'] = ss.image_at(Rect(1*45, 5*45, 45, 45))
     self.i = random.choice(range(len(ethunterone.images['idle'])))
     self.image = ethunterone.images['idle'][self.i]
     self.rect = self.image.get_rect()
     self.truePos = [x, y]
     self.range = 50
     self.target = None
     self.attackTimeout = cat.attackTimeout
Example #17
0
    def addMusicAuto(self):
        # inputFilepath = 'path/to/file/foobar.txt'
        # filename_w_ext = os.path.basename(inputFilepath)
        # filename, file_extension = os.path.splitext(filename_w_ext)
        # # filename = foobar
        # # file_extension = .txt
        #
        # path, filename = os.path.split(path / to / file / foobar.txt)
        # # path = path/to/file
        # # filename = foobar.txt
        tag = id3.Tag()
        print(glob.glob('musics/*.mp3'))
        for path in glob.glob('musics/*.mp3'):
            print(os.path.splitext(ntpath.basename(path))[0])
            print(path)
            tag.parse(path)
            if tag.artist is not None:
                artist = tag.artist
            else:
                artist = ''

            if tag.genre is not None:
                genre = tag.genre.name
            else:
                genre = ''

            if tag.artist_url is not None:
                url = tag.artist_url.decode("utf-8")
                print(url)
            else:
                url = 'null'

            music = Music(
                os.path.splitext(ntpath.basename(path))[0], genre, artist, url)
            self.addDocument(music)
Example #18
0
 def scale_shift_with_capo_position(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Scale shift with capo position')
     note = self.__valid_input('Original Scale')
     music = Music(note)
     if music.valid_note(note)[1]:
         if music != None:
             capo_position = int(self.__valid_input('Capo on Fret Number'))
             new_note = music.capo_pos_note_shift(capo_position)
             result = music.capo_pos_scale_shift(capo_position)
             print("Result Scale for {} with Capo at {}: {}".format(
                 note, capo_position, new_note))
             print("Notes: " + ' '.join(result))
         else:
             self.Study_Music_Theory()
     else:
         self.Study_Music()
Example #19
0
 def __init__(self):
     self.language=Language()
     self.box = Grid2D(50, 10)
     self.dictionary = Random_Word_Generator()
     self.dictionary.load_dictionary()
     self.game = Game(self.box,self.language)
     self.game.choose_generator(self.dictionary)
     self.music=Music()
     self.game.connect_music(self.music)
Example #20
0
class RestartGoalSound(Game.RestartGame):
    def __init__(self, game):
        Game.RestartGame.__init__(self, game)
        #Default
        musicFolder = "Music"
        self.__restartSound = "restart.mp3"
        if os.path.exists(GameController.SETTINGS):
            with open(GameController.SETTINGS, "r") as file:
                jsonFile = json.loads(file.read())
                musicFolder = jsonFile["musicFolder"]
                self.__restartSound = jsonFile["restartSound"]

        self.__music = Music(musicFolder)

    def motion(self):
        Game.RestartGame.motion(self)
        self.__music.play(self.__restartSound)
        print("Restarting score!")
Example #21
0
 def scale_from_notes(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Scale from Notes')
     # Find Scale from notes and use in best_capo_position() for up-shifting / down-shifting
     notes = self.__valid_input('Notes: ')
     music = Music()
     common_scale = music.common_scale_from_notes(notes.split())
     result = common_scale[0]
     if len(result) > 0:
         if common_scale[1] is '' or common_scale[1] == 'NR':
             print("'{}' Notes are present in '{}' & '{}' Scales".format(
                 notes, result[0], result[1]))
         elif common_scale[1] == 'R':
             print("'{}' Notes are present in '{}' Scale or '{}' Scale".
                   format(notes, result[0], result[1]))
     else:
         print(
             "'{}' Notes does not share common scale... Please Check the Notes Once..."
             .format(notes))
	def perform(self):
		startTime = time() #time will be used to decide when the piece will end
		done = False #determines if program will stop
		m = Music() #public class to do operations relating to playing samples
		while not done:
			print("beginLoop")
			self.decideIfThreadShouldBeStarted(0, m)
   			#self.sleep()
			done = self.decideIfPieceShouldEnd(startTime)
		return
Example #23
0
 def setMusic(self, tconst):
     try:
         # Follows the link to the soundtrack for the movie
         sublink = tconst + '/soundtrack'
         url = 'http://www.imdb.com/title/' + sublink
         # Music will take the url and collect a list of songs from the link
         self.music = Music(url)
     except:
         print('\t*M Error getting music for ' + self.title + ' IMDB-id: ' +
               tconst)
         self.music = None
Example #24
0
async def yt(ctx, search: str):
    voice = await bot_join_voice(ctx)
    if not voice:
        return

    url = search

    song_there = os.path.isfile('song.mp3')
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        await ctx.send("ERROR: Music playing")
        return

    bot_remove_old_queue_folder()

    await ctx.send("Getting song ready now")
    voice = get(client.voice_clients, guild=ctx.guild)

    music = Music()
    music.download_song(url)

    for file in os.listdir("./"):
        if file.endswith('.mp3'):
            name = file
            print("Renamed File: {}".format(name), end='\n\n')
            os.rename(file, 'song.mp3')

    voice.play(discord.FFmpegPCMAudio('song.mp3'),
               after=lambda e: check_queue(voice))
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.5

    if name:
        nname = name.rsplit('-', 2)
        await ctx.send(f'Playing: {nname[1]} by {nname[0]}')
    print('playing\n')
Example #25
0
class StopGame(Game.StopGame):
    def __init__(self, game):
        Game.StopGame.__init__(self, game)
        #Default
        musicFolder = "Music"
        self.__stopSound = "restart.mp3"
        if os.path.exists(GameController.SETTINGS):
            with open(GameController.SETTINGS, "r") as file:
                jsonFile = json.loads(file.read())
                musicFolder = jsonFile["musicFolder"]
                self.__stopSound = jsonFile["powerOffSound"]

        self.__music = Music(musicFolder)

    def motion(self):
        Game.StopGame.motion(self)
        self.__music.play(self.__stopSound)
        #W8 to finish the sound
        while self.__music.isPlayingMusic():
            time.sleep(0.1)
        print("PowerOff raspberry!")
Example #26
0
class VisitorGoalSound(Game.VisitorGoal):
    def __init__(self, game):
        Game.VisitorGoal.__init__(self, game)
        #Default
        musicFolder = "Music"
        if os.path.exists(GameController.SETTINGS):
            with open(GameController.SETTINGS, "r") as file:
                jsonFile = json.loads(file.read())
                musicFolder = jsonFile["musicFolder"]
                self.finSong = jsonFile['restartSound']

        self.music = Music(musicFolder)

    def motion(self):
        Game.VisitorGoal.motion(self)
        # finish = self.game.gameFinish()
        # if not finish:
        if not self.game.gameFinish():
            print("GOOL visitant!")
            self.music.random()
        else:
            self.music.play(self.finSong)
Example #27
0
    def input_selection_change(self):
        selected_text = self.input_menu.currentText()

        # ----- Detect change in menu selection ----- #
        if self.input_change_detect != selected_text:
            self.input_change_detect = selected_text

        # ----- Action performed on Input Menu Values ----- #
        if selected_text != self.select_data:
            option_menu_selected_text = self.option_menu.currentText()
            if option_menu_selected_text == self.options_menu_vals[
                    0]:  # Major Scale
                note = selected_text
                music = Music(note)
                result = music.major_scale()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    1]:  # Major Chord
                note = selected_text
                music = Music(note)
                result = music.major_chord()
                self.output_text.setText('     '.join(result))
            elif option_menu_selected_text == self.options_menu_vals[
                    2]:  # Chords in Major Scale
                note = selected_text
                music = Music(note)
                result = music.chords_in_major_scale()
                self.output_text.setText('     '.join(result))

        # ----- To Keep track of Selections ----- #
        if self.option_menu.currentText() != self.select_data:
            if self.option_menu.currentText() in self.sub_menu_selected:
                self.sub_menu_selected[self.option_menu.currentText()].append(
                    selected_text)
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set(self.sub_menu_selected[
                        self.option_menu.currentText()]))
            else:
                self.sub_menu_selected[self.option_menu.currentText()] = list(
                    set([selected_text]))
Example #28
0
    def run(self):
        while self.running:
            self.clock.tick(30)
            for event in pygame.event.get():
                if (event.type == pygame.QUIT):
                    pygame.quit()
                    sys.exit(0)
                elif (event.type == pygame.KEYDOWN):
                    if (self.surface != self.menu):
                        self.surface = self.menu
                        self.music = Music("mf01.ogg")

                    else:
                        self.keyEvent(event)

            self.update_display(self.surface)
Example #29
0
 def record_play(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Record and Playback')
     music = Music()
     duration = int(input('Enter the duration of recording (in sec): '))
     print('Record your audio after this beep...')
     sleep(2)
     music.freq_beep(1047)
     sleep(.3)
     print('Listening...')
     music.record_and_playback(duration=duration)
     print('Playing Audio...')
Example #30
0
 def record_save(self, wob):
     wob.set_wrong_flag(False)
     self.__talk('You chose Record and Save')
     music = Music()
     duration = int(input('Enter the duration of recording (in sec): '))
     output_file = input('Enter Output File Name: ')  # recordedFile
     output_file = 'assets\\' + output_file + '.wav'
     print('Record your audio after this beep...')
     sleep(2)
     music.freq_beep(1047)
     sleep(.3)
     print('Listening...')
     music.record_and_save(duration=duration, output_file=output_file)
     print('{} file saved successfully...'.format(output_file))
Example #31
0
def on_message(client, userdata, message):
    mp = messageParser()
    list = mp.messageParse(message.payload)

    song = list[0]
    difficulty = list[1]

    m = Music()
    thread = threading.Thread(target=m.playSong, args=(
        song,
        difficulty,
    ))

    if song != "Test":
        s = Score()
        score = s.getScore(song, difficulty)

        mqttc.publish("score", payload=score)

    thread.start()
    thread.join()
Example #32
0
 def __init__(self, x, y):
     RelativeSprite.__init__(self)
     #self.tilewidth = tilewidth
     self.health = cat.maxHealth
     self.aware = Config['PIXELS_PER_TILE']*4
     #self.id = id
     self.speed = 9
     self.musica = Music()
     if not cat.images:
         ss = Spritesheet('tiles-bottom.png')
         cat.images['idle'] = []
         cat.images['idle'].append(ss.image_at(Rect(12*45, 3*45, 90, 90)))
         cat.images['idle'].append(ss.image_at(Rect(14*45, 3*45, 90, 90)))
         cat.images['dead'] = ss.image_at(Rect(10*45, 3*45, 90, 90))
     self.i = 0
     self.image = cat.images['idle'][self.i]
     self.rect = self.image.get_rect()
     self.truePos = [x, y]
     self.range = 50
     self.target = None
     self.attackTimeout = cat.attackTimeout
     self.aggro = False
Example #33
0
    def __init__(self):
        
        pygame.sprite.Sprite.__init__(self)
        if not Hero.images:
            ssFoo = Spritesheet('tiles-bottom.png')
            Hero.images['idle'] = ssFoo.image_at(Rect(0*45, 4*45, 45, 45))
            Hero.images['shooting'] = ssFoo.image_at(Rect(0*45, 6*45, 45, 45))
            Hero.images['knife'] = ssFoo.image_at(Rect(7*45, 6*45, 45, 45))
            Hero.images['dead'] = ssFoo.image_at(Rect(1*45, 6*45, 45, 45))
        self.image = Hero.images['shooting']
        self.rect = self.image.get_rect()
        self.speed = Hero.speed
        self.theta = 0.0
        self.truePos = [0,0]
        self.musica = Music()

        self.health = Hero.maxHealth
        self.alive = self.health > 0

        self.ammo = Hero.CLIP

        self.shootTimeout = -1
        self.slashTimeout = -1
        self.reloadTimeout = -1
Example #34
0
from Synth import Synth
import numpy as np
from Music import Music
import Signal
import thread

#sepapoisid

m = Music()

superMario = [
			 "E F#/Gb4 D 0.25",
			 "E F#/Gb4 D 0.25",
			 "pause 0.25",
			 "E F#/Gb4 D 0.25",
			 "pause 0.25",
			 "C F#/Gb4 D 0.25",
			 "E F#/Gb4 D 0.25",
			 "pause 0.25",
			 "G B G5 0.25",
			 "pause 0.75",
			 "G G G 0.25",
			 "pause 0.75",
			 "C E G 0.25",
			 "pause 0.5",
			 "G C E 0.25",
			 "pause 0.5",
			 "E G C 0.25",
			 "pause 0.5",
			 "A C F 0.25",
			 "pause 0.25",
Example #35
0
# --------------------------
# --- Script starts here ---
# --------------------------

if not os.path.exists("result"):
    os.makedirs("result")

lyrics_file = open('result/lyrics.tex', 'w')
chords_file = open('result/chords.tex', 'w')
presentation_file = open('result/presentation.tex', 'w')

lyrics_file.write(tex_inic % ('lyric', document_title))
chords_file.write(tex_inic % ('chorded', document_title))
presentation_file.write(presentation_inic % (document_title, document_date))

for music_item in music_list:
    subtitle = music_item[0]
    music_file = music_item[1]

    if not music_file == '':
        current_music = Music(music_file, subtitle)
        current_music.write_tex(chords_file, lyrics_file)
        current_music.write_presentation(presentation_file)

lyrics_file.write(tex_fim)
chords_file.write(tex_fim)
presentation_file.write(presentation_fim)

lyrics_file.close()
chords_file.close()
Example #36
0
class ethunterone(RelativeSprite):
    """ Hostile Enemy Hunter Class """
    images = {}
    maxHealth = 30
    attackTimeout = 1000
    power = 10
    def __init__(self, x, y):
        RelativeSprite.__init__(self)
        #self.tilewidth = tilewidth
        self.health = ethunterone.maxHealth
        self.aware = Config['PIXELS_PER_TILE']*8
        #self.id = id
        self.speed = 3
        self.musica = Music()
        
        self.clientUpdate = False
        
        if not ethunterone.images:
            ss = Spritesheet('tiles-bottom.png')
            ethunterone.images['idle'] = []
            ethunterone.images['idle'].append(ss.image_at(Rect(5*45, 6*45, 45, 45)))
            ethunterone.images['idle'].append(ss.image_at(Rect(6*45, 6*45, 45, 45)))
            ethunterone.images['idle'].append(ss.image_at(Rect(0*45, 5*45, 45, 45)))
            ethunterone.images['dead'] = ss.image_at(Rect(1*45, 5*45, 45, 45))
        self.i = random.choice(range(len(ethunterone.images['idle'])))
        self.image = ethunterone.images['idle'][self.i]
        self.rect = self.image.get_rect()
        self.truePos = [x, y]
        self.range = 50
        self.target = None
        self.attackTimeout = cat.attackTimeout
        
    def damage(self, dmg):
        self.health = self.health-dmg
        self.musica.enemydamaged()
        self.aware = 3000
        if self.health <= 0:
            self.die()
    
    def die(self):
        self.alive = False
        self.deathTime = pygame.time.get_ticks()
        self.image = ethunterone.images['dead']
        pos = self.target.rect.center
        targetDir = math.degrees(math.atan2(pos[1] - self.rect.centery, pos[0] - self.rect.centerx))
        self.image = rot_center(self.image, -90-targetDir)

    def update(self, dT):
        RelativeSprite.update(self, dT)

        #change image
        if self.alive:
            self.attackTimeout -= dT
            if random.random() > 0.7:
                self.i = random.choice(range(len(ethunterone.images['idle'])))
            self.image = ethunterone.images['idle'][self.i]
        else:
            self.image = ethunterone.images['dead']
        
        #if self.clientUpdate:
        #    targetDir = -self.theta
        #    self.image = rot_center(self.image, -90-targetDir)
        #    return
        
        #change direction
        if self.alive and self.target:
            pos = self.target.rect.center
            targetDir = math.degrees(math.atan2(pos[1] - self.rect.centery, pos[0] - self.rect.centerx))
            self.image = rot_center(self.image, -90-targetDir)

        #animate
        if self.alive and self.target:
            vel = Vec2d(self.target.truePos) - Vec2d(self.truePos)
            if vel.length < self.aware and vel.length != 0:
                vel.length = self.speed
                self.truePos += vel
        else:
            if hasattr(self, 'deathTime') and self.deathTime < pygame.time.get_ticks() - 1000:
                self.kill()
    
    def ai(self):
        min = float("inf");
        player = -1;
        playloclist = main.getplayerlocations() #todo
        for i in playloclist:
            temp = math.sqrt(player[0]**2+player[1]**2)
            player = i
            if emp < min:
                min = temp
                player = i
        if min <= self.range:
            pass
            #attack
        elif min <= self.aware:
            #coord = #call sterling function
            move(self, coord)
Example #37
0
if len(sys.argv) <= multi_args:
    multiplayer.init_network()
else:
    multiplayer.init_network(sys.argv[-1])
threading.Thread(target=manage_network).start()
# End of this selection of Sterling's bad choices.

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

keys = defaultdict(lambda: False)
buttons = defaultdict(lambda: False)

pygame.init()
musica = Music()
##musica.junglestart()
flags = pygame.DOUBLEBUF|pygame.SRCALPHA|pygame.HWACCEL
if "--fullscreen" in sys.argv:
    flags |= pygame.FULLSCREEN
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), flags)


# set up sprite groups
seeds = {}
lower = defaultdict(pygame.sprite.RenderUpdates)
middle = defaultdict(pygame.sprite.RenderUpdates)
enemies = pygame.sprite.RenderUpdates()
actors = pygame.sprite.RenderUpdates()
allies = pygame.sprite.RenderUpdates()
upper = defaultdict(pygame.sprite.RenderUpdates)
Example #38
0
class Hero(pygame.sprite.Sprite):
    images = {}
    speed = 200.0
    maxHealth = 100
    RELOAD_TIME = 2000
    CLIP = 15
    def __init__(self):
        
        pygame.sprite.Sprite.__init__(self)
        if not Hero.images:
            ssFoo = Spritesheet('tiles-bottom.png')
            Hero.images['idle'] = ssFoo.image_at(Rect(0*45, 4*45, 45, 45))
            Hero.images['shooting'] = ssFoo.image_at(Rect(0*45, 6*45, 45, 45))
            Hero.images['knife'] = ssFoo.image_at(Rect(7*45, 6*45, 45, 45))
            Hero.images['dead'] = ssFoo.image_at(Rect(1*45, 6*45, 45, 45))
        self.image = Hero.images['shooting']
        self.rect = self.image.get_rect()
        self.speed = Hero.speed
        self.theta = 0.0
        self.truePos = [0,0]
        self.musica = Music()

        self.health = Hero.maxHealth
        self.alive = self.health > 0

        self.ammo = Hero.CLIP

        self.shootTimeout = -1
        self.slashTimeout = -1
        self.reloadTimeout = -1
    
    def rot_center(self, image, angle):
        """rotate an image while keeping its center and size"""
        orig_rect = image.get_rect()
        rot_image = pygame.transform.rotate(image, angle)
        rot_rect = orig_rect.copy()
        rot_rect.center = rot_image.get_rect().center
        rot_image = rot_image.subsurface(rot_rect).copy()
        return rot_image

    def shoot(self):
        if self.ammo:
            self.musica.pistolshot()
            self.shootTimeout = 500
            self.image = self.rot_center(Hero.images['shooting'], -90+self.theta)
            self.ammo -= 1
        else:
            self.reload()
            return False

    def reload(self):
        if self.reloadTimeout <= 0:
            self.reloadTimeout = Hero.RELOAD_TIME

    def slash(self):
        if self.alive:
            self.slashTimeout = 200
            self.image = self.rot_center(Hero.images['knife'], -90+self.theta)
        else:
            return False

    def face(self, pos):
        targetDir = math.degrees(math.atan2(pos[1] - self.rect.centery, pos[0] - self.rect.centerx))
        if not self.alive:
            imageString = 'dead'
        elif self.slashTimeout > 0:
            imageString = 'knife'
        elif self.shootTimeout > 0:
            imageString = 'shooting'
        else:
            imageString = 'idle'
        self.image = self.rot_center(Hero.images[imageString], -90-targetDir)
        self.theta = -targetDir

    def damage(self, amount):
        self.musica.damaged()
        self.health -= amount
        if self.health <= 0:
            self.alive = False

    def update(self, dT):
        if self.shootTimeout > 0:
            self.shootTimeout -= dT
        if self.slashTimeout > 0:
            self.slashTimeout -= dT
        if self.reloadTimeout > 0:
            self.reloadTimeout -= dT
            if self.reloadTimeout <= 0:
                self.ammo = Hero.CLIP
        if self.shootTimeout <= 0 and self.slashTimeout <= 0:
            if self.alive:
                string = 'idle'
            else:
                string = 'dead'
            self.image = self.rot_center(Hero.images[string], -90+self.theta)
Example #39
0
class cat(RelativeSprite):
    """Panther Class """
    images = {}
    maxHealth = 50
    attackTimeout = 1000
    power = 20
    def __init__(self, x, y):
        RelativeSprite.__init__(self)
        #self.tilewidth = tilewidth
        self.health = cat.maxHealth
        self.aware = Config['PIXELS_PER_TILE']*4
        #self.id = id
        self.speed = 9
        self.musica = Music()
        if not cat.images:
            ss = Spritesheet('tiles-bottom.png')
            cat.images['idle'] = []
            cat.images['idle'].append(ss.image_at(Rect(12*45, 3*45, 90, 90)))
            cat.images['idle'].append(ss.image_at(Rect(14*45, 3*45, 90, 90)))
            cat.images['dead'] = ss.image_at(Rect(10*45, 3*45, 90, 90))
        self.i = 0
        self.image = cat.images['idle'][self.i]
        self.rect = self.image.get_rect()
        self.truePos = [x, y]
        self.range = 50
        self.target = None
        self.attackTimeout = cat.attackTimeout
        self.aggro = False
    def damage(self, dmg):
        self.health = self.health-dmg
        self.musica.catdmg()
        self.aware = 3000
        if self.health <= 0:
            self.die()
    def die(self):
        self.alive = False
        self.deathTime = pygame.time.get_ticks()
        self.image = cat.images['dead']
        pos = self.target.rect.center
        targetDir = math.degrees(math.atan2(pos[1] - self.rect.centery, pos[0] - self.rect.centerx))
        self.image = rot_center(self.image, targetDir)
    def update(self, dT):
        RelativeSprite.update(self, dT)
        #change image
        if self.alive:
            self.attackTimeout -= dT
            if random.random() > 0.7:
                self.i = random.choice(range(len(cat.images['idle'])))
            self.image = cat.images['idle'][self.i]
        else:
            self.image = cat.images['dead']

        #change direction
        if self.alive and self.target:
            pos = self.target.rect.center
            targetDir = math.degrees(math.atan2(pos[1] - self.rect.centery, pos[0] - self.rect.centerx))
            self.image = rot_center(self.image, -targetDir)

        #animate
        if self.alive and self.target:
            vel = Vec2d(self.target.truePos) - Vec2d(self.truePos)
            if vel.length < self.aware and vel.length > 0:
                self.aggro = True
                vel.length = self.speed
                self.truePos += vel
        else:
            if hasattr(self, 'deathTime') and self.deathTime < pygame.time.get_ticks() - 1000:
                self.kill()
    def ai(self):
        min = float("inf");
        player = -1;
        playloclist = main.getplayerlocations() #todo
        for i in playloclist:
            temp = math.sqrt(player[0]**2+player[1]**2)
            player = i
            if emp < min:
                min = temp
                player = i
        if min <= self.range:
            pass
            #attack
        elif min <= self.aware:
            #coord = #call sterling function
            move(self, coord)
Example #40
0
__author__ = 'adamlind'

import pysynth
from Music import Music

musicMarkov = Music()

musicMarkov.add(["c", 4]) #Row
musicMarkov.add(["c", 4]) #row
musicMarkov.add(["c", 4]) #row
musicMarkov.add(["d", 8]) #your
musicMarkov.add(["e", 4]) #boat
musicMarkov.add(["e", 4]) #gent-
musicMarkov.add(["d", 8]) #-ly
musicMarkov.add(["e", 4]) #down
musicMarkov.add(["f", 8]) #the
musicMarkov.add(["g", 2]) #stream
musicMarkov.add(["c", 8]) #mer-
musicMarkov.add(["c", 8]) #-ri-
musicMarkov.add(["c", 8]) #-ly
musicMarkov.add(["g", 8]) #mer-
musicMarkov.add(["g", 8]) #-ri-
musicMarkov.add(["g", 8]) #-ly
musicMarkov.add(["e", 8]) #mer-
musicMarkov.add(["e", 8]) #-ri-
musicMarkov.add(["e", 8]) #-ly
musicMarkov.add(["c", 8]) #mer-
musicMarkov.add(["c", 8]) #-ri-
musicMarkov.add(["c", 8]) #-ly
musicMarkov.add(["g", 4]) #life
musicMarkov.add(["f", 8]) #is