def _handleEvent(self, event):
     if (event.type == pygame.QUIT):
         if reactor.running:
             reactor.stop()
         return True
     if (event.type == Input.FPS):
         self._fpsDisplayer.toggle()
         self._limitFPS = not self._limitFPS
         return True
     if (event.type == Input.TOGGLE_SOUND):
         Sound.toggleQuiet()
         return True
     if (event.type == Input.TOGGLE_FULLSCREEN):
         if platform.system() != "Linux":
             return True
         self._fullscreen = not self._fullscreen
         if self._fullscreen:
             self._size = self._fullscreenSize
         else:
             self._size = self._defaultSize
         self._resize()
         return True
     if (event.type == pygame.VIDEORESIZE):
         self._size = event.size
         self._defaultSize = event.size
         self._resize()
         return True
     return False
 def accept_specialMenu(self):
     ability = self.gui._specialMenu.getSelection()
     if not ability:
         Sound.cursorInvalid()
         return
     Sound.cursorClick()
     self.trans("abilityTarget", ability)
Exemple #3
0
    def explode(self, map):  # Make dirt
        size = self.explosionSizeFactor * self.size

        if int(self.x + size) > map.width:
            right = map.width
        else:
            right = int(self.x + size)

        if int(self.x - size) < 0:
            left = 0
        else:
            left = int(self.x - size)

        for x in range(left, right):
            if (x - self.x) / (size + 0.01) >= -1:
                for y in range(
                    int((-math.sin(math.acos((x - self.x) / (size + 0.01))) * size) + self.y),
                    int((math.sin(math.acos((x - self.x) / (size + 0.01))) * size) + self.y),
                ):
                    if y < map.height and y > 0:
                        if map.mask[x][y] == map.maskimage.map_rgb((0, 0, 0, 255)):
                            rand = random.randint(-20, 20)

                            map.mask[x][y] = (150, 90, 20, 255)
                            map.visual.set_at((x, y), (145 + rand, 95 + rand, 20 + rand, 255))
                            map.screenImage.set_at((x, y), (145 + rand, 95 + rand, 20 + rand, 255))

        Sound.playSound(self.game, 5)

        self.destroy(map)
 def checkFacingResult(self, result):
     if result:
         Sound.cursorClick()
         self.gui.clearTopText()
         self.trans("disabled")
     else:
         Sound.cursorInvalid()
Exemple #5
0
 def init_smart_sound(self):
     if Config.mode == 'music':
         Sound.set_mute(self.out.pid, False)
         self.is_muted = False
     else:
         if Config.smart_sound_timeout_sec > 0:
             Sound.set_mute(self.out.pid, True)
             self.is_muted = True
Exemple #6
0
 def activate(self):
     self.state = 0
     Sound.playSound("click")
     if self.function:
         if self.argument:
             self.function(self.argument)
         else:
             self.function()
Exemple #7
0
    def setDead(self, d):
        self.dead = d
        self.particleEmitters["explode"].active = d
        if d:
            Sound.playSound("explode")

        if not d:
            self.setModel(Files.ModelGroups["ship"].getRandomModel())
Exemple #8
0
 def hit(self, other):
     if str(type(other)).__contains__("Invader"):
         Sound.hit()
         lives = RunningValues.lives_variable.get()
         lives = lives - 1
         RunningValues.lives_variable.set(lives)
         Explosion.create_explosion(self.canvas, self.x + self.width / 2,
                                    self.y - self.height / 2)
         RunningValues.player_dead()
Exemple #9
0
    def __init__(self):
        self.window = Tk()
        self.window.title("Dori")
        self.window.geometry("800x600")
        self.window.configure(bg="green")

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

        self.sound = Sound()

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

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

        self.SetupGUI()
        self.Initialize()

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

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

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

        self.window.mainloop()
Exemple #10
0
def loop(beat):
  k = 0
  a = Beat(beat)
  for i in range(32):
    n = a.pattern.pop(0)
    print(n)
    Sound.play(n)
    a.pattern.append(n)
    for j in range(1000000):
      k += 10
Exemple #11
0
def get_newgame():
    scene = Scene()
    bg_layer = Level2_Background()
    hero = Level2_Hero()

    scroller_2.add(bg_layer)
    scroller_2.add(hero)
    Sound.play("res/audio/Level2.mp3")
    scene.add(scroller_2)
    return scene
Exemple #12
0
    def manage_silence(self):
        if Config.mode == 'music':
            if Sound.get_silence_duration_sec() == 0:
                self.is_sound_started = True

            if self.is_sound_started is True and Sound.get_silence_duration_sec(
            ) > 5.0:
                self.out.kill()

                self.is_sound_started = False
Exemple #13
0
    def __init__(self, songName):
        self.noteList = []
        try:
            file = open('Songs/' + songName, "r")
            print("File found!")
            firstline = file.readline().replace(
                '\n', '')  #Remove the carriage returns
            self.name = firstline.split('\"')[
                1]  #Takes the name given within the quotes
            self.tempo = int(firstline.split(',')[1]
                             [7:])  #Takes the number after the "tempo="
            timSigStr = firstline.split(',')[2][
                6:]  #Takes the string after the tempo, EX: "4/4"
            self.timSigUp = int(
                timSigStr[0:timSigStr.find('/')]
            )  #Takes the value before the / stores as an int
            self.timSigDown = int(
                timSigStr[timSigStr.find('/') +
                          1:])  #Same as above, but after the /

            #Done with the basics, now for the notes
            songStr = file.read().replace('\n', '').replace(
                ' ', ''
            )  #Read the rest of the file, take out all carriage returns and spaces
            measureList = songStr.split('(')  #Splits the string by measure
            measureList.remove(
                measureList[0])  #Removes the empty string at index 0
            for measure in measureList:  #For every measure...
                measure = measure.replace(')', '').replace(
                    ']', '')  #Removes the ending syntax as they are repetative
                beatList = measure.split(
                    '[')  #Split based on each beat of a measure
                beatList.remove(beatList[0])  #remove the empty string
                for beat in beatList:
                    if (beat.find(',') == -1):  #This means it's only one note
                        if (beat == ""):
                            self.noteList.append(Sound.Note("REST"))
                        else:
                            self.noteList.append(Sound.Note(beat))
                            print('Success')
                    else:  #Chord
                        beat = beat.split(',')
                        for a in beat:  #checks for collisions, multiple notes on one string
                            for b in beat:
                                if a == b:
                                    pass
                                elif a[-1] == b[-1]:
                                    raise NewExceptions.wrongFormatException(
                                        "Multiple notes on one string")
                        self.noteList.append(Sound.Chord(beat))

        except Exception as e:
            print(e)  #Tell the user what errors you're getting
            del self
            raise e  #Tell the function that an error occured
Exemple #14
0
 def showActionPerformed(self, abilityID):
     action = engine.Ability.Ability.get[abilityID]
     unit = self.unit
     self.setTopText(action.name())
     Sound.action(action.sound(unit.attack()))
     # FIXME: don't compare against the string name! Will break
     # when "Attack" is translated
     if action.name() == "Attack":
         ud = self.unitDisplayer(unit)
         attDisp = Sprite.AttackDisplayer(unit, 0.0)
         ud.addAnimation(attDisp)
Exemple #15
0
 def accept_battleMenu(self):
     choice = self.gui._battleMenu.getSelection()
     Sound.cursorClick()
     if choice == Sprite.BattleMenu.MOVE:
         self.trans('moveTarget')
     elif choice == Sprite.BattleMenu.ATTACK:
         self.trans('abilityTarget', self.gui.unit.attack())
     elif choice == Sprite.BattleMenu.SPECIAL:
         self.trans('specialMenu')
     elif choice == Sprite.BattleMenu.DONE:
         self.trans('facing')
 def accept_battleMenu(self):
     choice = self.gui._battleMenu.getSelection()
     Sound.cursorClick()
     if choice == Sprite.BattleMenu.MOVE:
         self.trans("moveTarget")
     elif choice == Sprite.BattleMenu.ATTACK:
         self.trans("abilityTarget", self.gui.unit.attack())
     elif choice == Sprite.BattleMenu.SPECIAL:
         self.trans("specialMenu")
     elif choice == Sprite.BattleMenu.DONE:
         self.trans("facing")
 def showActionPerformed(self, abilityID):
     action = engine.Ability.Ability.get[abilityID]
     unit = self.unit
     self.setTopText(action.name())
     Sound.action(action.sound(unit.attack()))
     # FIXME: don't compare against the string name! Will break
     # when "Attack" is translated
     if action.name() == "Attack":
         ud = self.unitDisplayer(unit)
         attDisp = Sprite.AttackDisplayer(unit, 0.0)
         ud.addAnimation(attDisp)
Exemple #18
0
 def showRule(self):
     isRuleA = Utilities.pickByWeight([1-self.ruleAProb,self.ruleAProb])                
     if self.isSoundRule:
         freq = self.ruleAFreq if isRuleA else self.ruleBFreq
         Sound.playFreq(freq,self.tRule)
         logging.info("Sending Sound {} for Rule {}".format(freq,'A' if isRuleA else 'B'))
     else:
         nextImg = Utilities.choice(self.ruleAImgNames if isRuleA else self.ruleBImgNames)
         nextImgFull = os.path.join(self.imageFolder,nextImg)
         self.visual.show(nextImgFull,self.fov,[0.5,0.5],self.tRule)
         logging.info("Sending Visual {} for Rule {}".format(nextImg,'A' if isRuleA else 'B'))
     return isRuleA
Exemple #19
0
 def manage_smart_sound(self):
     if Config.smart_sound_timeout_sec > 0:
         if self.sound_index == self.index:
             if self.is_muted is True:
                 Sound.set_mute(self.out.pid, False)
                 self.desktop.set_title(self.out.pid, "* " + self.title)
                 self.is_muted = False
         else:
             if self.is_muted is False:
                 Sound.set_mute(self.out.pid, True)
                 self.desktop.set_title(self.out.pid, self.title)
                 self.is_muted = True
Exemple #20
0
 def showStim(self):
     isStimA = Utilities.pickByWeight([1-self.stimAProb,self.stimAProb])                
     if self.isSoundStim:
         freq = self.stimAFreq if isStimA else self.stimBFreq
         Sound.playFreq(freq,self.tStimulus)
         logging.info("Sending Sound {} for Stimulus {}".format(freq,'A' if isStimA else 'B'))
     else:
         nextImg = Utilities.choice(self.stimAImgNames if isStimA else self.stimBImgNames)
         nextImgFull = os.path.join(self.imageFolder,nextImg)
         self.visual.show(nextImgFull,self.fov,[0.5,0.5],self.tStimulus)
         logging.info("Sending Visual {} for Stimulus {}".format(nextImg,'A' if isStimA else 'B'))
     return isStimA
Exemple #21
0
def get_menu():

    menu = MainMenu()
    main_bg = MainScene()
    scene = Scene()
    Sound.music.set_volume(0.5)
    Sound.play("res/audio/Menu.mp3")

    scene.add(main_bg)
    scene.add(menu)

    return scene
Exemple #22
0
	def check(self, map):
		if self.activationTime > 0:
			self.activationTime -= 1
		else:
			if self.fuel < 1:
				self.thrust = False
				if random.uniform(0,1) < 0.1:
					self.game.objects.append(Smoke(self.game, self.owner, self.x, self.y))
			else:
				target = self.getClosestShip(300)
				if target != None:
					if self.target == None:
						self.target = target
						Sound.playSound(self.game.engine, 6, False)
					elif target == self.target:
						predictedTargetX = target.x - 5*self.dx
						predictedTargetY = target.y - 5*self.dy
						predictedSelfX = self.x + 5*self.dx
						predictedSelfY = self.y + 5*self.dy + 5

						if predictedTargetX > predictedSelfX and predictedTargetY > predictedSelfY:
							targetAngle = math.atan((predictedSelfY-predictedTargetY)/(self.x+2*self.dx-predictedTargetX))
						elif predictedTargetX < predictedSelfX and predictedTargetY > predictedSelfY:
							targetAngle = math.atan((predictedSelfY-predictedTargetY)/(self.x+2*self.dx-predictedTargetX)) + math.pi
						elif predictedTargetX < predictedSelfX and predictedTargetY < predictedSelfY:
							targetAngle = Functions.returnAngle(math.atan((predictedSelfY-predictedTargetY)/(self.x+2*self.dx-predictedTargetX))) + math.pi
						elif predictedTargetX > predictedSelfX and predictedTargetY < predictedSelfY:
							targetAngle = Functions.returnAngle(math.atan((predictedSelfY-predictedTargetY)/(self.x+2*self.dx-predictedTargetX)) + math.pi) + math.pi
						else:
							targetAngle = math.pi/2

						if predictedTargetY > predictedSelfY:
							if Functions.returnAngle(self.angle) < Functions.returnAngle(targetAngle) or Functions.returnAngle(self.angle) > Functions.returnAngle(targetAngle + math.pi):
								self.angle += 0.1275
							else:
								self.angle -= 0.1275
						elif predictedTargetY < predictedSelfY:
							if Functions.returnAngle(self.angle) < Functions.returnAngle(targetAngle + math.pi) or Functions.returnAngle(self.angle) > Functions.returnAngle(targetAngle):
								self.angle -= 0.1275
							else:
								self.angle += 0.1275

						if math.fabs(Functions.returnAngle(self.angle) - targetAngle) < math.pi/8:
							self.fuel -= 1
							self.thrust = True
							if random.uniform(0,1) < 0.3:
								self.game.objects.append(ThrustFlame(self.game, self.owner, self.x-2*self.dx-5*math.cos(self.angle), self.y-2*self.dy-5*math.sin(self.angle), self.dx-1*math.cos(self.angle), self.dy-1*math.sin(self.angle)))

				else:
					self.thrust = False
					self.activationTime = 10
					self.target = None
Exemple #23
0
 def load_sounds(self):
     self.menu_click = Sound()
     self.menu_click.load("click.ogg", False)
     self.menu_click.loop(False)
     self.main_menu_music = Sound()
     self.main_menu_music.load("mainMenuMusic.ogg", True)
     self.main_menu_music.loop(True)
     self.fs_wood = [Sound() for x in range(10)]
     r = 0
     while r < 10:
         self.fs_wood[r].load("fs_wood_" + str(r + 1) + ".ogg", False)
         self.fs_wood[r].loop(False)
         r += 1
    def __init__(self, **kwargs):
        super(TicTacToe, self).__init__(**kwargs)

        self.x_pic_location = "pics/x_gold.png"
        self.o_pic_location = "pics/o_gold.png"
        self.button_start = "pics/blue_But_square.png"
        self.reset_exit = "pics/blue_gloss.png"

        self.Xturn = True
        self.buttons_pressed = 0
        self.game_done = False

        self.button_layout = GridLayout(cols=3, rows=3)
        self.display = BoxLayout(orientation="vertical")

        self.message = Label(text="Player 1's turn")

        exit_button = Button(text="Exit")
        exit_button.background_normal = self.reset_exit
        exit_button.bind(on_press=self.Exit)

        reset_button = Button(text="Reset")
        reset_button.background_normal = self.reset_exit
        reset_button.bind(on_press=self.Reset)

        self.display.add_widget(self.message)
        self.display.add_widget(exit_button)
        self.display.add_widget(reset_button)

        self.add_widget(self.display)

        for x in xrange(9):

            b = CustomTTTButton(border=[0, 0, 0, 0],
                                background_normal=self.button_start)
            b.bind(on_press=self.PlayerPokesButton)
            self.button_layout.add_widget(b)

        #self.button_layout.background_color = [1,0,0,1]

        self.add_widget(self.button_layout)

        x_sound = s.Mp3File("sms-alert-2-daniel_simon.mp3", 3)
        o_sound = s.Mp3File("sms-alert-5-daniel_simon.mp3", 3)
        draw_sound = s.Mp3File("Sad_Trombone-Joe_Lamb-665429450.mp3", 3)
        victory_sound = s.Mp3File("glass_ping-Go445-1207030150.mp3", 3)

        self.x_id = PiMusic.CreateEntry(x_sound)
        self.o_id = PiMusic.CreateEntry(o_sound)
        self.draw_id = PiMusic.CreateEntry(draw_sound)
        self.victory_id = PiMusic.CreateEntry(victory_sound)
    def unclick(self):
        if self.state == MapEditorCursor.DISABLED:
            return
        elif self.state == MapEditorCursor.FREE:
            Sound.cursorCancel()
#            if self.selectedSquare != None:
#                pass#for now
        elif self.state == MapEditorCursor.SELECTED:
            Sound.cursorCancel()
            self.state = MapEditorCursor.FREE
            self._selectedUnit = None
            GUI.get().topMenu().setSelectedOption(0)
            GUI.get().topMenu().setEnabled(False)
            GUI.get().topMenu().setShowing(False)
        elif (self.state == MapEditorCursor.IN_DIALOG):
            Sound.cursorCancel()
            GUI.get().topMenu().setEnabled(True)
            GUI.get().clearTopText() # from special menu
            GUI.get().clearHighlights()
        elif (self.state == MapEditorCursor.SETTING_TAG):
            Sound.cursorCancel()
            self.state = MapEditorCursor.SELECTED
            GUI.get().topMenu().setEnabled(True)
            GUI.get().tagMenu().setEnabled(False)
            GUI.get().tagMenu().setShowing(False)
            GUI.get().clearTopText() # from special menu
            GUI.get().clearHighlights()
        else:
            print 'Error: unhandled unclick() call in MapEditorCursor'
Exemple #26
0
    def updateC(self):
        if (self.state == 2):
            return

        if Controller.menuSelector % self.menuCount == self.id:
            if self.state != 1:
                Sound.playSound("change")
            self.state = 1
        else:
            self.state = 0

        if self.state == 1 and Controller.menuActivate:
            Controller.menuActivate = False
            self.activate()
Exemple #27
0
    def destroy(self,game,i):
        Sound.playSound("explode")
        self.particleEmitters["explode"].active=True
        self.alive=False
        game.addMsg("Alien presence vanished")
        if(game.ship.dead):
            game.addMsg("from the Grave +100")
            game.score+=100

        game.gameObjects.append(Model.LootBox.LootBox(
            random.choice([-1,1])*random.random()*10+self.position.x,
            random.choice([-1, 1]) * random.random() * 10 + self.position.y, game
            , random.choice(["score1"]*10+["invin"]+["score2"]*4+["score3"])
        ))
Exemple #28
0
    def unclick(self):
        if self.state == MapEditorCursor.DISABLED:
            return
        elif self.state == MapEditorCursor.FREE:
            Sound.cursorCancel()
#            if self.selectedSquare != None:
#                pass#for now
        elif self.state == MapEditorCursor.SELECTED:
            Sound.cursorCancel()
            self.state = MapEditorCursor.FREE
            self._selectedUnit = None
            GUI.get().topMenu().setSelectedOption(0)
            GUI.get().topMenu().setEnabled(False)
            GUI.get().topMenu().setShowing(False)
        elif (self.state == MapEditorCursor.IN_DIALOG):
            Sound.cursorCancel()
            GUI.get().topMenu().setEnabled(True)
            GUI.get().clearTopText()  # from special menu
            GUI.get().clearHighlights()
        elif (self.state == MapEditorCursor.SETTING_TAG):
            Sound.cursorCancel()
            self.state = MapEditorCursor.SELECTED
            GUI.get().topMenu().setEnabled(True)
            GUI.get().tagMenu().setEnabled(False)
            GUI.get().tagMenu().setShowing(False)
            GUI.get().clearTopText()  # from special menu
            GUI.get().clearHighlights()
        else:
            print 'Error: unhandled unclick() call in MapEditorCursor'
Exemple #29
0
    def hit(self, other):
        if isinstance(other, PlayerMissile):
            Sound.invader()
            Invader.alive_invader_count = Invader.alive_invader_count - 1
            RunningValues.delete_list.append(self)
            if self in RunningValues.render_list:
                RunningValues.render_list.remove(self)
            self.canvas.delete(self.img1)
            self.canvas.delete(self.img2)
            score = RunningValues.score_variable.get()
            score = score + 1
            RunningValues.score_variable.set(score)

            Explosion.create_explosion(self.canvas, self.x + self.width / 2,
                                       self.y - self.height / 2)
Exemple #30
0
def get_gameover(flag):

    global game_over_flag
    game_over_flag = flag

    scene = Scene()
    main_bg = MainScene()
    over = GameOver()

    Sound.play("res/audio/GameOver.mp3")

    scene.add(main_bg)
    scene.add(over)

    return scene
Exemple #31
0
	def setInstance(self, GPIO):
		print("set Instance")
		if self.useSensor[0] :
			self.sensorTimerControl.append(DHT11.Control(self.all_pin[0], GPIO, self.topic, [0, 1]))
			self.sensorTimerControlIndex.append(0)
			self.sensorTimerControlIndex.append(1)
		if self.useSensor[1] :
			self.sensorDetectControl.append(Fire.Control(self.all_pin[1], GPIO, self.topic, 0))
			self.sensorDetectControlIndex.append(0)
		if self.useSensor[2] :
			self.sensorDetectControl.append(Shock.Control(self.all_pin[4], GPIO, self.topic, 1))
			self.sensorDetectControlIndex.append(1)
		if self.useSensor[3] :
			self.sensorDetectControl.append(IR.Control(self.all_pin[5], GPIO, self.topic, 2))
			self.sensorDetectControlIndex.append(2)
		if self.useSensor[4] :
			self.sensorDetectControl.append(Gas.Control(self.adc_pin[0], self.topic, 3))
			self.sensorDetectControlIndex.append(3)
		if self.useSensor[5] :
			self.sensorTimerControl.append(Cds.Control(self.all_pin[7], GPIO, self.topic, 2))
			self.sensorTimerControlIndex.append(2)
		if self.useSensor[6] :
			self.button_instance = Button.Control(self.all_pin[6], GPIO, self.topic)
		if self.useSensor[7] :
			self.led_instance = LED.LED(self.all_pin[2], self.all_pin[3], GPIO)
			self.led_instance.write(1)
		if self.useSensor[8] :
			self.sensorMoveControl.append(SG90.SG90(self.all_pin[8], self.all_pin[9], GPIO))
		if self.useSensor[9] :
			self.sensorTimerControl.append(PM2008M.Control(self.topic,[3, 4]))
			self.sensorTimerControlIndex.append(3)
			self.sensorTimerControlIndex.append(4)
		if self.useSensor[10] :		
			self.sensorTimerControl.append(Sound.Control(self.adc_pin[1], GPIO, self.topic, 5))
			self.sensorTimerControlIndex.append(5)
 def __init__(self, **kwargbs):
     self.handle = Sound.sound()
     self.filename = kwargbs.get("filename")
     self.x = kwargbs.get("x", 0)
     self.y = kwargbs.get("y", 0)
     self.z = kwargbs.get("z", 0)
     self.looping = kwargbs.get("looping", 0)
     self.pan_step = kwargbs.get("pan_step", 0)
     self.volume_step = kwargbs.get("volume_step", 0)
     self.behind_pitch_decrease = kwargbs.get("behind_pitch_decrease", 0)
     self.start_pan = kwargbs.get("start_pan", 0)
     self.start_volume = kwargbs.get("start_volume", 0)
     self.start_pitch = kwargbs.get("start_pitch", 0)
     self.start_offset = kwargbs.get("start_offset", 0)
     self.upper_range = kwargbs.get("upper_range", 0)
     self.lower_range = kwargbs.get("lower_range", 0)
     self.left_range = kwargbs.get("left_range", 0)
     self.right_range = kwargbs.get("right_range", 0)
     self.backward_range = kwargbs.get("backward_range", 0)
     self.forward_range = kwargbs.get("forward_range", 0)
     self.looping = kwargbs.get("looping", False)
     self.is_3d = kwargbs.get("is_3d", False)
     self.stationary = kwargbs.get("stationary", False)
     self.persistent = kwargbs.get("persistent", False)
     self.paused = kwargbs.get("paused", False)
Exemple #33
0
    def __init__(self):
        logging.basicConfig(format="%(levelname)s (%(asctime)s): %(message)s",
                            datefmt="%I:%M:%S %p",
                            level=logging.WARNING,
                            filename="/var/tmp/BB8.log")
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        #atexit.register(self.Exit)

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

        atexit.register(self.Exit)

        self.Network = Network()
        self.Eye = Eye()
        self.ProcessStateIndicator = ProcessStateIndicator(self)
        self.FrontTopLogicDisplay = FrontTopLogicDisplay(self.strip)
        self.FrontBottomLogicDisplay = FrontBottomLogicDisplay(self.strip)
        self.SideLogicDisplay = SideLogicDisplay(self.strip)
        self.HoloProjector = HoloProjector(self, self.strip)
        self.StatusDisplay = StatusDisplay(self)
        self.Sound = Sound()
Exemple #34
0
    def __init__(self):
        super(MainMenu, self).__init__("Don't Crash")
        self.select_sound = Sound.load('move.mp3')

        # add the items
        items = [
            (MenuItem('Play Game', self.on_play_game)),
            (MenuItem('Setting', self.on_setting)),
            (MenuItem('Quit', self.on_quit)),
        ]

        # set title params
        self.font_title['font_size'] = 78
        self.font_title['color'] = (250, 0, 0, 255)
        self.font_title['bold'] = True
        self.font_title['italic'] = True
        self.font_item['color'] = (255, 255, 255, 144)

        item_margin = 60
        cx = Display.cx
        cy = Display.cy
        self.create_menu(items,
                         selected_effect=rotate_effect(),
                         unselected_effect=rotate_effect_back(),
                         layout_strategy=fixedPositionMenuLayout([
                             (cx, cy + item_margin),
                             (cx, cy),
                             (cx, cy - item_margin),
                         ]))
Exemple #35
0
    def __init__(self):
        super(MainMenu, self).__init__("Don't Crash")
        self.select_sound = Sound.load('move.mp3')

        # add the items
        items = [
            (MenuItem('Play Game', self.on_play_game)),
            (MenuItem('Setting', self.on_setting)),
            (MenuItem('Quit', self.on_quit)),
        ]

        # set title params
        self.font_title['font_size'] = 78
        self.font_title['color'] = (250, 0, 0, 255)
        self.font_title['bold'] = True
        self.font_title['italic'] = True
        self.font_item['color'] = (255, 255, 255, 144)

        item_margin = 60
        cx = Display.cx
        cy = Display.cy
        self.create_menu(items,
                         selected_effect=rotate_effect(),
                         unselected_effect=rotate_effect_back(),
                         layout_strategy=fixedPositionMenuLayout([
                             (cx, cy + item_margin),
                             (cx, cy),
                             (cx, cy - item_margin),
                         ]))
Exemple #36
0
    def __init__(self, frame):
        # Cette variable représente les différents états dans lequel le jeu peut se trouver.
        self.etat = 0
        # Cette variable représente la partie au cas ou on en aurait besoin.
        self.partie = None
        # Cette variable représente le joueur au cas ou on en aurait besoin.
        self.profilHandler = Profil.Handler.Handler(self)
        self.profilHandler.load("profilsData.data")

        # Ces variables permettent d'activer et désactiver le son/musique
        self.sound_active = True
        self.music_active = True
        self.soundSystem = Sound.SoundManager(self)
        self.fin = False
        self.fond = pygame.image.load(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "../assets", "background_menu.jpg")).convert()
        frame.blit(self.fond, (0, 0))
        self.particules = ParticleSystem.ParticleSystem()
        self.classements = [
            Classements.Classement(["Profil", "Temps", "Erreurs"],
                                   [0.5, 0.75]), None,
            Classements.Classement(["Profil", "Gagné/Perdu", "Taux réussite"],
                                   [0.3, 0.7]),
            Classements.Classement(["Profil", "Gagné/Perdu", "précision"],
                                   [0.35, 0.75])
        ]
        self.classements[0].load("Classements_Sudoku.yolo")
        self.classements[2].load("Classements_Loto.yolo")
        self.classements[3].load("Classements_Bataille_Navale.yolo")
Exemple #37
0
    def start(self):
        # Let's hope this works...
        Sound.play_async(Sound.start_music)

        self.board.prepare()
        # Setup the board by putting the bats and ball in the right place
        self.board.updateBats(self.player_one.position,
                              self.player_two.position, self.player_one.is_big,
                              self.player_two.is_big)
        self.board.updateBall(self.ball.position[0], self.ball.position[1])
        self.board.updateScore(0, False)
        self.board.updateScore(0, True)

        # Run the game loop until the game is over
        while not self.gameOver:
            self.game_loop()
    def __init__(self,scale):
        super().__init__("Main")
        self.useRenderer=False
        self.renderer = gui.ScreenRenderer(self.Width , self.Height)

        menu = gui.ButtonMenu(15,5,25,7,1,{
            "Play":"Game",
            "Options":"Option",
            #"Modeling": "model",
            "High Scores":"HiScore",
            "Credits":"Credits",
            "Quit":"QUIT"
        },function=self.changeScreen,scale=scale)

        self.guiObjects.append(menu)

        Sound.playMusic("m_menu")
Exemple #39
0
def makeEmptySoundBySeconds(seconds, samplingRate=Sound.SAMPLE_RATE):
    if seconds <= 0 or samplingRate <= 0:
        print "makeEmptySoundBySeconds(numSamples[, samplingRate]): numSamples and samplingRate must each be greater than 0"
        raise ValueError
    if seconds > 600:
        print "makeEmptySoundBySeconds(numSamples[, samplingRate]): Created sound must be less than 600 seconds"
        raise ValueError
    return Sound(seconds * samplingRate, samplingRate)
Exemple #40
0
    def updateC(self):

        if Controller.menuSelector % self.menuCount == self.id:
            if self.state != 1:
                Sound.playSound("change")
            self.state = 1
        else:
            self.state = 0

        if self.state == 0:
            self.string.color = WHITE
        else:
            self.string.color = BLACK

        if self.state == 1 and Controller.menuActivate:
            Controller.menuActivate = False
            self.activate()
Exemple #41
0
	def activate(self, ship): # Use the weapon
		if (not(self.loading) or self.continuousLoad) and self.loaded >= self.activationCost and self.shotDelayStatus == 0:
			if self.probability == 1 or random.uniform(0,1) < self.probability:
				self.loaded -= self.activationCost
				self.shotDelayStatus = self.shotDelay + random.randint(-self.shotDelayVariation,self.shotDelayVariation)

				self.fire(ship)

				Sound.playSound(self.game, self.sound, self.soundSingle)

				ship.dx -= self.recoil*math.cos(ship.angle)
				ship.dy -= self.recoil*math.sin(ship.angle)

		if not((not(self.loading) or self.continuousLoad) and self.loaded >= self.activationCost):
			self.loading = True
			if not(self.continuousLoad) and self.loaded >= 100:
				self.loading = False
Exemple #42
0
	def explode(self,map): # Explode
		size = self.explosionSizeFactor*self.size

		if size > 10:
			Sound.playSound(self.game.engine, 0, False)

		if int(self.x+size) > map.width:
			right = map.width
		else:
			right = int(self.x+size)

		if int(self.x-size) < 0:
			left = 0
		else:
			left = int(self.x-size)

		for x in range(left, right):
			if (x-self.x)/(size+0.01) >= -1:
				for y in range(int((-math.sin(math.acos((x-self.x)/(size+0.01)))*size)+self.y), int((math.sin(math.acos((x-self.x)/(size+0.01)))*size)+self.y)):
					if y < map.height and y >= 0:
						maskValue = map.mask[x][y]
						if maskValue != map.maskimage.map_rgb((127, 127, 127, 255)) and maskValue != map.maskimage.map_rgb((255, 0, 0, 255)) and maskValue != map.maskimage.map_rgb((0, 0, 0, 255)) and maskValue != map.maskimage.map_rgb((0, 0, 255, 255)):
							map.mask[x][y] = (0, 0, 0)
							map.visual.set_at((x,y),map.background[x][y])
							map.screenImage.set_at((x,y), map.background[x][y])

		for object in self.game.objects:
			distance = (object.x-self.x)**2+(object.y-self.y)**2
			if object != self and object.explosionCollision and distance < size**2:
				object.hp -= math.sqrt((1.5*size)**2-distance)
				if object.isShip:
					object.lastHitter = self.owner

				object.dx += 0.01*(size**2-distance)*(object.x-self.x)/math.sqrt((object.x-self.x+0.01)**2+(object.y-self.y)**2)
				object.dy += 0.01*(size**2-distance)*(object.y-self.y)/math.sqrt((object.x-self.x+0.01)**2+(object.y-self.y)**2)

		for i in range(self.explosionParticleFactor*int(self.size)):
			angle = random.uniform(0,2*math.pi)
			speed = random.uniform(0.1,3.5)
			dx = speed*math.cos(angle)
			dy = speed*math.sin(angle)

			self.game.objects.append(Shard(self.game, self.owner, self.x+5*dx,self.y+5*dy, dx+self.dx/2, dy+self.dy/2))

		self.destroy(map)
Exemple #43
0
 def __init__(
     self,
     start_x,
     start_y,
     cell_height,
     cell_width,
     num_cells_wide,
     num_cells_tall,
     color,
     use_fullscreen,
     fullscreen_width,
     fullscreen_height,
 ):
     self.cells = {}
     self.start_x = start_x
     self.start_y = start_y
     self.cell_height = cell_height
     self.cell_width = cell_width
     self.num_cells_wide = num_cells_wide
     self.num_cells_tall = num_cells_tall
     self.num_lines_cleared = 0
     self.color = color
     self.height = cell_height * num_cells_tall
     self.width = cell_width * num_cells_wide
     self.grid_top_x = 0
     self.grid_top_y = 0
     if use_fullscreen:
         self.grid_top_x = (fullscreen_width / 2) - (self.width / 2)
         self.grid_top_y = (fullscreen_height / 2) - (self.height / 2)
     self.sound = Sound()
     self.color_accum = {}
     # Build Grid
     for x in range(self.num_cells_wide):
         for y in range(self.num_cells_tall):
             self.cells[(x, y)] = (
                 color,
                 Rect(
                     (
                         x * self.cell_width + self.start_x + self.grid_top_x,
                         y * self.cell_height + self.start_y + self.grid_top_y,
                     ),
                     (self.cell_height, self.cell_width),
                 ),
                 0,
             )
 def __init__(self, start_x, start_y, cell_height, cell_width, num_cells_wide, num_cells_tall, color):
     self.cells = {}
     self.start_x = start_x
     self.start_y = start_y
     self.cell_height = cell_height
     self.cell_width = cell_width
     self.num_cells_wide = num_cells_wide
     self.num_cells_tall = num_cells_tall
     self.numLinesCleared = 0
     self.color = color
     self.height = cell_height * num_cells_tall
     self.width = cell_width * num_cells_wide
     self.sound = Sound()
     # Build Grid
     for x in range(self.num_cells_wide):
         for y in range(self.num_cells_tall):
             self.cells[(x, y)] = (
                 color,
                 Rect(
                     (x * self.cell_width + self.start_x, y * self.cell_height + self.start_y),
                     (self.cell_height, self.cell_width),
                 ),
                 0,
             )
 def moveDown(self):
     if self.canMove() and self.y < self.map.height - 1:
         self.y += 1
         Sound.cursorMove()
         GUI.get().scrollTo((self.x, self.y))
 def click(self):
     if self.state == MapEditorCursor.DISABLED:
         return
     elif self.state == MapEditorCursor.FREE:
         Sound.cursorClick()
         GUI.get().topMenu().setShowing(True)
         return 'topMenu'
     elif self.state == MapEditorCursor.SELECTED:
         Sound.cursorClick()
         choice = GUI.get().topMenu().getSelection()
         if choice == Sprite.TopMenu.SET_TAG:
             self.state = MapEditorCursor.SETTING_TAG
             GUI.get().tagMenu().setShowing(True)
         elif choice == Sprite.TopMenu.NEW_TAG:
             self.state = MapEditorCursor.CREATING_TAG
             GUI.get().topMenu().setEnabled(False)
             #GUI.get().addTagDialog().setEnabled(True)
             #GUI.get().addTagDialog().setShowing(True)
             GUI.get().addTagDialog().execute()
             GUI.get().topMenu().setShowing(False)
             self.state = MapEditorCursor.FREE
         #elif choice == Sprite.TopMenu.EDIT_TAG:
         #    self.state = MapEditorCursor.EDITING_TAG
         #    GUI.get().topMenu().setEnabled(False)
         #    GUI.get().editTagDialog().setEnabled(True)
         #    GUI.get().editTagDialog().setShowing(True)
         #elif choice == Sprite.TopMenu.SAVE:
         #    self.state = MapEditorCursor.SETTING_TAG
         #    GUI.get().topMenu().setEnabled(False)
         #    GUI.get().saveMapDialog().setEnabled(True)
         #    GUI.get().saveMapDialog().setShowing(True)
         else:
             print "ERROR: menu option %s not implemented yet" % choice
     elif self.state == MapEditorCursor.SETTING_TAG:
         tagNum = GUI.get().tagMenu().getSelection()
         tags = GUI.get().m.tags
         tagName = tags.keys()[tagNum]
         self.mapSquare().setTag(tags[tagName])
         GUI.get().updateMap()
         GUI.get().topMenu().setEnabled(False)
         GUI.get().topMenu().setShowing(False)
         GUI.get().tagMenu().setEnabled(False)
         GUI.get().tagMenu().setShowing(False)
         self.state = MapEditorCursor.FREE
         #GUI.get().clearTopText() # from special menu
         #GUI.get().clearHighlights()
     #    if ability == None:
     #        Sound.cursorInvalid()
     #        return
     #    self.selectedAbility = ability
     #    Sound.cursorClick()
     #    self.state = MapEditorCursor.CHOOSING_ABILITY_TARGET
     #    GUI.get().showAbilityRange(self.activeUnit,
     #                                       self.selectedAbility)
     #    GUI.get().battleMenu().setEnabled(False)             
     #    GUI.get().specialMenu().setEnabled(False)             
     #elif self.state == MapEditorCursor.CHOOSING_ABILITY_TARGET:
     #    Sound.cursorClick()
     #    a = self.selectedAbility
     #    if (self.x, self.y) not in a.range(self.map,
     #                                       self.activeUnit):
     #        Sound.cursorInvalid()
     #        return
     #    if not a.hasEffect(self.map, self.activeUnit, self.posn3d()):
     #        Sound.cursorInvalid()
     #        return
     #    self.state = MapEditorCursor.UNIT_SELECTED
     #    Battle.get().unitActed(a, self.posn3d())
     #    GUI.get().topMenu().setSelectedOption(0)
     #    GUI.get().topMenu().setEnabled(True)
     #    GUI.get().specialMenu().setEnabled(False)
     #    GUI.get().specialMenu().setShowing(False)
     #    GUI.get().clearHighlights()
     #    self.x = self.activeUnit.x()
     #    self.y = self.activeUnit.y()
     #elif self.state == MapEditorCursor.CHOOSING_MOVE_TARGET:
     #    if self.map.squares[self.x][self.y].unit != None:
     #        Sound.cursorInvalid()                
     #        return
     #    u = self._selectedUnit
     #    reachable = self.map.reachable(u)
     #    if (self.x, self.y) not in reachable:
     #        Sound.cursorInvalid()                
     #        return
     #    Sound.cursorClick()
     #    ScenarioGUI.get().moveUnit(u, (self.x, self.y))
     #    self.state = MapEditorCursor.UNIT_MOVING
     #elif self.state == MapEditorCursor.UNIT_MOVING:
     #    return
     else:
         print 'Error: unhandled click() call in MapEditorCursor'
 def cancel_abilityTarget(self):
     Sound.cursorCancel()
     self.trans("battleMenu")
 def cancel_moveTarget(self):
     Sound.cursorCancel()
     self.trans("battleMenu")
Exemple #49
0
from random import randint
import uuid
import xml.etree.ElementTree as ET
#importing our modules
from commonFunctions import *
from projectile import *
from troop import *
import collision
from pandaImports import *
from pandac.PandaModules import CollisionSphere
from math import *
import physics
from Sound import *

#Getting the shoot sound effect
towerAttackSound = Sound("../sounds/towerAttack.wav")
towerAttackSound.setVolume(0.5)

towerPositioningSound = Sound("../sounds/towerPositioning.wav")
towerPositioningSound.setVolume(0.5)


towerModelDict = {}
#Getting configuration
typ = None
cfTree = ET.parse("tower.xml")
cfRoot = cfTree.getroot()
for element in cfRoot.findall('tower'):
	
	towerType = element.get('type')
	modelTag = element.find('model')
Exemple #50
0
class Tetris():

    NORMAL_MODE = 0
    BOOZE_MODE = 1
    DESIGNATED_DRIVER_MODE = 2
    SINGLE_DRINK_MODE = 3

    def __init__(self):
        self._event_handlers = []
        self._setup_states()
        self._state["game_over"] = True
        self._setup_display()
        self._joystick = None
        if pygame.joystick.get_count() > 0:
            print "FOUND A JOYSTICK!"
            self._joystick = pygame.joystick.Joystick(0)
            self._joystick.init()
            
    def _setup_states(self, mode = 0):
        self._params = {
            "fullscreen"             : False,
            "fullscreen_width"       : 1024,
            "fullscreen_height"      : 768,
            "num_cells_wide"         : 10,
            "num_cells_high"         : 20,
            "cell_width"             : 25,
            "cell_height"            : 25,
            "drink_pouring_time"     : 10.0,
            "starting_cell_x"        : 4,
            "starting_cell_y"        : 1,
            "grid_top_x"             : 0,
            "grid_top_y"             : 0,
            "modes"                  : ["(N)ormal Mode", "(B)ooze Mode", "(S)ingle Drink Mode", "(D)esignated Driver Mode", "(Q)uit"]
            }

        self._level_params = {
            "moving_rate"            : [0.00005,.00004,0.00003,0.00002,0.00001],
            "rotating_rate"          : [0.00009,0.00008,0.00007,0.00006,0.00005],
            "falling_rate"           : [0.00050,0.00035,0.00020,0.00010,0.00005]
            }

        self._state = {
            "last_falling_time"      : 0,
            "falling_rate"           : self._level_params["falling_rate"][0],
            "last_moving_time"       : 0,
            "last_rotating_time"     : 0,
            "level_up_line_count"    : 5,
            "last_num_lines_cleared" : 0,
            "top_y"                  : 0,
            "times_found"            : 0,
            "current_level"          : 1,
            "game_over"              : False,
            "all_finished"           : False,
            "current_y"              : 0,
            "holding_down"           : False
            }


        if mode in [self.NORMAL_MODE, self.SINGLE_DRINK_MODE]:
            self._color_dict     = {1: COLORS["blue"], 6 : COLORS["brown"], 10: COLORS["darkGrey"]}        
        elif mode == self.BOOZE_MODE:
            self._color_dict     = {3 : COLORS["brown"], 10: COLORS["darkGrey"]}
        elif mode == self.DESIGNATED_DRIVER_MODE:
            self._color_dict     = {10: COLORS["blue"]}

        if mode == self.SINGLE_DRINK_MODE or mode == self.BOOZE_MODE:
            self._level_params = {
                "moving_rate"            : [0.00005],
                "rotating_rate"          : [0.00009],
                "falling_rate"           : [0.00040]
                }
            self._params["drink_pouring_time"] = 20.0

        self._color_range    = 10

        self._textBuff       = 2
        self._grid           = Grid( 1, 1, self._params["cell_width"], self._params["cell_height"], self._params["num_cells_wide"], self._params["num_cells_high"], COLORS["black"], self._params["fullscreen"], self._params["fullscreen_width"], self._params["fullscreen_height"])
        if self._params["fullscreen"]:
            self._params["grid_top_x"] = (self._params["fullscreen_width"] / 2) - (self._grid.width / 2)
            self._params["grid_top_y"] = (self._params["fullscreen_height"] / 2) - (self._grid.height / 2)

        self._tetrominoList  = ['T','I','O','S','Z','L','J']
        self._sound          = Sound()

        self._new_tetromino()

    def _setup_display(self):
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.init()
        if self._params["fullscreen"]:
            self._screen = pygame.display.set_mode((1024, 768), pygame.FULLSCREEN, 24)
        else:
            self._screen = pygame.display.set_mode((self._grid.width+self._textBuff,self._grid.height+self._textBuff),0,32)
        if pygame.font:
            self._font = pygame.font.Font(None, 18)

    def init_game(self):
        pygame.display.set_caption("Python Tetris")

    def run_game(self):
        time.sleep(0.01)
        if self._state["game_over"]:
            self._menu_state()
        else:
            self._game_loop()
        self._render()
        return

    def _menu_state(self):
        current_key = ''
        for event in pygame.event.get():
            if event.type == QUIT:
                raise QuitException()
            if event.type == pygame.KEYDOWN:
                current_key = event.key
        if current_key == K_q:
            raise QuitException()
        elif current_key == K_n:
            self._setup_states(self.NORMAL_MODE)
        elif current_key == K_b:
            self._setup_states(self.BOOZE_MODE)
        elif current_key == K_d:
            self._setup_states(self.DESIGNATED_DRIVER_MODE)
        elif current_key == K_s:
            self._setup_states(self.SINGLE_DRINK_MODE)

    def _game_loop(self):

        # Grab vars
        if self._tetromino.active:
            self._move_tetromino()
        else: #New Tetromino
            osc.sendMsg("/tetris/piece_down", [0], "localhost", 9001)
            self._new_tetromino()
        #Levels and Speedup
        if self._grid.num_lines_cleared >= (self._state["level_up_line_count"] * self._state["current_level"]) and self._state["last_num_lines_cleared"] != self._grid.num_lines_cleared:
            self._level_up()

    def _move_tetromino(self):

        current_key = ''
        up_key = ''
        for event in pygame.event.get():
            legal_moves   = {
                "down"  : self._tetromino.max_y < self._grid.height,
                "left"  : self._tetromino.min_x > 0 and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],-1,0),
                "right" : self._tetromino.max_x < self._grid.width and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],1,0),
                }



            if event.type == QUIT:
                break

            if event.type == pygame.JOYAXISMOTION:
                a = event.axis
                p = event.value
                #turn joystick into key simulations
                if a == 0:
                    if p < -0.01:
                        current_key = K_LEFT
                    elif p > 0.01:
                        current_key = K_RIGHT
                else:
                    if p > 0.01:
                        current_key = K_DOWN
                    elif p < 0.01 and p > -0.01:
                        up_key = K_DOWN
            if event.type == pygame.JOYBUTTONDOWN:
                if event.button == 1:
                    current_key = K_z
                else:
                    current_key = K_x
            if event.type == pygame.KEYDOWN:
                current_key = event.key
            elif event.type == pygame.KEYUP:
                up_key = event.key

            if current_key == K_RIGHT and legal_moves["right"]:
                self._tetromino.move(self._grid,1,0)
            if current_key == K_LEFT and legal_moves["left"]:
                self._tetromino.move(self._grid,-1,0)
            if current_key == K_DOWN:
                self._state["holding_down"] = True
                osc.sendMsg("/mario/speed", [40], "localhost", 9001)
            elif up_key == K_DOWN:
                osc.sendMsg("/mario/speed", [0], "localhost", 9001)
                self._state["holding_down"] = False
            #TODO: Fix rotation states
            if current_key == K_z and False not in legal_moves.values():
                self._tetromino.rotate(self._grid, -1)
            if current_key == K_x and False not in legal_moves.values():
                self._tetromino.rotate(self._grid, 1)
            #ADDED: quit current_key
            if current_key == K_q:
                raise QuitException()

        legal_moves   = {
            "down"  : self._tetromino.max_y < self._grid.height,
            "left"  : self._tetromino.min_x > 0 and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],-1,0),
            "right" : self._tetromino.max_x < self._grid.width and self._grid.accept(self._tetromino.id,self._tetromino.positions[self._tetromino.currentPosition],1,0),
            }

        current_time  = time.time()/1000.0
        falling_time  = current_time - self._state["last_falling_time"]

        #Downward fall
        if self._state["holding_down"] is True and legal_moves["down"]:
            self._tetromino.move(self._grid,0,1)
            self._state["current_y"] += 1
        elif falling_time >= self._state["falling_rate"] and legal_moves["down"]:
            self._state["last_falling_time"] = current_time
            self._tetromino.move(self._grid,0,1)
            self._state["current_y"] += 1
        elif not legal_moves["down"] and falling_time >= self._state["falling_rate"]:
            self._tetromino.cluck.play()
            self._tetromino.active = False

    def _new_tetromino(self):
        #ADDED: Set tetromino color to one of our three allowed colors
        color_index = random.randint(0,self._color_range)
        color = ()
        for color_probability in sorted(self._color_dict.keys()):
            if color_index <= color_probability:
                color = self._color_dict[color_probability]
                break

        rand          = random.randint(0,len(self._tetrominoList)-1)
        self._tetromino = Tetromino(self._params["starting_cell_x"], self._params["starting_cell_y"], COLORS["black"],color,self._tetrominoList[rand])
        self._state["holding_down"] = False
        if self._grid.checkForLines():
            for e in self._event_handlers:
                e.on_line_created(self)

        #Test for GAME OVER
        top_y = self._grid.topY()
        if top_y <= 2:
            self._state["times_found"] += 1
        if self._state["times_found"] > 3:
            self._state["game_over"] = True

    def _level_up(self):
        self._state["last_num_lines_cleared"] = self._grid.num_lines_cleared
        self._state["current_level"] += 1
        if self._state["current_level"] < len(self._level_params["falling_rate"]):
            self._state["falling_rate"] = self._level_params["falling_rate"][self._state["current_level"]]
        else:
            self._state["all_finished"] = True
            self._state["game_over"] = True
        self._sound.play("../sound/levelup.wav")
        for e in self._event_handlers:
            e.on_level_up(self)

    def _render(self):
        #render Background
        pygame.draw.rect(self._screen,(255,255,255),Rect(self._params["grid_top_x"], self._params["grid_top_y"],self._grid.width+2,self._grid.height+2))
        #Render Grid
        self._grid.render(self._screen)
        self._render_status()
        pygame.display.update()

    def _render_status(self):
        if not self._state["game_over"]:
            lineText       = "Lines: " + str(self._grid.num_lines_cleared) + "  Level: " + str(self._state["current_level"])
            lines_text     = self._font.render(lineText, 1, COLORS["white"])
            lines_text_pos = Rect((self._params["grid_top_x"]+1, self._params["grid_top_y"]+1),(self._params["grid_top_x"] + 300, self._params["grid_top_y"] + 20))
            self._screen.blit(lines_text, lines_text_pos)
        else:
            game_over_text     = self._font.render("GAME OVER... LEVEL: "+str( self._state["current_level"])+" LINES: " + str(self._grid.num_lines_cleared),1, COLORS["red"])
            if self._state["all_finished"]:
                game_over_text     = self._font.render("ALL LEVELS FINISHED! LEVEL: "+str( self._state["current_level"])+" LINES: " + str(self._grid.num_lines_cleared),1, COLORS["red"])
            game_over_text_pos = Rect((self._params["grid_top_x"]+1, self._params["grid_top_y"]+1),(self._params["grid_top_x"] + 300, self._params["grid_top_y"] + 20))
            self._screen.blit(game_over_text,game_over_text_pos)
            for i in range(0, len(self._params["modes"])):
                pLineText       = self._params["modes"][i]
                p_lines_text     = self._font.render(pLineText, 1, COLORS["white"])
                p_lines_text_pos = Rect((1+self._params["grid_top_x"],100+(i*25)+self._params["grid_top_y"]),(300,250))
                self._screen.blit(p_lines_text, p_lines_text_pos)


    def add_event_handler(self, eh):
        self._event_handlers.append(eh)
Exemple #51
0
#Vec2 and Vec3 will help positioning the objects
from panda3d.core import Vec2,Vec3
from panda3d.core import Point2, Point3, CardMaker

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

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

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

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



class PlayScreenHUD (DirectObject):
	def __init__(self, gameScreenFSM, mousePicking):
		self.gameScreenFSM = gameScreenFSM
		self.mousePicking = mousePicking
		self.playScreenFrame=None
		self.isoScale = 3.2
		self.scale = (self.isoScale,1,self.isoScale)
lastNumLinesCleared = 0
topY                = 0
timesFound          = 0
current_level       = 1
fallingRate         = .00100
movingRate          = [0.00005,.00004,0.00003,0.00002,0.00001]
rotatingRate        = [0.00009,0.00008,0.00007,0.00006,0.00005]
currentY            = 0
textBuff            = 2
rateIncrease        = .00015
grid                = Grid(1,1,cell_width,cell_height,num_cells_wide,num_cells_high,black)
gameOver            = False
tetrominoList       = ['T','I','O','S','Z','L','J']
levels              = [0.0004,0.00025,0.0001,0.00005,0.00002]
tetromino           = Tetromino(starting_cell_x,starting_cell_y,black,blue,tetrominoList[0])
sound               = Sound()

#Init Pygame
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.init()
screen = pygame.display.set_mode((grid.width+textBuff,grid.height+textBuff),0,32)
pygame.display.set_caption("Python Tetris")
#Initialize Fonts
if pygame.font:
    font = pygame.font.Font(None, 18)


#Main Game Loop

while True:
    time.sleep(0.01)   
Exemple #53
0
from Sound import *

import numpy as np
import matplotlib.pyplot as plt

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

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

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

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

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

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

plt.plot(fundamental*harmonics, s.amplitudes, 'go-', label='With Formant')
plt.legend()
plt.show()
Exemple #54
0
            logging.debug('Enabled "psyco" just-in-time Python compiler')
            psyco.full()
        except ImportError:
            logging.debug('"psyco" just-in-time Python compiler not found')
   
    # Set up PyGame
    import pygame
    pygame.display.init()
    pygame.font.init()
    pygame.joystick.init()
 
    try:
        pygame.mixer.init(48000, -16, True, 4096)
    except pygame.error, e:
        options.quiet = True
        logging.warn("Couldn't initialize sound: " + str(e))

    # Import our own modules
    import Resources
    import Sound
    import twistedmain

    # Set texture size
    Resources.texture.setTextureSize(64)

    # Initialize Sound
    Sound.setQuiet(options.quiet)

    twistedmain.run(options)
    
Exemple #55
0
def main():
    """The main function!"""

    global theClock, theBoard, thePiece, thePieceColor
    global pieceX, pieceY, idealX, idealY
    global boardWidth, boardHeight
    global borderWidth, borderHeight, extraBorder, countFrom
    global theEventQueue, timeDelta, theScore, theHighScore, theMultiplyer, gameTime
    global highScoreWasChanged, highScoreFile

    print ""

    boardWidth = 16
    boardHeight = 15
    borderWidth = 8
    borderHeight = 8
    extraBorder = 35

    highScoreFile = "highscore.dat"

    gameTime = 0    # Time the game has been running (allowed to overflow)
    countFrom = 0   # Time we count from for countdown

    pieceX = pieceY = idealX = idealY = 0.0

    theScore = 0
    theHighScore = 0
    theMultiplyer = 1

    random.seed()

    pygame.init()

    pygame.display.set_mode((640, 480), pygame.OPENGL | pygame.DOUBLEBUF)

    pygame.key.set_repeat(100, 100)   # Turn on key repeat for us

    Video.initThings(boardWidth * 8 + borderWidth * 2 + extraBorder,
                     boardHeight * 8 + borderHeight * 2,
                     160)

    Sound.initSound()

    theClock = pygame.time.Clock()
    timeDelta = 0

    theEventQueue = EventQueue.EventQueue()

    theEventQueue.addToQueue("Gamestate", "Get New Board")
    theEventQueue.addToQueue("Gamestate", "Get New Piece")
    theEventQueue.addToQueue("Score", "Reset Score")
    theEventQueue.addToQueue("Program", "Get Highscore")

    while 1:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                theEventQueue.addToQueue("Program", "Save Highscore")
                theEventQueue.addToQueue("Program", "Quit")
            elif event.type == pygame.KEYDOWN:
                checkKeys(event)      

        theEventQueue.addToQueue("Gamestate", "Update Piece Position")
        theEventQueue.addToQueue("Video", "Redraw Buffer")
        theEventQueue.addToQueue("Video", "Swap Buffers")
        theEventQueue.addToQueue("Program", "Tick Clock")
        
        runThroughQueue()
Exemple #56
0
def runThroughQueue():
    """Go through the queue and deal with the events in it."""

    global timeDelta, theEventQueue, theClock
    global idealX, idealY, boardWidth, boardHeight
    global theBoard, thePiece, thePieceColor
    global theScore, theMultiplyer, gameTime, countFrom
    global theHighScore, highScoreHasChanged

    while theEventQueue.isEmpty() == 0:
        type, info, tuple = theEventQueue.getFromQueue()
        if type == "Gamestate":
            if info == "Check For Squares":
                squareList = theBoard.findSquaresToRemove()

                if len(squareList) > 0:
                    # Squares were found, mark 'em dead.
                    # Note that by putting "Done With Blocks" on the event queue
                    #   now, it will be executed AFTER the block scores are added
                    for i in range(len(squareList)):
                        dataTuple = (i + 1) * 100
                        theEventQueue.addToQueueFront("Score", "Block Found", dataTuple)
                        (x, y) = squareList[i]
                        theBoard.markSquareAsDead(x, y)
            elif info == "Get New Board":
                prepareBoard()
            elif info == "Get New Piece":
                idealX = idealY = pieceX = pieceY = 0.0
                thePiece = Pieces.getPiece()
                thePieceColor = random.randint(1, 7)
            elif info == "Out of Time":
                theEventQueue.addToQueueFront("Input", "Place Piece", "Forced")
            elif info == "Update Piece Position":
                updatePiecePosition(timeDelta)
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Input":
            if info == "Move Piece Down":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc <= (boardHeight - 3)):
                    if (theBoard.checkForCollision(xLoc, yLoc + 1, thePiece)  <= 0):
                        idealY += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Left":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc >= 0):
                    if (theBoard.checkForCollision(xLoc - 1, yLoc, thePiece) <= 0):
                        idealX -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Right":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (xLoc <= (boardWidth - 3)):
                    if (theBoard.checkForCollision(xLoc + 1, yLoc, thePiece) <= 0):
                        idealX += 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Move Piece Up":

                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if (yLoc >= 0):
                    if (theBoard.checkForCollision(xLoc, yLoc - 1, thePiece) <= 0):
                        idealY -= 8.0
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Move")
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Place Piece":

                # First we get the x,y of the piece
                
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)

                if theBoard.checkForCollision(xLoc, yLoc, thePiece) == 0:
                    countFrom = gameTime    # Resets the countdown, move to event?
                    theBoard.placePiece(xLoc, yLoc, thePiece, thePieceColor)
                    theEventQueue.addToQueueFront("Score", "Placed Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Get New Piece")
                    theEventQueue.addToQueueFront("Gamestate", "Check For Squares")
                else:
                    if tuple == "Forced":
                        theEventQueue.addToQueueFront("Program", "Game Over")
                        theEventQueue.addToQueueFront("Notification", "Game Over")
                    else:
                        theEventQueue.addToQueueFront("Notification", "Can't Place")
            elif info == "Rotate Clockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateRight(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            elif info == "Rotate Counterclockwise":
                xLoc = int(idealX / 8.0)
                yLoc = int(idealY / 8.0)
                tempPiece = RotateBlocks.rotateLeft(thePiece)
                if (theBoard.checkForCollision(xLoc, yLoc, tempPiece) <= 0):
                    thePiece = tempPiece
                else:
                    theEventQueue.addToQueueFront("Notification", "Can't Move")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Notification":
            if info == "Can't Move":
                Sound.playSound("Bad Move")
            elif info == "Can't Place":
                Sound.playSound("Bad Place")
            elif info == "Game Over":
                Sound.playSound("Game Over")
            elif info == "Got High Score":
                Sound.playSound("Got High")
            elif info == "Out Of Time":
                Sound.playSound("Forced")
            elif info == "Piece Placed":
                Sound.playSound("Place")
            elif info == "Squares Removed":
                Sound.playSound("Removed")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Program":
            if info == "Game Over":
                # Game over stuff goes here
                # For now, just quit
                theEventQueue.addToQueueFront("Program", "Quit")
                theEventQueue.addToQueueFront("Program", "Save Highscore")
            elif info == "Get Highscore":
                getTheHighScore()
                highScoreHasChanged = False
            elif info == "Help":
                help()
            elif info == "Print FPS":
                 print "FPS: %.1f" % (theClock.get_fps())
            elif info == "Quit":
                sys.exit()
            elif info == "Save Highscore":
                if highScoreHasChanged:
                    saveTheHighScore()
            elif info == "Tick Clock":
                timeDelta = theClock.tick(60)   # Limit ourselves to 60 FPS
                gameTime = gameTime + timeDelta
                if abs(gameTime - countFrom) > 10000:
                    countFrom = gameTime
                    theEventQueue.addToQueueFront("Gamestate", "Out of Time")
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Score":
            if info == "Add To Score":
                oldScore = theScore

                theScore = theScore + tuple

                if (theScore > theHighScore):
                    if (oldScore < theHighScore):
                        highScoreHasChanged = True
                        theEventQueue.addToQueueFront("Notification", "Got High Score")
                    theHighScore = theScore
            elif info == "Block Found":
                if tuple == None:
                    theEventQueue.addToQueueFront("Score", "Add To Score", 100 * theMultiplyer)
                else:
                    theEventQueue.addToQueueFront("Score", "Add To Score", tuple * theMultiplyer)
            elif info == "Placed Piece":
                theEventQueue.addToQueueFront("Score", "Add To Score", 5)
            elif info == "Reset Score":
                theScore = 0
                theMultiplyer = 1
            elif info == "Reset High Score":
                theHighScore = 0
                highScoreHasChanged = True
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        elif type == "Video":
            if info == "Change Culling":
                Video.changeCulling()
            elif info == "Decrease Light X":
                Video.moveLight(-0.5, 0, 0)
            elif info == "Decrease Light Y":
                Video.moveLight(0, -0.5, 0)
            elif info == "Decrease Light Z":
                Video.moveLight(0, 0, -0.5)
            elif info == "Increase Light X":
                Video.moveLight(0.5, 0, 0)
            elif info == "Increase Light Y":
                Video.moveLight(0, 0, 0.5)
            elif info == "Increase Light Z":
                Video.moveLight(0, 0, 0.5)
            elif info == "Print Light Position":
                Video.moveLight(0, 0, 0)
            elif info == "Redraw Buffer":
                draw(timeDelta)
            elif info == "Sink Blocks":
                Video.sinkEm(theBoard, timeDelta)
            elif info == "Swap Buffers":
                pygame.display.flip()
            elif info == "Toggle Lights":
                Video.toggleLights()
            else:
                print "Unknown %s event '%s' disregarded." % (type, info)
        else:
            print "Event of unknown type '%s' with info '%s' disregarded." % (type, info)

    return # Done here    
 def moveLeft(self):
     if self.canMove() and self.x > 0:
         self.x -= 1
         Sound.cursorMove()
         GUI.get().scrollTo((self.x, self.y))
class Grid(object):
    def __init__(self, start_x, start_y, cell_height, cell_width, num_cells_wide, num_cells_tall, color):
        self.cells = {}
        self.start_x = start_x
        self.start_y = start_y
        self.cell_height = cell_height
        self.cell_width = cell_width
        self.num_cells_wide = num_cells_wide
        self.num_cells_tall = num_cells_tall
        self.numLinesCleared = 0
        self.color = color
        self.height = cell_height * num_cells_tall
        self.width = cell_width * num_cells_wide
        self.sound = Sound()
        # Build Grid
        for x in range(self.num_cells_wide):
            for y in range(self.num_cells_tall):
                self.cells[(x, y)] = (
                    color,
                    Rect(
                        (x * self.cell_width + self.start_x, y * self.cell_height + self.start_y),
                        (self.cell_height, self.cell_width),
                    ),
                    0,
                )

    def set(self, color, x, y, id):
        self.cells[(x, y)] = (
            color,
            Rect(
                (x * self.cell_width + self.start_x, y * self.cell_height + self.start_y),
                (self.cell_height, self.cell_width),
            ),
            id,
        )

    def render(self, screen):
        screen.lock()
        for key in self.cells:
            cell = self.cells[key]
            # BG Rect
            if cell[2] > 0:
                pygame.draw.rect(screen, (0, 0, 0), cell[1])
                rectLeft = cell[1].left + 1
                rectTop = cell[1].top + 1
                rectWidth = cell[1].width - 2
                rectHeight = cell[1].height - 2
                nRect = Rect(rectLeft, rectTop, rectWidth, rectHeight)
                pygame.draw.rect(screen, cell[0], nRect)
            else:
                pygame.draw.rect(screen, cell[0], cell[1])
        screen.unlock()

    def accept(self, id, postions, x_mv, y_mv):
        for pos in postions:
            x = pos[0] + x_mv
            y = pos[1] + y_mv
            if self.cells.has_key((x, y)):
                cell = self.cells[(x, y)]
                if cell and cell[2] != id and cell[2] != 0:
                    return False
            else:
                return False
        return True

    def checkForLines(self):
        nums = {}
        # Test for y coords with all thier x coords filled up
        # If so then set that line of x,y coords to masking color and move the rest of the coords
        # above it down one y coord
        for cell in self.cells:
            y = cell[1]
            if not nums.has_key(y):
                nums[y] = 0
            if self.cells[cell][2] > 0:
                nums[y] += 1
        for num in nums:
            if nums[num] >= self.num_cells_wide:
                self.sound.play("../sound/clear.wav")
                self.numLinesCleared += 1
                self.remLine(num)
                self.shiftGridDown(num)

    def topY(self):
        top = self.num_cells_tall
        for cell in self.cells:
            y = cell[1]
            if y < top and self.cells[cell][2] > 0:
                top = y
        return top

    def remLine(self, y):
        for cell_x in range(self.num_cells_wide):
            self.set(self.color, cell_x, y, 0)

    def shiftGridDown(self, num):
        n_cells = {}
        for cell in self.cells:
            x = cell[0]
            y = cell[1]
            color = self.cells[cell][0]
            id = self.cells[cell][2]
            if y < num:
                self.set(self.color, x, y, id)
                n_cells[(x, y + 1)] = (
                    color,
                    Rect(
                        (x * self.cell_width + self.start_x, y * self.cell_height + self.start_y),
                        (self.cell_height, self.cell_width),
                    ),
                    id,
                )
        for n_cell in n_cells:
            x = n_cell[0]
            y = n_cell[1]
            color = n_cells[n_cell][0]
            id = n_cells[n_cell][2]
            self.set(color, x, y, id)
 def moveRight(self):
     if self.canMove() and self.x < self.map.width - 1:
         self.x += 1
         Sound.cursorMove()
         GUI.get().scrollTo((self.x, self.y))
Exemple #60
0
    def _setup_states(self, mode = 0):
        self._params = {
            "fullscreen"             : False,
            "fullscreen_width"       : 1024,
            "fullscreen_height"      : 768,
            "num_cells_wide"         : 10,
            "num_cells_high"         : 20,
            "cell_width"             : 25,
            "cell_height"            : 25,
            "drink_pouring_time"     : 10.0,
            "starting_cell_x"        : 4,
            "starting_cell_y"        : 1,
            "grid_top_x"             : 0,
            "grid_top_y"             : 0,
            "modes"                  : ["(N)ormal Mode", "(B)ooze Mode", "(S)ingle Drink Mode", "(D)esignated Driver Mode", "(Q)uit"]
            }

        self._level_params = {
            "moving_rate"            : [0.00005,.00004,0.00003,0.00002,0.00001],
            "rotating_rate"          : [0.00009,0.00008,0.00007,0.00006,0.00005],
            "falling_rate"           : [0.00050,0.00035,0.00020,0.00010,0.00005]
            }

        self._state = {
            "last_falling_time"      : 0,
            "falling_rate"           : self._level_params["falling_rate"][0],
            "last_moving_time"       : 0,
            "last_rotating_time"     : 0,
            "level_up_line_count"    : 5,
            "last_num_lines_cleared" : 0,
            "top_y"                  : 0,
            "times_found"            : 0,
            "current_level"          : 1,
            "game_over"              : False,
            "all_finished"           : False,
            "current_y"              : 0,
            "holding_down"           : False
            }


        if mode in [self.NORMAL_MODE, self.SINGLE_DRINK_MODE]:
            self._color_dict     = {1: COLORS["blue"], 6 : COLORS["brown"], 10: COLORS["darkGrey"]}        
        elif mode == self.BOOZE_MODE:
            self._color_dict     = {3 : COLORS["brown"], 10: COLORS["darkGrey"]}
        elif mode == self.DESIGNATED_DRIVER_MODE:
            self._color_dict     = {10: COLORS["blue"]}

        if mode == self.SINGLE_DRINK_MODE or mode == self.BOOZE_MODE:
            self._level_params = {
                "moving_rate"            : [0.00005],
                "rotating_rate"          : [0.00009],
                "falling_rate"           : [0.00040]
                }
            self._params["drink_pouring_time"] = 20.0

        self._color_range    = 10

        self._textBuff       = 2
        self._grid           = Grid( 1, 1, self._params["cell_width"], self._params["cell_height"], self._params["num_cells_wide"], self._params["num_cells_high"], COLORS["black"], self._params["fullscreen"], self._params["fullscreen_width"], self._params["fullscreen_height"])
        if self._params["fullscreen"]:
            self._params["grid_top_x"] = (self._params["fullscreen_width"] / 2) - (self._grid.width / 2)
            self._params["grid_top_y"] = (self._params["fullscreen_height"] / 2) - (self._grid.height / 2)

        self._tetrominoList  = ['T','I','O','S','Z','L','J']
        self._sound          = Sound()

        self._new_tetromino()