def __loadAudio(self):
        """
            Loads voice and sound effects files for this menu.
        """
        fileLocs = FileLocations()
        self.__menuSoundFilename = {
            "done": "\menu_00_01.ogg",
            "retry": "\menu_02_09.ogg",
            "back": "\menu_02_06.ogg"
        }
        if self.__type == "loadAccount":
            self.__menuSoundFilename["prompt"] = "\menu_02_05.ogg"
            self.__menuSoundFilename["success"] = "\menu_02_11.ogg"
            self.__menuSoundFilename["failure"] = "\menu_02_07.ogg"
        if self.__type == "createAccount":
            self.__menuSoundFilename["prompt"] = "\menu_02_04.ogg"
            self.__menuSoundFilename["success"] = "\menu_02_10.ogg"
            self.__menuSoundFilename["failure"] = "\menu_02_08.ogg"
        if self.__type == "deleteAccount":
            self.__menuSoundFilename["prompt"] = "\menu_02_12.ogg"
            self.__menuSoundFilename["success"] = "\menu_02_13.ogg"
            self.__menuSoundFilename["failure"] = "\menu_02_07.ogg"

        ###load sounds
        self.__menuSound = {}
        for type, filename in self.__menuSoundFilename.iteritems():
            self.__menuSound[type] = pygame.mixer.Sound(fileLocs.menuSounds +
                                                        filename)

        self.__narrationChannel = pygame.mixer.Channel(0)
예제 #2
0
    def __initMenuStatus(self):
        """
           Builds a list of files that describe the player's current game choices and login settings.
           Must be used before __playMenuStatus
        """
        fileLocs = FileLocations()
        self.__statusIndex = 0
        self.__statusPlaying = True

        #build the list of files to play
        self.__status = [
            pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_04.ogg")
        ]
        if self.__game.getNumPlayers() == 1:
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_05.ogg"))
        else:
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_06.ogg"))
        if self.__game.getGameMode() == 0:
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_07.ogg"))
        else:
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_08.ogg"))
        if self.__game.getPlayer(0).getName() == "New player":
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_02.ogg"))
        else:
            self.__status.append(
                pygame.mixer.Sound(fileLocs.menuSounds + r"\menu_00_03.ogg"))
예제 #3
0
    def __loadAudio(self):
        """
            Loads voice and sound effects files for this menu.
        """
        fileLocs = FileLocations()
        self.__menuSoundFilename = [
            "\menu_04_02.ogg", "\menu_04_04.ogg", "\menu_04_06.ogg",
            "\menu_04_08.ogg", "\menu_00_01.ogg"
        ]
        self.__menuSound = []
        for filename in self.__menuSoundFilename:
            self.__menuSound.append(
                pygame.mixer.Sound(fileLocs.menuSounds + filename))

        #screensize insert sounds
        self.__screensizeSoundFilename = [
            "\menu_04_11.ogg", "\menu_04_12.ogg", "\menu_04_13.ogg"
        ]
        self.__screensizeSound = []
        for filename in self.__screensizeSoundFilename:
            self.__screensizeSound.append(
                pygame.mixer.Sound(fileLocs.menuSounds + filename))

        self.__louderSound = pygame.mixer.Sound(fileLocs.menuSounds +
                                                r"\menu_04_10.ogg")
        self.__quieterSound = pygame.mixer.Sound(fileLocs.menuSounds +
                                                 r"\menu_04_09.ogg")

        #use one channel for narration to avoid multiple voice items playing at the same time
        self.__narrationChannel = pygame.mixer.Channel(0)
예제 #4
0
    def __loadAudio(self):
        """
            Loads voice and sound effects files for this menu.
        """
        fileLocs = FileLocations()
        self.__menuSoundsFilename = [
            "\menu_06_05.ogg", "\menu_06_06.ogg", "\menu_00_01.ogg"
        ]
        self.__menuSound = []
        for filename in self.__menuSoundsFilename:
            self.__menuSound.append(
                pygame.mixer.Sound(fileLocs.menuSounds + filename))

        self.__welcomeMessage = pygame.mixer.Sound(fileLocs.menuSounds +
                                                   r"\menu_06_01.ogg")
        self.__navMessage1 = pygame.mixer.Sound(fileLocs.menuSounds +
                                                r"\menu_06_03.ogg")
        self.__navMessage2 = pygame.mixer.Sound(fileLocs.menuSounds +
                                                r"\menu_06_04.ogg")

        self.__howto1 = pygame.mixer.Sound(fileLocs.menuSounds +
                                           r"\menu_08_01.ogg")
        self.__howto2 = pygame.mixer.Sound(fileLocs.menuSounds +
                                           r"\menu_08_02.ogg")
        self.__howto3 = pygame.mixer.Sound(fileLocs.menuSounds +
                                           r"\menu_08_03.ogg")

        self.__soundController = SoundEffectController()
        self.__soundController.queueSound(self.__welcomeMessage)
        self.__soundController.queueSound(self.__navMessage1)
        self.__soundController.queueSound(self.__navMessage2)

        self.__narrationChannel = pygame.mixer.Channel(0)
예제 #5
0
 def setNewPlayerName(self, playerName):
     """
        Sets player name to passed-in name only if no name has already been set.
        If the passed-in playerName is already in use, the name will not be
        added to the list a second time.  The method returns true if the
        name is added, otherwise it will return false.
     """
     if(self.__playerName=="???" and not(self.__playerAlreadyExists(playerName)) ):
           #verify that there isn't already a player by this name
         fileLocs=FileLocations()
         filename = fileLocs.playerProfiles+r"\profiles.p"
         playerList = []
         index = -1
         f = None
         try:
               #load list of players -- if there's no file, then we skip this step 
             f = open(filename, "r")
             playerList = pickle.load(f)
             f.close()                
         except IOError:    
             pass
         finally:
               #add name to list
             self.__playerName=playerName
             playerList.append(playerName)
             try:
                 f = open(filename,"w")
                 pickle.dump(playerList, f)
                 f.close()
                 self.savePlayerInfo()
             except IOError:
                 raise PlayerIOError("Unable to add player name to profile.p")
             return True
     else:
         return False ##unsuccessful -- return false
예제 #6
0
 def __loadAudio(self):
     """
         Loads voice and sound effects files for this menu.
     """
     fileLocs=FileLocations()
     self.__menuSoundFilename=["\menu_03_01.ogg", "\menu_03_03.ogg", "\menu_01_02.ogg","\menu_01_07.ogg", "\menu_00_01.ogg"]
     self.__menuSound=[]
     for filename in self.__menuSoundFilename:
         self.__menuSound.append(pygame.mixer.Sound(fileLocs.menuSounds+filename))
         
       #difficulty insert sounds
     self.__difficultySoundFilename=["\menu_00_10.ogg", "\menu_00_11.ogg", "\menu_00_12.ogg"]
     self.__difficultySound=[]
     for filename in self.__difficultySoundFilename:
         self.__difficultySound.append(pygame.mixer.Sound(fileLocs.menuSounds+filename))
         
       #mode insert sounds
     self.__modeSoundFilename=["\menu_00_07.ogg","\menu_00_08.ogg"]
     self.__modeSound=[]
     for filename in self.__modeSoundFilename:
         self.__modeSound.append(pygame.mixer.Sound(fileLocs.menuSounds+filename))
     
       #one-off sounds
     self.__modeChange_fail = pygame.mixer.Sound(fileLocs.menuSounds+r"\menu_03_04.ogg")
             
       #use one channel for narration to avoid multiple voice items playing at the same time
     self.__narrationChannel = pygame.mixer.Channel(0)
    def __init__(self, volume=1):
        pygame.mixer.init()

        self.fileLocs = FileLocations()
        self.numberSpeaker = NumberSpeaker()
        self.channel = pygame.mixer.Channel(1)
        self.soundQueue = []
        self.channel.set_volume(volume)
    def __loadImages(self):
        """
            Loads images for menus, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()
        menuImage_file = fileLocs.images_menus + r"\songChooserMenu.png"
        note_file = fileLocs.images_menus + r"\note.png"
        menu_bkgrd_file = fileLocs.images_menus + r"\menu_right.png"

        self.__menuImage = pygame.image.load(menuImage_file).convert_alpha()
        self.__noteImage = pygame.image.load(note_file).convert_alpha()
        self.__bkgrd_rightImage = pygame.image.load(
            menu_bkgrd_file).convert_alpha()

        #scale note to match font height
        note_x, note_y = self.__noteImage.get_size()
        self.__noteImage = pygame.transform.scale(self.__noteImage,
                                                  (note_x, self.__font_height))

        #settings for placement on screen  -- default items
        self.__offset_x = 80
        self.__offset_y = 50
        self.__menuItem_height = self.__font_height
        self.__menu_Y_bump = 10  #centers the note on menu item

        screen_x, screen_y = self.__screen_size

        #scale image dimensions according to screen size if needed
        if (screen_x != 1280):
            transform = 0
            if (screen_x == 800):
                transform = 0.625
            elif (screen_x == 1024):
                transform = 0.8
            self.__offset_x = self.__offset_x * transform

            #            menu_x, menu_y = self.__menuImage.get_size()
            #            menu_x = int(menu_x * transform)
            #            menu_y = int(menu_y * transform)
            note_x, note_y = self.__noteImage.get_size()
            note_x = int(note_x * transform)
            note_y = int(note_y * transform)
            #            self.__menuImage = pygame.transform.scale( self.__menuImage, (menu_x, menu_y))
            self.__noteImage = pygame.transform.scale(self.__noteImage,
                                                      (note_x, note_y))

        #level list only displays in career mode
        if self.__game.getGameMode() == "career":
            self.__songList_y = self.__offset_y + (self.__font_height * 7)
            self.__noteStart_y = 2 * self.__offset_y + self.__font_height
        else:
            self.__songList_y = self.__offset_y + self.__font_height
            self.__noteStart_y = self.__offset_y + self.__songList_y  #+ 2*self.__font_height

        self.__bkgrd_x = screen_x - self.__bkgrd_rightImage.get_width()
        self.__bkgrd_y = screen_y - self.__bkgrd_rightImage.get_height()
    def __init__(self):
        fileLocs = FileLocations()
        prefix = fileLocs.comboSounds
        zero = GoodStep(0)
        one = GoodStep(1)
        two = GoodStep(2)
        three = GoodStep(3)
        five = GoodStep(5)
        six = GoodStep(6)
        seven = GoodStep(7)
        eight = GoodStep(8)

        comboA = Combo((six, seven, six), "Warm_Er_Up")
        comboB = Combo((six, three, zero), "Jackhammer")
        comboC = Combo((seven, six, three), "Sidewinder")
        comboD = Combo((seven, five, eight), "Off_The_Rocker")
        comboE = Combo((one, six, eight), "Chromosomal")
        comboF = Combo((one, eight, six), "Corkscrew")
        comboG = Combo((three, five, seven), "Whirlwind")
        comboH = Combo((three, zero, three), "Left_Waggle")
        comboI = Combo((five, eight, five), "Right_Waggle")
        comboJ = Combo((five, zero, three), "Sicktackular")
        comboK = Combo((two, seven, six), "Thunderstorm")
        comboL = Combo((two, five, eight), "Triple_Jump")
        comboM = Combo((zero, one, two), "Super_Slide")
        comboN = Combo((zero, two, five), "ZigZag")
        comboO = Combo((eight, seven, six), "Exit_Hatch")
        comboP = Combo((eight, three, one), "Blast_Off")
        comboQ = Combo((six, three, seven, seven), "Power_Surge")
        comboR = Combo((seven, one, three, five), "Inferno")
        comboS = Combo((eight, five, five, eight), "Carolina_Two_Step")
        comboT = Combo((three, six, seven, two), "Torpedo")
        comboU = Combo((five, two, one, five), "Fusion")
        comboV = Combo((zero, zero, three, one), "Somersault")
        comboW = Combo((one, six, seven, eight), "Psycho_T")
        comboX = Combo((two, eight, two, zero), "Ricochet")
        comboY = Combo((six, eight, two, zero, six), "Atomic_Accelerator")
        comboZ = Combo((seven, five, one, three, seven), "Flipside_360")
        comboAA = Combo((eight, five, seven, three, six), "Berserker")
        comboBB = Combo((three, zero, three, one, three), "Canonball")
        comboCC = Combo((five, eight, six, three, two), "Schism_Leap")
        comboDD = Combo((zero, one, zero, one, zero), "Running_Man")
        comboEE = Combo((one, two, zero, one, one), "Suspended_In_Time")
        comboFF = Combo((two, eight, five, three, seven), "Annihilator")


        self.comboDictionary= [comboA,comboB,comboC,comboD,comboE,comboF,comboG,comboH,\
                               comboI, comboJ, comboK, comboL, comboM, comboN, comboO, comboP,\
                               comboQ,comboR,comboS,comboT,comboU,comboV,comboW,comboX,comboY, \
                               comboZ,comboAA,comboBB,comboCC,comboDD,comboEE,comboFF]
        self.MINCOMBO = 3
        self.MAXCOMBO = 5

        self.combosSize3 = self.createCombosOfSize(3)
        self.combosSize4 = self.createCombosOfSize(4)
        self.combosSize5 = self.createCombosOfSize(5)
예제 #10
0
 def __init__ (self, location, time=0):
     """
         Location must be a int, which is converted to a tuple, time is the time since the current song began.  If no song is playing
          (i.e. during menu navigation), default time = 0.
     """
     self.stepLocations = {0:(0, 0), 1:(1, 0), 2:(2, 0), 3:(0, 1), 5:(2, 1), 6:(0, 2), 7:(1, 2), 8:(2, 2)}
     self.stepDictionary = {(0, 0): "back-left",(1, 0):"back",(2, 0):"back-right",(0, 1): "left",\
                         (2, 1):"right",(0, 2):"front-left",(1, 2):"front", (2, 2):"front-right"}
     self.__buildLocation(location)
     self.fileLocs = FileLocations()
     self.time = time
예제 #11
0
 def __saveGameProfile(self):
     """
        Saves this profile to /profiles/gameprofile.p
        Only one profile is saved on a given machine. 
     """
     fileLocs = FileLocations()
     filename = fileLocs.playerProfiles + r"\gameProfile.p"
     try:
         f = open(filename, "w")
         pickle.dump(self, f)
         return True
     except IOError:
         raise GameProfileIOError("Unable to write game profile to file.")
예제 #12
0
 def saveSongScores(self):
     """
        Saves this profile to /profiles/gameprofile.p
        Only one profile is saved on a given machine. 
     """
     fileLocs = FileLocations()
     filename = fileLocs.songs + r"\songScores.p"
     try:
         f = open(filename, "w")
         pickle.dump(self, f)
         print 'High Scores Saved'
         return True
     except IOError:
         raise GameProfileIOError("Unable to write game profile to file.")
예제 #13
0
    def __init__(self, goodSteps, comboName):

        self.comboSteps = []
        self.comboSteps = goodSteps
        self.numberOfSteps = len(self.comboSteps)
        self.name = comboName
        self.fileLocs = FileLocations()
        self.scorer = Score()
        self.difficulty = 0
        self.difficultyBenchmarks = {
            "easy": 40000,
            "medium": 70000,
            "hard": 2000000
        }
 def __saveGameSettings(self):
     """
        Saves this Settings to /Settingss/gameSettings.p
        Only one Settings is saved on a given machine. 
     """
     fileLocs = FileLocations()
     filename = fileLocs.playerProfiles + r"\gameProfile.p"
     print 'this is the filename ', filename
     try:
         f = open(filename, "w")
         pickle.dump(self, f)
         return True
     except IOError:
         raise GameSettingsIOError("Unable to write game Settings to file.")
예제 #15
0
 def __loadAudio(self):
     """
         Loads voice and sound effects files for this menu.
     """
     fileLocs = FileLocations()
     self.__menuSoundsFilename = [
         "\menu_02_01.ogg", "\menu_02_14.ogg", "\menu_02_02.ogg",
         "\menu_02_03.ogg", "\menu_00_01.ogg"
     ]
     self.__menuSound = []
     for filename in self.__menuSoundsFilename:
         self.__menuSound.append(
             pygame.mixer.Sound(fileLocs.menuSounds + filename))
     self.__narrationChannel = pygame.mixer.Channel(0)
예제 #16
0
    def __loadGameProfile(self):
        try:
            #filename handled internally -- derive it from playerName
            fileLocs = FileLocations()
            filename = fileLocs.playerProfiles + r"\gameProfile.p"
            f = open(filename, "r")
            tempIn = pickle.load(f)

            mVol = tempIn.getMusicVolume()
            vVol = tempIn.getVoiceVolume()
            fxVol = tempIn.getFxVolume()
            self.setVolumes(mVol, vVol, fxVol)
            width, height = tempIn.getScreenSize()
            self.setScreenSize(width, height)
            f.close()
            return True
        except IOError:
            return False
예제 #17
0
    def __loadImages(self):
        """
            Loads images for menus, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()
        menuImage_file = fileLocs.images_menus + r"\tutorialmenu.png"
        note_file = fileLocs.images_menus + r"\note.png"
        menu_bkgrd_file = fileLocs.images_menus + r"\menu_right.png"

        self.__menuImage = pygame.image.load(menuImage_file).convert_alpha()
        self.__noteImage = pygame.image.load(note_file).convert_alpha()
        self.__bkgrd_rightImage = pygame.image.load(
            menu_bkgrd_file).convert_alpha()

        #settings for placement on screen  -- default items
        self.__offset_x = 80
        self.__offset_y = 50
        self.__menuItem_height = 125
        self.__menu_Y_bump = 10  #centers the note on menu item

        screen_x, screen_y = self.__screen_size

        #adjust image dimensions according to screen size if needed
        if (screen_x != 1280):
            transform = 0
            if (screen_x == 800):
                transform = 0.625
            elif (screen_x == 1024):
                transform = 0.8
            self.__offset_x = self.__offset_x * transform
            menu_x, menu_y = self.__menuImage.get_size()
            menu_x = int(menu_x * transform)
            menu_y = int(menu_y * transform)
            note_x, note_y = self.__noteImage.get_size()
            note_x = int(note_x * transform)
            note_y = int(note_y * transform)
            self.__menuImage = pygame.transform.scale(self.__menuImage,
                                                      (menu_x, menu_y))
            self.__noteImage = pygame.transform.scale(self.__noteImage,
                                                      (note_x, note_y))
            self.__menuItem_height = int(self.__menuItem_height * transform)

        self.__bkgrd_x = screen_x - self.__bkgrd_rightImage.get_width()
        self.__bkgrd_y = screen_y - self.__bkgrd_rightImage.get_height()
예제 #18
0
    def __loadAudio(self):
        """
            Loads voice and sound effects files for this menu.
        """
        fileLocs = FileLocations()
        themeSongFilename = "\People_Like_Us_and_Ergo_Phizmiz_-_Social_Folk_Dance.ogg"
        self.__welcomeMessage = pygame.mixer.Sound(fileLocs.menuSounds +
                                                   r"\menu_05_01.ogg")

        ##time file for beats
        timefile = fileLocs.beats + r"\People_Like_Us_and_Ergo_Phizmiz_-_Social_Folk_Dance.times"

        self.__times = [float(t.strip()) for t in file(timefile, 'rt')]

        self.__music = pygame.mixer.music
        self.__music.load(fileLocs.songs + themeSongFilename)

        #        self.__buzzer = pygame.mixer.Sound(fileLocs.soundEffects+"\\fx_00_00.ogg")
        self.__narrationChannel = pygame.mixer.Channel(0)
예제 #19
0
 def __playerAlreadyExists(self, playerName):
     """
         Checks profiles.p to see if the name is already on the list.
         Returns true if the name is on the list, otherwise returns false.
     """
     fileLocs = FileLocations()
     filename = fileLocs.playerProfiles+r"\profiles.p"
     playerList = []
     f = None
     try:
         f = open(filename, "r")
         playerList = pickle.load(f)
         f.close()
         try:
             index = playerList.index(playerName)
             return True ## name found as key -- return true
         except ValueError:
             return False #key not found -- return false      
     except IOError:
         return False # no file found -- return false
예제 #20
0
 def loadSongScores(self):
     try:
         #filename handled internally -- derive it from playerName
         fileLocs = FileLocations()
         filename = fileLocs.songs + r"\songScores.p"
         f = open(filename, "r")
         tempIn = pickle.load(f)
         self.top_song_scores = tempIn.getSongScores()
         self.players_top_scores = tempIn.getPlayerSongScores()
         f.close()
         return True
     except IOError:
         self.top_song_scores = {}
         self.players_top_scores = {}
         return False
     except AttributeError:
         self.top_song_scores = {}
         self.players_top_scores = {}
     except EOFError:
         self.top_song_scores = {}
         self.players_top_scores = {}
    def __loadAudio(self):
        """
            Loads voice and sound effects files for this menu.
        """
        fileLocs = FileLocations()
        self.__menuSoundsFilename = [
            "\menu_01_01.ogg", "\menu_01_02.ogg", "\menu_01_03.ogg",
            "\menu_01_04.ogg", "\menu_01_05.ogg", "\menu_01_06.ogg"
        ]
        self.__menuSound = []
        for filename in self.__menuSoundsFilename:
            self.__menuSound.append(
                pygame.mixer.Sound(fileLocs.menuSounds + filename))

        self.__songTitleAudio = {}
        for title, filename in self.__songTitle_filenames.iteritems():
            self.__songTitleAudio[title] = pygame.mixer.Sound(
                fileLocs.menuSounds + filename)

        self.__levelNumber = []
        self.__levelNumberFilename = [
            "\menu_09_04.ogg", "\menu_09_05.ogg", "\menu_09_06.ogg",
            "\menu_09_07.ogg", "\menu_09_08.ogg"
        ]
        for filename in self.__levelNumberFilename:
            self.__levelNumber.append(
                pygame.mixer.Sound(fileLocs.menuSounds + filename))

        #one-off sounds
        self.__diffLevel = pygame.mixer.Sound(fileLocs.menuSounds +
                                              r"\menu_09_09.ogg")
        self.__pickSong = pygame.mixer.Sound(fileLocs.menuSounds +
                                             r"\menu_09_01.ogg")
        self.__pickLevel = pygame.mixer.Sound(fileLocs.menuSounds +
                                              r"\menu_09_02.ogg")
        self.__returnMessage = pygame.mixer.Sound(fileLocs.menuSounds +
                                                  r"\menu_09_03.ogg")
        self.__buzzer = pygame.mixer.Sound(fileLocs.soundEffects +
                                           "\\fx_00_00.ogg")
        self.__narrationChannel = pygame.mixer.Channel(0)
    def __loadImages(self):
        """
            Loads images for arrows, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()
        #load the arrow files
        game_over_file = fileLocs.images + r"\game_over.png"
        self.__game_over = pygame.image.load(game_over_file).convert_alpha()
        font = pygame.font.SysFont("arial", 48)
        self.__high_song_score = font.render("Song High Scores", True,
                                             (0, 0, 0))
        self.__high_player_score = font.render("Player High Scores", True,
                                               (0, 0, 0))

        self.__margin_x = 15
        self.__margin_y = 15
        self.__offset_x = 80
        self.__offset_y = 75
        self.__menuItem_height = 100
        self.__menu_Y_bump = 10
        #must eventually allow for different sized screens
        self.screen_x, self.screen_y = self.__screen_size
예제 #23
0
   On loading an existing account, the user should create a new PlayerProfile object
   and then use addExistingPlayerName to set the name before attempting to load player data.
   
   PlayerProfile also has a method that loads the profiles.p file and returns all player names as a list.
"""

"""
   Started 16 March by Jason Cisarano.  Pickle retrieve not working yet--it seems to save fine, though.
   20 March -- completed save and load functions.  Added checking to avoid players' using existing names.
   Added error handling.
"""

import cPickle as pickle
import os
from FileLocations import FileLocations
fileLocs = FileLocations()

class PlayerIOError(Exception):
    """
       Custom error message for problems with loading and saving files
    """
    def __init__(self, message):
        self.__message = message
    def __str__(self):
        return repr(self.__message)

class PlayerProfile(object):
    fileLocs=FileLocations()
    ALPH_DICT = {
             "A":fileLocs.alphSounds+"\\menu_11_01.ogg", "B":fileLocs.alphSounds+"\\menu_11_02.ogg", "C":fileLocs.alphSounds+"\\menu_11_03.ogg",
             "D":fileLocs.alphSounds+"\\menu_11_04.ogg", "E":fileLocs.alphSounds+"\\menu_11_05.ogg", "F":fileLocs.alphSounds+"\\menu_11_06.ogg",
예제 #24
0
#This class makes aubio compile a song -- it has to be a wav file, however
#something weird happens with mp3s, even if it thinks it will work
#one problem with this script is that it expects the song to be in the folder
#where aubiotrack is, but we can fix all that.
import os
#import tkFileDialog
import shutil
import sys
import re
from FileLocations import FileLocations
import pygame
from SoundEffectController import SoundEffectController

soundController = SoundEffectController()
fileLoc = FileLocations()
currentDir = os.curdir
mysongs = []
oldSongs = []


def getOldSongs(sms, dr, flst):
    for file in flst:
        wholeFile = os.path.splitext(file.__str__())
        if (wholeFile[1] == ".mp3"):
            oldSongs.append(wholeFile[0])


def changeNames(sms, dr, flst):
    if (len(flst) == 0):
        # soundController.queueSound(pygame.mixer.Sound(fileLoc.nameEntry+r"\menu_14_01.ogg"))
        #soundController.playAllSounds()
예제 #25
0
def startGame(screen):
    gameInfo = GameInfo()
    screenInf = ScreenInfo()
    player = gameInfo.getPlayer(0)
    gameStats = player.getGameStats()
    gameStats.newRound()
    difficulty = player.getProfile().getDifficulty()

    if (difficulty == 0):
        FAIR_DIFF = .3

    if (difficulty == 1):
        FAIR_DIFF = .25

    if (difficulty == 2):
        FAIR_DIFF = .2

    HIT_TOL = FAIR_DIFF
    BEAT_TOL = 0.033

    print HIT_TOL

    comboDictionary = ComboDictionary()
    fileLocs = FileLocations()
    scorer = Score()
    screenBorder = ScreenBorder(screen)

    #find one simple song for this
    songfile = fileLocs.songs + "\TeQuieroMas.mp3"
    timefile = fileLocs.beats + "\TeQuieroMas.times"

    #initialize pygame
    pygame.mixer.pre_init(44100, -16, 2, 1024 * 2)
    pygame.init()
    music = pygame.mixer.music
    music.load(songfile)

    #initialize sound controller
    soundController = SoundEffectController()
    clock = pygame.time.Clock()

    #get the times from the times file
    times = [float(t.strip()) for t in file(timefile, 'rt')]

    #FUNCTIONS FOR SINGLEPLAYER

    #get the change in time between the beat times and the current time
    def GetDelta(t):
        n = bisect(times, t)
        d1 = t - times[n - 1]
        try:
            d2 = times[n] - t
        except IndexError:
            return None
        if d1 < d2:
            return -d1
        else:
            return d2

    #figure out if the change in time / tolerance is < .5, it if is, it's a hit
    def HitOnBeat(changeInTime, hitTolerance):
        dt = changeInTime
        ht = hitTolerance

        f = max(-1, min(1, (dt / ht)))
        hit = abs(f) < 0.5
        errors.append(f)
        return hit

    #compare containers of goodsteps and see if they are equal
    def CompareGoodStepContainers(container1, container2):
        isTrue = True
        if len(container1) != len(container2):
            return False
        for i in range(0, len(container1)):
            if container1[i].getLocation() != container2[i].getLocation():
                return False
        return isTrue

    #combo Detection will return combo if yes, none if not
    def CheckForCombo():
        currentStepLength = len(gameStats.getComboSteps())
        comboStepList = gameStats.getComboSteps()
        for item in comboDictionary.getCombosOfSize(3):
            if CompareGoodStepContainers(
                    comboStepList[currentStepLength - 3:currentStepLength],
                    item.getSteps()):
                return item
        for item in comboDictionary.getCombosOfSize(4):
            if CompareGoodStepContainers(
                    comboStepList[currentStepLength - 4:currentStepLength],
                    item.getSteps()):
                return item
        for item in comboDictionary.getCombosOfSize(5):
            if CompareGoodStepContainers(
                    comboStepList[currentStepLength - 5:currentStepLength],
                    item.getSteps()):
                return item
        return None

    #prepare screen flash
    def FlashOrUpdateScreen(gameStats):
        if abs(dt) < BEAT_TOL:
            #screen.fill((0, 0, 0))
            screenBorder.IncrementDanceFloorCounter()
            #pygame.display.flip()

        screenBorder.drawScreen(gameStats.getGoodSteps(), screenInf,
                                gameStats.getPointsPerHit(),
                                gameStats.getCurrentScore(),
                                gameInfo.getGameMode())

    #update score
    def UpdateScore(gameinfo, dt):

        #set points per hit
        gameStats.setPointsPerHit(
            int(
                scorer.scoreHit(gameStats.getGoodSteps(), difficulty, dt,
                                gameStats.getCurrentCombo())))

        currentScore = gameStats.getCurrentScore()

        pointsForCurrentHit = gameStats.getPointsPerHit()
        currentScore += pointsForCurrentHit

        gameStats.setCurrentScore(currentScore)

    def checkPositiveSounds(gameInfo):
        playPointsSound(gameInfo)

    #plays number of points based on how many points there are, every 100,000
    def playPointsSound(gameInfo):
        pass
        """
        totalScore = gameInfo.getCurrentScore()
        pointGoal = gameInfo.getPointGoal()
        if totalScore >= pointGoal:
            soundController.playNumberSound(totalScore)
            print "you've reached " + str(pointGoal) + " points!"
            gameInfo.setPointGoal(pointGoal + 100000)
         """

    #depending on the level, create a list of combos to ask for
#    def createAskComboList(gameInfo):
#        #easy
#        comboListtoAsk = []
#
#        unlockLevel = gameInfo.getCurrentLevel()
#        #unlockLevel = 9
#        print "highest level is " + str(unlockLevel)
#
#        if unlockLevel ==0 or unlockLevel ==1:
#            combos= comboDictionary.getCombosOfSizeAndDifficulty(3, "easy")
#            combos1 = comboDictionary.getCombosOfSizeAndDifficulty(3, "medium")
#            comboListtoAsk = combos + combos1
#
#        elif unlockLevel ==2 or unlockLevel ==3:
#            combos = comboDictionary.getCombosOfSizeAndDifficulty(3, "easy")
#            combos1 = comboDictionary.getCombosOfSizeAndDifficulty(3, "medium")
#            combos2 = comboDictionary.getCombosOfSizeAndDifficulty(3, "hard")
#            comboListtoAsk = combos + combos1 + combos2
#
#        elif unlockLevel ==4 or unlockLevel ==5:
#            combos = comboDictionary.getCombosOfSizeAndDifficulty(3, "easy")
#            combos1 = comboDictionary.getCombosOfSizeAndDifficulty(3, "medium")
#            combos2 = comboDictionary.getCombosOfSizeAndDifficulty(3, "hard")
#            combos3 = comboDictionary.getCombosOfSizeAndDifficulty(4, "easy")
#            comboListtoAsk = combos + combos1 + combos2 + combos3
#
#
#        elif unlockLevel ==6 or unlockLevel ==7:
#            combos = comboDictionary.getCombosOfSizeAndDifficulty(3, "easy")
#            combos1 = comboDictionary.getCombosOfSizeAndDifficulty(3, "medium")
#            combos2 = comboDictionary.getCombosOfSizeAndDifficulty(3, "hard")
#            combos3 = comboDictionary.getCombosOfSizeAndDifficulty(4, "easy")
#            combos4 = comboDictionary.getCombosOfSizeAndDifficulty(4, "medium")
#            combos5 = comboDictionary.getCombosOfSizeAndDifficulty(4, "hard")
#            combos6 = comboDictionary.getCombosOfSizeAndDifficulty(5, "easy")
#            comboListtoAsk = combos + combos1 + combos2 + combos3 + combos4 + combos5 + combos6
#
#        elif unlockLevel ==8 or unlockLevel ==9:
#            combos = comboDictionary.getCombosOfSizeAndDifficulty(3, "easy")
#            combos1 = comboDictionary.getCombosOfSizeAndDifficulty(3, "medium")
#            combos2 = comboDictionary.getCombosOfSizeAndDifficulty(3, "hard")
#            combos3 = comboDictionary.getCombosOfSizeAndDifficulty(4, "easy")
#            combos4 = comboDictionary.getCombosOfSizeAndDifficulty(4, "medium")
#            combos5 = comboDictionary.getCombosOfSizeAndDifficulty(4, "hard")
#            combos6 = comboDictionary.getCombosOfSizeAndDifficulty(5, "easy")
#            combos7 = comboDictionary.getCombosOfSizeAndDifficulty(5, "medium")
#            combos8 = comboDictionary.getCombosOfSizeAndDifficulty(5, "hard")
#            comboListtoAsk = combos + combos1 + combos2 + combos3 + combos4 + combos5 + combos6 + combos7 + combos8
#
#
#
#        gameInfo.setAskedComboList(comboListtoAsk)
#

    def askForCombo(gameInfo):
        #get a combo to be played, randomly from askedComboList

        comboList = gameInfo.getAskedComboList()
        gameInfo.setAskedCombo(comboList[random.randrange(0,
                                                          (len(comboList)))])
        combo = gameInfo.getAskedCombo()

        soundController.queueSoundFile(fileLocs.careerSounds +
                                       "\\tryCombo.ogg")
        playComboSteps(combo)

        print "Let's try doing a combo! " + combo.getName()
        print combo.getStepNameList()

    def askForWarmupCombo():
        soundController.queueSoundFile(fileLocs.careerSounds +
                                       "\\tryCombo.ogg")
        playComboSteps(warmupCombo)

    def playComboSteps(combo):
        steps = combo.getSteps()
        for step in steps:
            soundController.queueSoundFile(step.getSoundFile())

    def checkForAskedCombo(gameInfo):
        if gameInfo.getCurrentCombo() == warmupCombo:
            print "Great Job, you hit the combo!"
            gameInfo.setAskedCombosHit(gameInfo.getAskedCombosHit() + 1)
            gameInfo.setAskedCombo(None)
            global hitWarmup
            return True
        return False

    def comboProcessing():
        gameStats.setCurrentCombo(CheckForCombo())
        if (gameStats.getCurrentCombo() != None):
            soundController.playComboInSong(gameStats.getCurrentCombo())
            gameStats.clearComboSteps()
            return True
        return False

    def stepProcessing(currentStep):
        gameStats.addStep(currentStep)
        gameStats.setBeatsHit(gameStats.getBeatsHit() + 1)
        gameStats.setBeatsAttempted(gameStats.getBeatsAttempted() + 1)
        soundController.playHitSound()

    def missedBeat():
        gameStats.setBeatsAttempted(gameStats.getBeatsAttempted() + 1)
        gameStats.clearGoodSteps()
        gameStats.clearComboSteps()

    def playNextPrompt(state, time):
        """
           Takes needed action for given state, returns next appropriate state
        """

        if state == 0:
            if music.get_pos(
            ) - time > 5000:  # makes sure there's always a bit of a pause -- tweak for each one
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_01.ogg")
                return (1, music.get_pos())  #updated state and time
            return (0, time)  #no change to state or time

        if state == 1:
            if music.get_pos() - time > 9000:
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_03.ogg")
                return (2, music.get_pos())
            return (1, time)

        if state == 2:
            if music.get_pos() - time > 5000:
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_02.ogg")
                return (3, music.get_pos())
            return (2, time)

        if state == 3:
            if music.get_pos() - time > 5000:
                askForWarmupCombo()
                return (4, music.get_pos())
            return (3, time)

        if state == 4:
            if music.get_pos() - time > 15000:
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_07.ogg")
                return (3, music.get_pos())
            return (4, time)

        if state == 5:
            if time != -1:
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_05.ogg")
                soundController.queueSoundFile(fileLocs.menuSounds +
                                               "\menu_07_06.ogg")
            return (5, -1)

    #start the single player mode and initialize
    music.set_volume(.5)
    music.play()
    errors = []
    cntrl = Controller()
    #createAskComboList(gameInfo)

    #tutorial-specific vars
    promptState = 0
    lastPromptTime = 0
    hitWarmup = False
    warmupCombo = Combo((GoodStep(6), GoodStep(7), GoodStep(6)), "Warm_Er_Up")

    #    timeSinceCombo = 0
    #    timeOfCombo = 0
    #    repeatedCombo = False

    run = True
    #start the game loop
    while run:
        #get current time position in song
        t = music.get_pos() * 0.001
        dt = GetDelta(t)
        if t > times[len(times) - 1]:
            music.stop()
            run = False
            break

        if music.get_pos() > 4000:
            if not soundController.isPlaying():
                promptState, lastPromptTime = playNextPrompt(
                    promptState, lastPromptTime)
#                timeOfCombo= t

        soundController.update()
        if hitWarmup:
            #            run = False
            if not soundController.isPlaying() and promptState == 5:
                run = False
            else:
                promptState = 5

        for event in pygame.event.get():
            #check for escape
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    music.stop()
                    run = False

            #see if it's a goodStep
            currentStep = cntrl.checkEvent(event, t)
            if currentStep != None:
                #check to see if you hit the beat
                #if you hit the beat
                if HitOnBeat(dt, HIT_TOL) == True:

                    stepProcessing(currentStep)

                    #check to see if it was a combo
                    hitWarmup = comboProcessing()

                    #update the score
                    UpdateScore(gameInfo, dt)
                    checkPositiveSounds(gameInfo)

                else:
                    #clear the goodSteps and combo list, because you stepped on a wrong beat
                    missedBeat()

        else:
            pygame.time.wait(2)

        clock.tick(30)
        FlashOrUpdateScreen(gameStats)
        # soundController.update()
        gameStats.setCurrentCombo(None)

    music.fadeout(4000)

    print "exiting"
예제 #26
0
    def __loadImages(self):
        """
            Loads images for menus, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()

        #background
        note_file = fileLocs.images_menus + r"\note.png"
        menu_bkgrd_file = fileLocs.images_menus + r"\menu_right.png"
        button_file = fileLocs.images_menus + r"\splash_buttons.png"

        #title dictionary of images
        title_file = "\up_arrow.png"
        self.__titleItems = {}
        for item in self.__letterDictionary:
            self.__titleItems[item] = pygame.image.load(
                fileLocs.images + title_file).convert_alpha()

        self.__noteImage = pygame.image.load(note_file).convert_alpha()
        self.__bkgrd_rightImage = pygame.image.load(
            menu_bkgrd_file).convert_alpha()
        self.__splash_buttonsImage = pygame.image.load(
            button_file).convert_alpha()

        #settings for placement on screen  -- default items
        self.__offset_x = 80
        self.__offset_y = 50
        self.__menuItem_height = 125
        self.__menu_Y_bump = 10  #centers the note on menu item

        screen_x, screen_y = self.__screen_size

        #adjust image dimensions according to screen size if needed
        if (screen_x != 1280):
            transform = 0
            if (screen_x == 800):
                transform = 0.625
            elif (screen_x == 1024):
                transform = 0.8
            self.__offset_x = self.__offset_x * transform

            #scale the note
            note_x, note_y = self.__noteImage.get_size()
            note_x = int(note_x * transform)
            note_y = int(note_y * transform)
            self.__noteImage = pygame.transform.scale(self.__noteImage,
                                                      (note_x, note_y))

            #scale the buttons
            button_x, button_y = self.__splash_buttonsImage.get_size()
            button_x = int(button_x * transform)
            button_y = int(button_y * transform)
            self.__splash_buttonsImage = pygame.transform.scale(
                self.__splash_buttonsImage, (button_x, button_y))

            #scale the title
            for item, image in self.__titleItems.iteritems():
                item_x, item_y = self.__titleItems[item].get_size()
                item_x = int(item_x * transform)
                item_y - int(item_y * transform)
                self.__titleItems[item] = pygame.transform.scale(
                    self.__titleItems[item], (item_x, item_y))

        self.__bkgrd_x = screen_x - self.__bkgrd_rightImage.get_width()
        self.__bkgrd_y = screen_y - self.__bkgrd_rightImage.get_height()
        self.__button_y = int(screen_y / 2)
        self.__button_x = (screen_x -
                           self.__splash_buttonsImage.get_size()[0]) / 2
예제 #27
0
    def __loadImages(self):
        """
            Loads images for arrows, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()
        #load the arrow files
        up_arrow_file = fileLocs.images + r"\up_arrow.png"
        down_arrow_file = fileLocs.images + r"\down_arrow.png"
        right_arrow_file = fileLocs.images + r"\right_arrow.png"
        left_arrow_file = fileLocs.images + r"\left_arrow.png"
        down_right_arrow_file = fileLocs.images + r"\down_right_arrow.png"
        up_right_arrow_file = fileLocs.images + r"\up_right_arrow.png"
        down_left_arrow_file = fileLocs.images + r"\down_left_arrow.png"
        up_left_arrow_file = fileLocs.images + r"\up_left_arrow.png"

        self.__up_arrow = pygame.image.load(up_arrow_file).convert_alpha()
        self.__up_arrow = self.transformImage(self.__up_arrow)
        self.__down_arrow = pygame.image.load(down_arrow_file).convert_alpha()
        self.__down_arrow = self.transformImage(self.__down_arrow)
        self.__left_arrow = pygame.image.load(left_arrow_file).convert_alpha()
        self.__left_arrow = self.transformImage(self.__left_arrow)
        self.__right_arrow = pygame.image.load(
            right_arrow_file).convert_alpha()
        self.__right_arrow = self.transformImage(self.__right_arrow)
        self.__up_right_arrow = pygame.image.load(
            up_right_arrow_file).convert_alpha()
        self.__up_right_arrow = self.transformImage(self.__up_right_arrow)
        self.__up_left_arrow = pygame.image.load(
            up_left_arrow_file).convert_alpha()
        self.__up_left_arrow = self.transformImage(self.__up_left_arrow)
        self.__down_left_arrow = pygame.image.load(
            down_left_arrow_file).convert_alpha()
        self.__down_left_arrow = self.transformImage(self.__down_left_arrow)
        self.__down_right_arrow = pygame.image.load(
            down_right_arrow_file).convert_alpha()
        self.__down_right_arrow = self.transformImage(self.__down_right_arrow)

        #load person pic files
        man1_file = fileLocs.images + r"\chibi-girl.png"
        self.__man1 = pygame.image.load(man1_file).convert_alpha()
        self.__man1 = self.transformImage(self.__man1)
        miss_file = fileLocs.images + r"\miss.png"
        self.__miss = pygame.image.load(miss_file).convert_alpha()
        self.__miss = self.transformImage(self.__miss)
        girl_up_left = fileLocs.images + r"\girl_up_left.png"
        self.__girlUL = pygame.image.load(girl_up_left).convert_alpha()
        self.__girlUL = self.transformImage(self.__girlUL)
        girl_up_right = fileLocs.images + r"\girl_up_right.png"
        self.__girlUR = pygame.image.load(girl_up_right).convert_alpha()
        self.__girlUR = self.transformImage(self.__girlUR)
        self.__girlR = pygame.image.load(fileLocs.images +
                                         r"\girl_right.png").convert_alpha()
        self.__girlR = self.transformImage(self.__girlR)
        self.__girlL = pygame.image.load(fileLocs.images +
                                         r"\girl_left.png").convert_alpha()
        self.__girlL = self.transformImage(self.__girlL)
        self.__girlBL = pygame.image.load(
            fileLocs.images + r"\girl_back_left.png").convert_alpha()
        self.__girlBL = self.transformImage(self.__girlBL)
        self.__girlBR = pygame.image.load(
            fileLocs.images + r"\girl_back_right.png").convert_alpha()
        self.__girlBR = self.transformImage(self.__girlBR)

        #load hit button files
        hit_file = fileLocs.images + r"\hit.png"
        self.__hit = pygame.image.load(hit_file).convert_alpha()
        self.__hit = self.transformImage(self.__hit)

        #load the background
        background_file = fileLocs.images + r"\background.png"
        self.__background = pygame.image.load(background_file).convert_alpha()
        self.__background = self.transformImage(self.__background)

        self.__danceFloor = pygame.image.load(
            fileLocs.images + r"\dance_floor.png").convert_alpha()
        self.__danceFloor = self.transformImage(self.__danceFloor)
        self.__danceFloor1 = pygame.image.load(
            fileLocs.images + r"\dance_floor1.png").convert_alpha()
        self.__danceFloor1 = self.transformImage(self.__danceFloor1)
        self.__danceFloor2 = pygame.image.load(
            fileLocs.images + r"\dance_floor2.png").convert_alpha()
        self.__danceFloor2 = self.transformImage(self.__danceFloor2)
        self.__danceFloor3 = pygame.image.load(
            fileLocs.images + r"\dance_floor3.png").convert_alpha()
        self.__danceFloor3 = self.transformImage(self.__danceFloor3)
        self.__danceFloor4 = pygame.image.load(
            fileLocs.images + r"\dance_floor4.png").convert_alpha()
        self.__danceFloor4 = self.transformImage(self.__danceFloor4)
        self.__danceFloor5 = pygame.image.load(
            fileLocs.images + r"\dance_floor5.png").convert_alpha()
        self.__danceFloor5 = self.transformImage(self.__danceFloor5)
        self.__danceFloor6 = pygame.image.load(
            fileLocs.images + r"\dance_floor6.png").convert_alpha()
        self.__danceFloor6 = self.transformImage(self.__danceFloor6)
        self.__danceFloor7 = pygame.image.load(
            fileLocs.images + r"\dance_floor7.png").convert_alpha()
        self.__danceFloor7 = self.transformImage(self.__danceFloor7)
        self.__danceFloor8 = pygame.image.load(
            fileLocs.images + r"\dance_floor8.png").convert_alpha()
        self.__danceFloor8 = self.transformImage(self.__danceFloor8)
        self.__danceFloor9 = pygame.image.load(
            fileLocs.images + r"\dance_floor9.png").convert_alpha()
        self.__danceFloor9 = self.transformImage(self.__danceFloor9)
        self.__danceFloor10 = pygame.image.load(
            fileLocs.images + r"\dance_floor10.png").convert_alpha()
        self.__danceFloor10 = self.transformImage(self.__danceFloor10)
        self.__danceFloor11 = pygame.image.load(
            fileLocs.images + r"\dance_floor11.png").convert_alpha()
        self.__danceFloor11 = self.transformImage(self.__danceFloor11)

        self.__danceFloorArray = [self.__danceFloor,self.__danceFloor1, self.__danceFloor2, self.__danceFloor3, self.__danceFloor4,\
                                  self.__danceFloor5, self.__danceFloor6, self.__danceFloor7, self.__danceFloor8, self.__danceFloor9, \
                                  self.__danceFloor10, self.__danceFloor11]

        self.__offset_x = 80
        self.__offset_y = 75
        self.__menuItem_height = 100
        self.__menu_Y_bump = 10
        #must eventually allow for different sized screens
        self.screen_x, self.screen_y = self.__screen_size
예제 #28
0
class PlayerProfile(object):
    fileLocs=FileLocations()
    ALPH_DICT = {
             "A":fileLocs.alphSounds+"\\menu_11_01.ogg", "B":fileLocs.alphSounds+"\\menu_11_02.ogg", "C":fileLocs.alphSounds+"\\menu_11_03.ogg",
             "D":fileLocs.alphSounds+"\\menu_11_04.ogg", "E":fileLocs.alphSounds+"\\menu_11_05.ogg", "F":fileLocs.alphSounds+"\\menu_11_06.ogg",
             "G":fileLocs.alphSounds+"\\menu_11_07.ogg", "H":fileLocs.alphSounds+"\\menu_11_08.ogg", "I":fileLocs.alphSounds+"\\menu_11_09.ogg",
             "J":fileLocs.alphSounds+"\\menu_11_10.ogg", "K":fileLocs.alphSounds+"\\menu_11_11.ogg", "L":fileLocs.alphSounds+"\\menu_11_12.ogg",
             "M":fileLocs.alphSounds+"\\menu_11_13.ogg", "N":fileLocs.alphSounds+"\\menu_11_14.ogg", "O":fileLocs.alphSounds+"\\menu_11_15.ogg",
             "P":fileLocs.alphSounds+"\\menu_11_16.ogg", "Q":fileLocs.alphSounds+"\\menu_11_17.ogg", "R":fileLocs.alphSounds+"\\menu_11_18.ogg",
             "S":fileLocs.alphSounds+"\\menu_11_19.ogg", "T":fileLocs.alphSounds+"\\menu_11_20.ogg", "U":fileLocs.alphSounds+"\\menu_11_21.ogg",
             "V":fileLocs.alphSounds+"\\menu_11_22.ogg", "W":fileLocs.alphSounds+"\\menu_11_23.ogg", "X":fileLocs.alphSounds+"\\menu_11_24.ogg",
             "Y":fileLocs.alphSounds+"\\menu_11_25.ogg", "Z":fileLocs.alphSounds+"\\menu_11_16.ogg", "-":fileLocs.alphSounds+"\\menu_11_27.ogg",
             "?":fileLocs.alphSounds+"\\menu_11_27.ogg"
             } 
    """
      PlayerProfile holds the player's statistics and game progress. Includes internal methods to store
      and retrieve player data based on user name.
   
      On creation of an account, the user can simply attempt to addNewPlayerName and
      PlayerProfile will check against the profiles.p file to verify the name doesn't
      exist and then add it if it does not.
   
      On loading an existing account, the user should create a new PlayerProfile object
      and then use addExistingPlayerName to set the name before attempting to load player data.
   
      PlayerProfile also has a method that loads the profiles.p file and returns all player names as a list.
    """
    
    def __init__(self):
          #PlayerProfile attributes
          #if you add an attribute, be sure to add it to the loadPlayerFile() method
        self.__playerName="???"
        self.__difficulty=0
        self.__highScore=0
        self.__bestStepRun=0
        self.__levelReached=1
        self.__songDictionary={}
        self.__filename = ""
        
    def __str__(self):
        return "%s. High score=%s. Best step run=%s. Highest level reached=%s. Difficulty=%s"%(self.__playerName, self.__highScore, self.__bestStepRun, self.__levelReached, self.__difficulty)
    
    def __setPlayerFilename(self):
        """
           Used internally to create a filename for the player based on login name.
        """
        if self.__playerName != "???":
            l=self.__playerName.rsplit(" ")
            nameWithoutSpaces="_".join(l)
            self.__filename = fileLocs.playerProfiles+"\\"+nameWithoutSpaces+r".p"

    def loadPlayerFile (self):
        """
           Pass in the player's already-registered account name, and loadPlayerFile
           will look for a matching player account.
        """
        #print self.__filename
        if self.__filename == "":
            self.__setPlayerFilename()
        #print "filename= " + self.__filename            
        try:
            #filename handled internally -- derive it from playerName
#            print self.__filename
            f = open(self.__filename, "r")
            tempIn = pickle.load(f)
            self.__playerName = tempIn.getPlayerName()
            self.setBestStepRun(tempIn.getBestStepRun())
            self.__songDictionary = tempIn.getAllSongs()
            self.setDifficulty(tempIn.getDifficulty())
            self.setHighScore(tempIn.getHighScore())
            self.setLevelReached(tempIn.getLevelReached())
            f.close()                       
        except IOError:
            raise PlayerIOError("Unable to read player info from file.")
        
    def savePlayerInfo(self):
        """
           Saves player info to file with filename based on player name         
        """
        if self.__filename == "":
            self.__setPlayerFilename()
        try:
            #f = open(self.__filename, "w")
            pickle.dump(self, open(self.__filename, "w"))
            return True
            #f.close()
        except IOError:
            raise PlayerIOError("Unable to write player info to file.")
    
    def setHighScore(self, score):
        """
           Sets current high score to score passed in only if new score is higher.
           Returns true if the change was successful, otherwise returns false
        """
        if (self.__highScore < score):
            self.__highScore = score
            return True
        else:
            return False
        
    def deleteThisPlayerProfile(self):
        """
           This will delete the player from the profiles list and delete
           player's .p file.  The player's name must have already been set.
           Returns true on success.
        """
        #delete player from profiles.p
        filename = fileLocs.playerProfiles+r"\profiles.p"
        playerList = []
        if self.__filename == "":
            self.__setPlayerFilename()
        f = None
        result = False
        try:
            f = open(filename, "r")
            playerList = pickle.load(f)
            f.close()
            try:
                playerList.remove(self.getPlayerName())
                f = open(filename, "w")
                pickle.dump(playerList, f)
                f.close()
                os.remove(self.getPlayerFilename())
                return True ## name found and removed -- return true
            except ValueError:
                return False #unsuccessful delete -- return false 
            except IOError:
                return False
            except WindowsError:
                return False #file not found returned if player profile has never been saved to file     
        except IOError:
            return False # no file found -- return false
        
        
    def setExistingPlayerName(self, playerName):
        """
           Used to both check that a player account has already been created
           and update the current PlayerProfile with that account name. Returns
           true on success, false on failure.
        """
        if self.__playerAlreadyExists(playerName):
            self.__playerName = playerName
            return True
        else:
            return False
    
    
    def setNewPlayerName(self, playerName):
        """
           Sets player name to passed-in name only if no name has already been set.
           If the passed-in playerName is already in use, the name will not be
           added to the list a second time.  The method returns true if the
           name is added, otherwise it will return false.
        """
        if(self.__playerName=="???" and not(self.__playerAlreadyExists(playerName)) ):
              #verify that there isn't already a player by this name
            fileLocs=FileLocations()
            filename = fileLocs.playerProfiles+r"\profiles.p"
            playerList = []
            index = -1
            f = None
            try:
                  #load list of players -- if there's no file, then we skip this step 
                f = open(filename, "r")
                playerList = pickle.load(f)
                f.close()                
            except IOError:    
                pass
            finally:
                  #add name to list
                self.__playerName=playerName
                playerList.append(playerName)
                try:
                    f = open(filename,"w")
                    pickle.dump(playerList, f)
                    f.close()
                    self.savePlayerInfo()
                except IOError:
                    raise PlayerIOError("Unable to add player name to profile.p")
                return True
        else:
            return False ##unsuccessful -- return false

                
    def __playerAlreadyExists(self, playerName):
        """
            Checks profiles.p to see if the name is already on the list.
            Returns true if the name is on the list, otherwise returns false.
        """
        fileLocs = FileLocations()
        filename = fileLocs.playerProfiles+r"\profiles.p"
        playerList = []
        f = None
        try:
            f = open(filename, "r")
            playerList = pickle.load(f)
            f.close()
            try:
                index = playerList.index(playerName)
                return True ## name found as key -- return true
            except ValueError:
                return False #key not found -- return false      
        except IOError:
            return False # no file found -- return false

    def setDifficulty(self, difficulty):
        """
           Sets current difficulty using numeric values 0-2
           Returns true if the change was successful, otherwise
           returns false
        """
        if(0<= difficulty and difficulty <=2):
            self.__difficulty=difficulty
            return True
        else:
            return False
        
    def setBestStepRun(self, stepRun):
        """
           Sets player's best step run to passed in value only
           if new value is higher.  Returns true if the change 
           was successful, otherwise returns false
        """
        if(self.__bestStepRun < stepRun):
            self.__bestStepRun = stepRun
            return True
        else:
            return False
    
    def setLevelReached(self, level):
        """
           Sets player's highest level to passed-in value only if 
           new value is higher and if the new value is in the range
           1-5.  Returns true if the change was successful,
           otherwise returns false.
        """
        
        if(0 < level and level < 6 and self.__levelReached < level):
            self.__levelReached = level
            self.savePlayerInfo()
            return True
        else:
            return False
        print"level reached: "  + self.__levelReached
        
        
        
    def addSong(self, title, filename):
        """
           Adds passed-in song to player's song dictionary.  Song title and filename
           should both be Strings.  Returns true if add was successful--otherwise, it
           returns false.  The filename should actually be the complete path to the song
           on the user's system.
        """
        #make sure that the filename is valid? or does this happen outside?
        self.__songDictionary[title]=filename
        return True
        
    def getHighScore(self):
        return self.__highScore
    
    def getPlayerName(self):
        return self.__playerName
    
    def getDifficulty(self):
        return self.__difficulty
    
    def getBestStepRun(self):
        return self.__bestStepRun
    
    def getLevelReached(self):
        return self.__levelReached
    
    def getSongFilename(self, title):
        """
           Returns the filename of the song title given.  
           Will return empty string if title isn't in list or if it is misspelled.
        """
        try:
            f = self.__songDictionary[title]
        except KeyError:
            f = ""
        return f
    
    def getAllSongs(self):
        """
           Returns all songs in the player's playlist.
        """
        return self.__songDictionary
    
    def getPlayerFilename(self):
        """
           Returns the filename where player data is stored.  If no player is set,
           returns empty string.
        """
        if (self.__playerName != "???"):
            return self.__filename
        else:
            return ""
        
    def dispose(self):
        """
           Sets all values to default.
        """
        self.__playerName="???"
        self.__difficulty=0
        self.__highScore=0
        self.__bestStepRun=0
        self.__levelReached=1
        self.__songDictionary={}  
        self.__filename = ""  
def startGame(screen,screenInf,currentGame):
    """
        Starts the game. This method grabs control of the game, detects beats, scores the beats and returns 
        the score of the game when the song is finished
    """
    HIT_TOL = 0.300
    BEAT_TOL = 0.033
    
    gameInfo = currentGame
    gameInfo.newRound()
    
    difficulty = gameInfo.getDifficulty()
    if (difficulty ==0):
        FAIR_DIFF = .3
    
    if (difficulty ==1):
        FAIR_DIFF = .25
    
    if (difficulty ==2):
        FAIR_DIFF = .2
            
            
    HIT_TOL = FAIR_DIFF
    BEAT_TOL = 0.033
    
    comboDictionary = ComboDictionary()
    fileLocs=FileLocations()
    scorer=Score()
    screenBorder=ScreenBorder(screen)
   
    #songfile = fileLocs.songs+r"\CodeMonkey.mp3"
    #timefile = fileLocs.beats+r"\CodeMonkey.times"
    songfile = fileLocs.songs+ gameInfo.getCurrentSong()[1] +".ogg"
    timefile = fileLocs.beats+ gameInfo.getCurrentSong()[1] +".times"
    
    
    #initialize pygame
    pygame.mixer.pre_init(44100, -16, 2, 1024*2)
    pygame.init()
    music = pygame.mixer.music
    music.load(songfile)
    
    music.set_volume(gameInfo.getMusicVolume()/100.0)
    

    
    #initialize sound controller

    soundController = SoundEffectController(gameInfo.getVoiceVolume()/ 100.0)
    
    
    #get the times from the times file
    times = [ float(t.strip()) for t in file(timefile, 'rt') ]
    
    
    #FUNCTIONS FOR SINGLEPLAYER
    
    #get the change in time between the beat times and the current time
    def GetDelta(t):
        n = bisect(times, t)
        d1 = t - times[n-1]
        try:
            d2 = times[n] - t
        except IndexError:
            return (0,False)
        if d1 < d2:
            return (-d1,True)
        else:
            return (d2, True)
        
        
    
    #figure out if the change in time / tolerance is < .5, it if is, it's a hit
    def HitOnBeat(changeInTime, hitTolerance):
        dt = changeInTime
        ht = hitTolerance
        
        f = max(-1, min(1, (dt / ht)))
        hit = abs(f) < 0.5
        errors.append(f)
        return hit
    
    #compare containers of goodsteps and see if they are equal
    def CompareGoodStepContainers(container1, container2):
        isTrue = True
        if len(container1) != len(container2):
            return False
        for i in range(0, len(container1)):
            if container1[i].getLocation() != container2[i].getLocation():
                return False
        return isTrue
            
        
    
    #combo Detection will return combo if yes, none if not
    def CheckForCombo():
        currentStepLength = len(gameInfo.getComboSteps())
        comboStepList = gameInfo.getComboSteps()
        for item in comboDictionary.getCombosOfSize(3):
            if CompareGoodStepContainers(comboStepList[currentStepLength - 3:currentStepLength],item.getSteps()):  
                return item
        for item in comboDictionary.getCombosOfSize(4):
            if CompareGoodStepContainers(comboStepList[currentStepLength - 4:currentStepLength],item.getSteps()):   
                return item
        for item in comboDictionary.getCombosOfSize(5):    
            if CompareGoodStepContainers(comboStepList[currentStepLength - 5:currentStepLength],item.getSteps()):
                return item
        return None      
        
    
    #prepare screen flash        
    def FlashOrUpdateScreen(gameInfo):
        if abs(dt) < BEAT_TOL:
            #screen.fill((0, 0, 0))
            screenBorder.IncrementDanceFloorCounter()
            #pygame.display.flip()
       
        screenBorder.drawScreen(gameInfo.getGoodSteps(),screenInf,gameInfo.getPointsPerHit(),gameInfo.getCurrentScore(),gameInfo.getGameMode())
    
    
    #update score   
    def UpdateScore(gameinfo, dt):
        
        
        #set points per hit
        gameinfo.setPointsPerHit(int(scorer.scoreHit(gameInfo.getGoodSteps(),gameInfo.getDifficulty(), dt, gameInfo.getCurrentCombo())))
    
        currentScore = gameinfo.getCurrentScore()
        
        pointsForCurrentHit = gameinfo.getPointsPerHit()
        currentScore += pointsForCurrentHit
        
        gameinfo.setCurrentScore(currentScore)
    
        
    def checkPositiveSounds(gameInfo):
        playPointsSound(gameInfo)
        

    #plays number of points based on how many points there are, every 100,000
    def playPointsSound(gameInfo):
        totalScore = gameInfo.getCurrentScore()
        pointGoal = gameInfo.getPointGoal()
        if totalScore >= pointGoal:
            soundController.playNumberSound(totalScore)
            print "you've reached " + str(pointGoal) + " points!"
            gameInfo.setPointGoal(pointGoal + 100000)
        
            
            
    def comboProcessing():
        gameInfo.setCurrentCombo(CheckForCombo())
        if (gameInfo.getCurrentCombo() != None):
            soundController.playComboInSong(gameInfo.getCurrentCombo())
            gameInfo.clearComboSteps()
            
    def stepProcessing(currentStep):
        gameInfo.addStep(currentStep)
        gameInfo.setBeatsHit(gameInfo.getBeatsHit() + 1)
        gameInfo.setBeatsAttempted(gameInfo.getBeatsAttempted() + 1)
        soundController.playHitSound()     
            
    def missedBeat():
        soundController.playMissSound()
        gameInfo.setBeatsAttempted(gameInfo.getBeatsAttempted() + 1)
        gameInfo.clearGoodSteps()
        gameInfo.clearComboSteps()
    
    #start the single player mode and initialize
    
    music.play()
    errors = []
    cntrl=Controller()
    cntrl2 = Controller(2)
    
    run = True
    #start the game loop
    while run:
        #get current time position in song
        t = music.get_pos() * 0.001
        dt,run = GetDelta(t)
        
        for event in pygame.event.get():
            #check for escape
            if event.type == pygame.KEYDOWN:
                
                if event.key == pygame.K_ESCAPE:
                    music.stop()
                    run = False
                    
                    
            #you could do for each controller, check if current step is a goodstep, then do the stuff
            #see if it's a goodStep
            currentStep = cntrl.checkEvent(event,t)
            currentStepPlayer2 = cntrl2.checkEvent(event,t)
            if currentStep != None: 
            #check to see if you hit the beat
                #if you hit the beat
                if HitOnBeat(dt, HIT_TOL) == True:
                    stepProcessing(currentStep)
                    comboProcessing()
                              
                    #update the score
                    UpdateScore(gameInfo, dt)
                    checkPositiveSounds(gameInfo)
                    print "player 1 hit"
                    
                else:
                    #clear the goodSteps and combo list, because you stepped on a wrong beat
                    missedBeat()
                    print dt
            elif currentStepPlayer2 != None: 
            #check to see if player 2 hit the beat
            #if you hit the beat
                if HitOnBeat(dt, HIT_TOL) == True:
                    stepProcessing(currentStepPlayer2)
                    comboProcessing()
                              
                    #update the score
                    UpdateScore(gameInfo, dt)
                    checkPositiveSounds(gameInfo)
                    print "player 2 hit"
                else:
                    #clear the goodSteps and combo list, because you stepped on a wrong beat
                    missedBeat()
                    print dt    
            
                    
                
        else:
            pygame.time.wait(2)
        
        FlashOrUpdateScreen(gameInfo)
        soundController.update()
        gameInfo.setCurrentCombo(None)
        
        
    print "exiting"
    return gameInfo
예제 #30
0
    def __loadImages(self):
        """
            Loads images for menus, resizes them for current screen dimensions.
        """
        fileLocs = FileLocations()
        menuImage_file = fileLocs.images_menus + r"\setupmenu.png"
        note_file = fileLocs.images_menus + r"\note.png"
        menu_bkgrd_file = fileLocs.images_menus + r"\menu_right.png"

        self.__menuImage = pygame.image.load(menuImage_file).convert_alpha()
        self.__noteImage = pygame.image.load(note_file).convert_alpha()
        self.__bkgrd_rightImage = pygame.image.load(
            menu_bkgrd_file).convert_alpha()

        #screensize inserts
        self.__screensizeImage = []
        for filename in self.__screensizeImage_file:
            self.__screensizeImage.append(
                pygame.image.load(fileLocs.images_menus +
                                  filename).convert_alpha())

        #settings for placement on screen  -- default items
        self.__offset_x = 80
        self.__offset_y = 50
        self.__menuItem_height = 125
        self.__menu_Y_bump = 10  #centers the note on menu item

        self.__vol_num_x = 960

        screen_width, screen_height = self.__screen_size
        #adjust dimensions according to screen size if needed
        if (screen_width != 1280):
            transform = 0
            if (screen_width == 800):
                transform = 0.625
            elif (screen_width == 1024):
                transform = 0.8
            self.__offset_x = self.__offset_x * transform

            menu_x, menu_y = self.__menuImage.get_size()
            menu_x = int(menu_x * transform)
            menu_y = int(menu_y * transform)
            note_x, note_y = self.__noteImage.get_size()
            note_x = int(note_x * transform)
            note_y = int(note_y * transform)

            for image in self.__screensizeImage:
                x, y = image.get_size()
                x = int(x * transform)
                y = int(y * transform)
                self.__screensizeImage[self.__screensizeImage.index(
                    image)] = pygame.transform.scale(image, (x, y))

            self.__menuImage = pygame.transform.scale(self.__menuImage,
                                                      (menu_x, menu_y))
            self.__noteImage = pygame.transform.scale(self.__noteImage,
                                                      (note_x, note_y))
            self.__menuItem_height = int(self.__menuItem_height * transform)
            self.__vol_num_x = self.__vol_num_x * transform

        #determine placement for the screensize inset
        self.__placeScreensizeImg()
        self.__bkgrd_x = screen_width - self.__bkgrd_rightImage.get_width()
        self.__bkgrd_y = screen_height - self.__bkgrd_rightImage.get_height()