示例#1
0
    def __init__(self):

        #questions = QuestionPack4().questions
        pygame.init()
        self.plateau = Plateau(1280, 700, "./images")
        self.partie = None
        self.sound_manager = SoundManager("./audio")
示例#2
0
文件: game.py 项目: doches/Bebop
class game:
	def __init__(self,surface,clock):
		self.loader = Loader()
		self.loader.init_map()
		self.sound = SoundManager()
		self.sound.init_sound_manager()
		self.clock = clock
		self.alive = True
		self.screen = surface
		self.width = surface.get_size()[0]
		self.height = surface.get_size()[1]
		self.screens = 	[AuthorScreen(3)]
		self.current_screen = 0
		self.screens[self.current_screen].on_focus()
		
	def reset(self):
		self.current_screen = 0
		self.screens[self.current_screen].on_focus()
		#self.layers.append(FPSScreen(self.clock))
	
	def draw(self):
		# INCREDIBLY wasteful...
		self.screen.fill( (0,0,0) )
		self.screens[self.current_screen].draw(self.screen)
		return True
		
	def handle_event(self,event):
		if event.type == QUIT:
			self.alive = False
		elif event.type == KEYDOWN:
			self.changed = True
			if event.key == K_ESCAPE:
				self.alive = False
		try:
			self.screens[self.current_screen].handle_event(event)
		except AttributeError:
			True
	
	def update(self):
		# If the current screen returns FALSE we should move to the next screen in the list.
		retval = self.screens[self.current_screen].update()
		if retval == False:
			if self.current_screen < len(self.screens)-1:
				self.current_screen += 1
				self.screens[self.current_screen].on_focus()
				return True
			else:
				return False
		else:
			return True
示例#3
0
 def __init__(self, positions, main):
     self._players = [ Player("Ninja", "ninja", positions[1], self, 0), Player("Pirate", "pirate", positions[0], self, 1) ] 
     self._collision = Collision(self._players[0], self._players[1])
     self._eventOccured = [ False, False ]
     self._soundManager = SoundManager()
     self._elapsedTime = 0;
     self.main = main
示例#4
0
class AuthorScreen(AbstractScreen):
	def __init__(self,ttl):
		AbstractScreen.__init__(self)
		self.loader = Loader()
		self.state = State()
		large_font = self.loader.load_font("slkscr",72)
		med_font = self.loader.load_font("slkscr",32)
		small_font = self.loader.load_font("slkscr",16)
		x = self.state.screen_size[0]/2
		y = self.state.screen_size[1]/2
		self.labels = [ Label("a rapid framework",med_font,(255,96,96),[x-280,y-30]),
						Label("Bebop",large_font,(255,255,255),[x-180,y-10]),
						Label("for game compos",small_font,(255,255,255),[x-70,y+50])
		 			  ]
		for label in self.labels:
			label.goal_alpha = 255
		# Set up fade timer
		self.ttl = ttl
		self.sound = SoundManager()
	
	def on_focus(self):
		self.start = pygame.time.get_ticks()
		self.fade_out = self.start + self.ttl*1000
		self.alive = True
		self.sound.start_music(0)
		
	def update(self):
		AbstractScreen.update(self)
		time = pygame.time.get_ticks()
		if time >= self.fade_out and self.alive:
			self.alive = False
			for label in self.labels:
				label.goal_alpha = 0
		elif time >= self.fade_out and self.labels[0].alpha == 0:
			return False
		for label in self.labels:
			label.update()
		return True
	
	def handle_event(self,event):
		if event.type == pygame.locals.KEYDOWN or event.type == pygame.locals.MOUSEBUTTONDOWN:
			self.fade_out = self.start
	
	def draw(self,screen):
		for label in self.labels:
			label.draw(screen)
		return True
示例#5
0
    def __init__(self):
        self.sm = SoundManager()
        self.qm = QuartzManager()
#        self.am = Arduino()
        self.am = QuartzScoreManager()
        self.bm = BuzzManager()
        self.pm = PerguntasManager()
        self.cm = ConsoleManager()
        self.scores = [0, 0, 0, 0]
        self.player_button_pool = []
示例#6
0
文件: game.py 项目: doches/Bebop
	def __init__(self,surface,clock):
		self.loader = Loader()
		self.loader.init_map()
		self.sound = SoundManager()
		self.sound.init_sound_manager()
		self.clock = clock
		self.alive = True
		self.screen = surface
		self.width = surface.get_size()[0]
		self.height = surface.get_size()[1]
		self.screens = 	[AuthorScreen(3)]
		self.current_screen = 0
		self.screens[self.current_screen].on_focus()
示例#7
0
    def __init__(self, num_lanes, path, level, speed):
        Arbapp.__init__(self)
        self.num_lanes = num_lanes
        self.score = 0
        self.speed = float(speed)
        self.rate = Rate(self.speed)
        self.grid = [['background']*num_lanes for h in range(self.height)] # The coming notes (last line included even if it will overwritten by the bottom bar)
        self.bar = ['idle']*num_lanes # The bottom bar, idle = not pressed, hit = pressed during a note, pressed = pressed outside a note

        # Threads creation and starting
        self.renderer = Renderer(self.model, self.grid, self.bar, self.height, num_lanes, self.width)
        self.reader = SongReader(path, num_lanes, level, speed)
        self.sound = SoundManager(path)
        self.hits = UserHits(self.num_lanes)
示例#8
0
 def initSounds(self):
     sounds = {
         "DetectionMode": QSound("resources/voices/detect_start.wav"),
         "SleepMode": QSound("resources/voices/sleep_mode.wav"),
         "Activation": QSound("resources/voices/activated.wav"),
         "Spotted": QSound("resources/voices/target_aquaired.wav"),
         "Shutdown": QSound("resources/voices/shutdown.wav"),
         "Searching": QSound("resources/voices/searching.wav"),
         "StartUp": QSound("resources/voices/startup.mp3"),
         "Login": QSound("resources/voices/login_sound.wav"),
         "Save": QSound("resources/voices/save_sound.wav"),
         "Error": QSound("resources/voices/error.wav"),
         "Moron": QSound("resources/voices/hey_moron.wav")
     }
     return SoundManager(sounds)
示例#9
0
	def __init__(self,ttl):
		AbstractScreen.__init__(self)
		self.loader = Loader()
		self.state = State()
		large_font = self.loader.load_font("slkscr",72)
		med_font = self.loader.load_font("slkscr",32)
		small_font = self.loader.load_font("slkscr",16)
		x = self.state.screen_size[0]/2
		y = self.state.screen_size[1]/2
		self.labels = [ Label("a rapid framework",med_font,(255,96,96),[x-280,y-30]),
						Label("Bebop",large_font,(255,255,255),[x-180,y-10]),
						Label("for game compos",small_font,(255,255,255),[x-70,y+50])
		 			  ]
		for label in self.labels:
			label.goal_alpha = 255
		# Set up fade timer
		self.ttl = ttl
		self.sound = SoundManager()
示例#10
0
 def __init__(self):
     #Display setup
     self.resolution = (
     )  #This is filled by ChooseResolution scene(further down this page)
     self.display = pygame.display.set_mode((400, 400))
     self.fullScreen = False
     #Scene management
     self.scenes = {"ChooseRes": ChooseResolution()}
     self.currentScene = self.scenes["ChooseRes"]
     self.currentSceneKey = "ChooseRes"
     self.soundManager = SoundManager(
     )  #Plays the musics and used to call sounds in the game
     self.eventHandlers = GameEventHandlers(
         self
     )  #Stores event handlers that work with an event manager. So that an event manager does not have direct control of any of the scenes or game
     self.eventManager = GameEventManager(
         self.eventHandlers, self.soundManager.eventHandlers
     )  #Handles game wide events, like music volume and fullscreen toggle
     self.main()  #Main game loop
示例#11
0
from Sprite_Manager import Sprite_Sheet
from SoundManager import SoundManager
import Game
import pygame
import Time

width = 1280
height = 720
all_sprites = Sprite_Sheet("Art").load_all()
time = Time.Time()
pygame.init()

screen = pygame.display.set_mode((width, height))
screen_copied = screen.copy()
main_loop_running = True
game_manager = Game.Game()
state = "START"

sound_manager = SoundManager()

示例#12
0
class GameController():
    """GameController for Quizz Show"""
    def __init__(self):
        self.sm = SoundManager()
        self.qm = QuartzManager()
#        self.am = Arduino()
        self.am = QuartzScoreManager()
        self.bm = BuzzManager()
        self.pm = PerguntasManager()
        self.cm = ConsoleManager()
        self.scores = [0, 0, 0, 0]
        self.player_button_pool = []

    def begin(self):
        """Game Begin"""
        n = self.cm.ask_int("Qual o grupo de perguntas?")
        self.perguntas = self.pm.perguntas_grupo( n )
        for x in self.perguntas.perguntas(): 
            self.cm.printc( "%d: %s %s" % x)
        
        idx = 0
        print self.scores
        
        idx = self.cm.ask_int("Iniciar em que pergunta (0)?")
        pergunta = self.perguntas.get_pergunta( idx )

        if idx > 0:
            cur_score = self.cm.ask("Current score - (0,0,0,0): ")
            if len(cur_score) > 4:
                self.scores = [int(x) for x in cur_score.split(",")]
                print self.scores


        while pergunta:
            self.ask_pergunta( pergunta )
            pergunta = self.perguntas.get_next()
            
        self.am.lights_off()

    def show_scores(self):
        s = []
        i = 1
        for score in  self.scores:
            if score == 1 : 
                plural = ""
            else : 
                plural = "s"
            s.append("Equipa %d - %d ponto%s" % (i, score, plural))
            i += 1
        self.qm.multiplas(s)
        
        
    def ask_pergunta(self, pergunta):
        self.cm.clear()
        self.am.lights_off()
        self.qm.pontuacao( self.scores )
        print self.scores

        self.qm.multiplas(" ")

        self.cm.printc( "%s: %s" % (pergunta.ordem, pergunta.pergunta) )
        self.qm.perguntar("   Codebits Quiz Show   ")


        # Show scores only if any team has already scored.
        if [x for x in self.scores if x > 0]:
            self.show_scores()
        
        ret = self.cm.ask_options("Enviar (S/N)?", ("S", "N"))
        if ret == "N": return

        self.bm.clear_button_poll()        
        self.qm.multiplas(" ")
           
        player= self.timer_red_buzz(pergunta)
        
        if player != None:
            ret = self.cm.ask_options("Red Buzz %s right? (S/N/(R)etry)" % player, ("S", "N", "I") )
            self.qm.perguntar(pergunta.pergunta)
            
            if ret == "S": 
                time.sleep(5)
                self.scores[player-1] += (2 * pergunta.multiplicador )
                self.qm.pontuacao( self.scores )
                return
            if ret == "R":
                return self.ask_pergunta(pergunta)
                
        self.cm.ask_options("Enviar Multiplas? (S)", ("S") )
        self.timer_multiplas( pergunta, player )
            
    
    def timer_multiplas(self, pergunta, player=None, t=30):
        """controls clock and checks for multiple choice
        events from the buzz"""
        
        if player != None:
            player = int(player)
    
        self.am.lights_off()        
        self.bm.clear_button_poll()
        self.clear_player_button_pool()
        
        self.cm.printc(" ")
        self.cm.printc("Waiting for Multiplas.")
        self.qm.multiplas( [x[0] for x in pergunta.multiplas] )
        
        playersStatus = self.am.get_players_from_int(0)
        
        playerHasResponded = []
        
        if player:
            print "Ignoring %d" %(player,)
            playerHasResponded.append( player )
            self.am.set_player_wrong( player )
            
        try:
            while t >= 0:
                self.qm.relogio( "0:%.2d" % (t,) )
                t -= 1
                if len(playerHasResponded) == 4:
                    self.qm.relogio(" ")
                    break
                
                for x in range(10):
                    time.sleep(0.1)
                    ev = self.bm.poll(True)
                    # No red buttons, nor the player who failed.
                    if ev:
                        if ev.color == "RED" or ev.player in playerHasResponded:
                            continue
                            
                        print ev.multi

                        if pergunta.options[ev.multi][1] == True:    

                            self.sm.play( ev.player )
                            self.am.set_player_right( ev.player )
                            self.scores[ev.player-1] += (1 * pergunta.multiplicador)
                            self.qm.pontuacao( self.scores )
                            
                            
                            print ev.player
                        else:
                            pergunta.add_wrong_player(ev.multi, ev.player)
                            self.sm.playError()
                            self.am.set_player_wrong( ev.player )
                            
                            playersStatus[ev.player - 1][1] = True
                            
                            print "FAIL"
                            print ev.player
                            
                        playerHasResponded.append(ev.player)    
                                            
        except KeyboardInterrupt:
            self.qm.relogio(" ")
        
        # Timeout. No one pressed the Buzz.
        if t < 1:
            self.sm.playTimeOut()
        self.cm.ask_options(" Mostrar resposta certa? (S)", ["S"])
        self.show_correct_answer(pergunta.options)
        self.cm.ask_options("Continuar? (S)", ["S"])


    def show_correct_answer(self, options):
        l = []
        for x in options:
            if x[1] == True: l.append(x[0])
            else:
                l_str = ''
                for p in x[2]:
                    l_str += "(%s) " %(p) 
                if len(l_str) > 2:
                    l_str = "X " + l_str
                    l_str += " %s" %(x[0])
                    l.append (l_str)
                else: 
                    l.append( " ")
        self.qm.multiplas( l )

    def timer_red_buzz(self, pergunta, t=20, has_been_asked=False):
        """controls clock and checks for buzz events
           t is the start time for countdown."""

        # Watch for events during the timer and during the time that the presenter
        # is reading the question.
        if has_been_asked == True:
            self.qm.multiplas(" ")
            self.qm.perguntar( pergunta.pergunta )
        else:
            self.clear_player_button_pool()
            self.bm.clear_button_poll()
            self.qm.perguntar("Podes responder com o botao vermelho.")
            if pergunta.multiplicador > 1:
                self.qm.multiplas(["Score Multiplier active: %dx" %(pergunta.multiplicador), "Straight answer is worth %d points." % (pergunta.multiplicador*2), "", ""])
               
        self.cm.printc(" ")
        self.cm.printc(pergunta.resposta )
        
        self.cm.printc("Waiting RED Buzz.")
        
        try:
            someone_answered = False
            while t > 0:

                if has_been_asked == True:
                    t -= 1
                    self.qm.relogio( "0:%.2d" % (t,) )
                else:
                    self.qm.relogio(" ")
                        
                for x in range(10):
                    time.sleep(0.1)
                    

                    if self.bm.mobile:
                        ev = self.bm.mobile.poll()
                        if ev and ev[1] == 1:
                            if has_been_asked == False:
                                raise KeyboardInterrupt
                                
                    ev = self.bm.poll(True)
                    if ev and ev.color == "RED":
                        print "GOT %d" % (ev.player,)
                        self.show_player_buttons(ev)    
                        self.qm.relogio(" ")
                        someone_answered = True
                        # Clear all other button requests
                        # if there's more than one close player,
                        # show them all.
                        for x in range (20):
                            time.sleep(0.1)
                            ev = self.bm.poll(False)
                            while ev:
                                if ev and ev.pressed:
                                    self.show_player_buttons(ev)
                                ev = self.bm.poll(False) 
                                
                            # Return who won.
                            return self.player_button_pool[3]
                            
        except KeyboardInterrupt:
            self.qm.relogio(" ")
            if has_been_asked == False:
                if someone_answered == True:
                    return self.player_button_pool[3]
                return self.timer_red_buzz( pergunta, 20, True)
                

        # Timeout. No one pressed the Buzz.
        self.sm.playTimeOut()
        self.cm.ask_options("Timeout. Continuar? (S)", ["S"])
        return None


    def clear_player_button_pool(self):
        self.player_button_pool = [{},[], 0,-1]

    def show_player_buttons(self, ev):
        """Show buttons pressed in order"""
        
        bp = self.player_button_pool
        
        if ev.player not in bp[0]:
            player_str = "TEAM %d" % ev.player
            
            # Print timestamp against first player
            if bp[2]:
                player_str += " (%.3f seg)" % ((ev.timestamp + (float(random.randint(1,10)) / 1000)) - bp[2])
            else:
                self.am.set_player_light(ev.player)
                bp[2] = ev.timestamp
                bp[0][ev.player] = True
                bp[3] = ev.player
                
            bp[1].append(player_str)
            for x in bp[1]:
                print x
            
            self.qm.multiplas( bp[1] )
            self.sm.play( ev.player )
            self.player_button_pool = bp
示例#13
0
class LightsHero(Arbapp):
    def __init__(self, num_lanes, path, level, speed):
        Arbapp.__init__(self)
        self.num_lanes = num_lanes
        self.score = 0
        self.speed = float(speed)
        self.rate = Rate(self.speed)
        self.grid = [['background']*num_lanes for h in range(self.height)] # The coming notes (last line included even if it will overwritten by the bottom bar)
        self.bar = ['idle']*num_lanes # The bottom bar, idle = not pressed, hit = pressed during a note, pressed = pressed outside a note

        # Threads creation and starting
        self.renderer = Renderer(self.model, self.grid, self.bar, self.height, num_lanes, self.width)
        self.reader = SongReader(path, num_lanes, level, speed)
        self.sound = SoundManager(path)
        self.hits = UserHits(self.num_lanes)

    def next_line(self):
        # Delete the last line leaving the grid
        # Note : The bottom bar will overwrite the last line but the latter needs to be kept to draw the bottom bar
        for l in range(self.height-1, 0, -1):
            for w in range(self.num_lanes):
                self.grid[l][w] = self.grid[l-1][w]

        # Ask for a new line to the song reader and fill the top of the grid with it
        new_line = self.reader.read()
        for lane in range(self.num_lanes):
            self.grid[0][lane] = new_line[lane]

    def process_user_hits(self):
        """
        Read user inputs, update the bottom bar with key states and warn the UserHits class to update the score
        """
        for lane in range(self.num_lanes):
            must_press = self.grid[self.height-1][lane] == 'active' or self.grid[self.height-1][lane] == 'bump'
            pressed = self.hits.get_pressed_keys()[lane]
            if must_press and pressed:
                status = 'hit'
            elif pressed:
                status = 'pressed'
            else:
                status = 'idle'
            self.bar[lane] = status

            # warn the user hits class whether the note has to be played
            self.hits.set_note(lane, self.grid[self.height-1][lane] in ['bump', 'active'])


    def run(self):
        countdown = self.height # Countdown triggered after Midi's EOF
        start = time()

        # We loop while the end countdown is not timed out
        # it starts decreasing only when EOF is returned by the song reader
        while countdown>0:
            self.next_line()
            self.process_user_hits()
            self.renderer.update_view()

            if self.reader.eof:
                countdown -= 1

            # delayed sound playing while the first notes are reaching the bottom bar
            if not self.sound.started and time()-start > (self.height-2)/self.speed:
                self.sound.start()

            self.rate.sleep()

        print "You scored", int((100.*self.hits.score)/self.hits.max_score), '% with', self.hits.score, 'hits over', self.hits.max_score
示例#14
0
class LightsHero(Arbapp):
    def __init__(self, num_lanes, path, level, speed):
        Arbapp.__init__(self)
        self.num_lanes = num_lanes
        self.score = 0
        self.speed = float(speed)
        self.rate = Rate(self.speed)
        self.grid = [['background']*num_lanes for h in range(self.height)] # The coming notes (last line included even if it will overwritten by the bottom bar)
        self.bar = ['idle']*num_lanes # The bottom bar, idle = not pressed, hit = pressed during a note, pressed = pressed outside a note

        # Threads creation and starting
        self.renderer = Renderer(self.model, self.grid, self.bar, self.height, num_lanes, self.width)
        self.reader = SongReader(path, num_lanes, level, speed)
        self.sound = SoundManager(path)
        self.hits = UserHits(self.num_lanes)

    def next_line(self):
        # Delete the last line leaving the grid
        # Note : The bottom bar will overwrite the last line but the latter needs to be kept to draw the bottom bar
        for l in range(self.height-1, 0, -1):
            for w in range(self.num_lanes):
                self.grid[l][w] = self.grid[l-1][w]

        # Ask for a new line to the song reader and fill the top of the grid with it
        new_line = self.reader.read()
        for lane in range(self.num_lanes):
            self.grid[0][lane] = new_line[lane]

    def process_user_hits(self):
        """
        Read user inputs, update the bottom bar with key states and warn the UserHits class to update the score
        """
        for lane in range(self.num_lanes):
            must_press = self.grid[self.height-1][lane] == 'active' or self.grid[self.height-1][lane] == 'bump'
            pressed = self.hits.get_pressed_keys()[lane]
            if must_press and pressed:
                status = 'hit'
            elif pressed:
                status = 'pressed'
            else:
                status = 'idle'
            self.bar[lane] = status

            # warn the user hits class whether the note has to be played
            self.hits.set_note(lane, self.grid[self.height-1][lane] in ['bump', 'active'])

    def display_score(self):
        levels = [15, 40, 60, 80, 90, 101]
        sentences = ["did you really play?", "you need to practice...", "I'm pretty sure you can do better...",
                    "that's a fair score!", "awesome, you're a master!", "incredible, did you cheat?"]
        colors = ['darkred', 'orange', 'gold', 'yellowgreen', 'green', 'white']
        score = int((100.*self.hits.score)/self.hits.max_score)

        for i, level in enumerate(levels):
            if score<level:
                sentence = sentences[i]
                color = colors[i]
                break

        print "You scored", score, '% with', self.hits.score, 'hits over', self.hits.max_score

        if self.hits.score>0:
            self.model.write("You scored {}%, {}".format(score, sentence), color)

    def run(self):
        countdown = self.height # Countdown triggered after Midi's EOF
        start = time()

        # We loop while the end countdown is not timed out
        # it starts decreasing only when EOF is returned by the song reader
        while countdown>0:
            self.next_line()
            self.process_user_hits()
            self.renderer.update_view()

            if self.reader.eof:
                countdown -= 1

            # delayed sound playing while the first notes are reaching the bottom bar
            if not self.sound.started and time()-start > (self.height-2)/self.speed:
                self.sound.start()

            self.rate.sleep()
        self.display_score()
示例#15
0
 def checkEvent(self, event):
     if event.type == pygame.QUIT:
         Pgl.app.stop()
     elif event.type == pygame.USEREVENT:
         SoundManager.getInstance().stopMusic()
         SoundManager.getInstance().playMusic(SoundManager.getInstance().CURRENTSONG+1)
示例#16
0
class Main:
    def __init__(self):

        #questions = QuestionPack4().questions
        pygame.init()
        self.plateau = Plateau(1280, 700, "./images")
        self.partie = None
        self.sound_manager = SoundManager("./audio")

    # Call public -> P
    # Call friend -> J
    # 50/50       -> L
    # Reset       -> R
    # Next question -> N
    # A B C D -> SELECT RESPONSE
    # ENTER -> Show result
    # ESCAPE -> Quit game
    #

    def reset(self):
        filename = FileChooser().get_filename()
        questions = Reader(filename).get_questions()
        if questions is None:
            return False

        self.partie = Partie(questions)
        # reset game
        self.partie.reset()
        self.plateau.reset()
        self.sound_manager.reset()
        self.sound_manager.play_generic()
        return True

    def start_game(self):
        question = self.partie.get_current_question()
        index = self.partie.current_question_index

        self.sound_manager.start_party_jingle()
        self.plateau.fill_question_area(question)
        self.sound_manager.play_ongoing_question(index)

    def select_response(self, letter):
        question = self.partie.get_current_question()
        index = self.partie.current_question_index

        self.partie.select_response(letter)
        self.plateau.select_answer(question, letter)
        self.sound_manager.play_last_word(index)

    def show_response(self):
        question = self.partie.get_current_question()
        index = self.partie.current_question_index

        good = self.partie.response_is_good()
        if good:
            self.sound_manager.play_good_response(index)
            winned_price = self.partie.gains[index]
            self.plateau.good_response(question, winned_price,
                                       self.partie.letter_selected)

        else:
            self.sound_manager.play_wrong_answer()
            self.plateau.wrong_response(question, question.good_letter)

    def run(self):
        self.reset()
        self.running = True
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    print("key")
                    print(event.key)
                    if event.key == pygame.K_q:
                        print("press A")
                        # answer a
                        self.select_response("A")

                    elif event.key == pygame.K_b:
                        print("press B")
                        # answer b
                        self.select_response("B")

                    elif event.key == pygame.K_c:
                        print("press C")
                        # answer c
                        self.select_response("C")

                    elif event.key == pygame.K_d:
                        print("press D")
                        # answer d
                        self.select_response("D")

                    elif event.key == pygame.K_p:
                        print("press P")
                        # public vote
                        # DISABLED

                    elif event.key == pygame.K_j:
                        print("press J")
                        # call friend
                        if self.partie.call_friend_available > 0:
                            self.partie.call_friend_available = self.partie.call_friend_available - 1
                            index = self.partie.current_question_index
                            self.sound_manager.play_call_friend(index)
                            if self.partie.call_friend_available == 0:
                                self.plateau.update_call_friend(False)
                    elif event.key == pygame.K_l:
                        print("press L")
                        # 50/50
                        if self.partie.fiftyfifty_available > 0:
                            self.partie.fiftyfifty_available = self.partie.fiftyfifty_available - 1
                            index = self.partie.current_question_index

                            question = self.partie.get_current_question()
                            choices = ["A", "B", "C", "D"]
                            choices.remove(question.good_letter)
                            first_answer_removed = choices[randint(
                                0,
                                len(choices) - 1)]
                            choices.remove(first_answer_removed)
                            second_answer_removed = choices[randint(
                                0,
                                len(choices) - 1)]

                            self.sound_manager.play_fifty_fifty()
                            self.plateau.hide_answers(
                                [first_answer_removed, second_answer_removed])
                            if self.partie.fiftyfifty_available == 0:
                                self.plateau.update_fifty_fifty(False)
                    elif event.key == pygame.K_r:
                        print("press R")
                        if self.reset():
                            pass
                        else:
                            self.running = False
                            pygame.quit()
                            return

                    elif event.key == pygame.K_s:
                        print("press S")
                        # start game
                        self.start_game()

                    elif event.key == pygame.K_n:
                        print("press N")
                        # next question
                        question = self.partie.next_question()
                        index = self.partie.current_question_index
                        self.plateau.fill_question_area(question)
                        self.sound_manager.play_ongoing_question(index)

                    elif event.key == pygame.K_RETURN:
                        print("press ENTER")
                        # enter show response
                        self.show_response()
                    elif event.key == pygame.K_ESCAPE:
                        print("press ESCAPE")
                        self.running = False
                        pygame.quit()
                        return
示例#17
0
 def __init_sound(self):
     "Initialize SoundManager"
     self.sound = SoundManager(self.soundFiles)
示例#18
0
class Pong:
    """
	Handles drawing of all components. 
	players -> Players[] list of players
	ball -> Ball ball to be bouncing in Pong
	scoreboard -> TextHandler scoreboard displayed on screen
	state -> boolean[] a list of booleans representing each state of the game
	MAX_POINTS -> the max points by default 
	"""
    SETTINGS = {
        "MAX_POINTS":
        8,
        "players": [{
            "name": "Player 1",
            "color": (255, 9, 9)
        }, {
            "name": "Player 2",
            "color": (40, 40, 255)
        }]
    }
    DEFAULT_SIZE = width, height = 600, 600
    FONT_SIZE = 52
    MAX_POINTS = 2
    soundFiles = ["paddle.wav", "point.wav", "winning_song.wav"]

    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Pong: Leon")

        self.screen = pygame.display.set_mode(self.DEFAULT_SIZE,
                                              pygame.RESIZABLE)
        self.__init_players()
        self.__init_sound()
        self.__init_menus()

        self.ball = Ball(self, self.players, speed=9)
        self.scoreboard = TextHandler(self, self.players)
        self.state = [False for state in GameState.states.keys()]
        self.set_game_state_to(GameState.states["START"])

        #menus

    def __init_menus(self):
        "Setups menus"
        startMenu = Menu(self, "Start Menu")
        startOption = MenuOption(self, "Start", self.start_game)
        exitOption = MenuOption(self, "Exit", quit)
        startMenu.addOption(startOption)
        startMenu.addOption(exitOption)

        self.set_current_menu(startMenu)

    def __init_players(self):
        "Initializes players"
        self.players = [
            Player("Player 1",
                   self,
                   Player.PLAYER_1,
                   color=(255, 9, 9),
                   controls={
                       'up': pygame.K_w,
                       'down': pygame.K_s
                   }),
            Player("Player 2", self, Player.PLAYER_2)
        ]
        self.currentWinner = None

    def __init_sound(self):
        "Initialize SoundManager"
        self.sound = SoundManager(self.soundFiles)

    def draw(self):
        """
			Draws all components of the game.	
		"""
        self.screen.fill(black)

        if (self.state[GameState.states["PLAY"]]):
            self.__draw_players()
            self.__draw_middle_lines()
            self.scoreboard.draw()
            self.ball.draw()
            #middle line
        elif (self.state[GameState.states["PAUSE"]]):
            self.scoreboard.draw_pause()
        elif (self.state[GameState.states["START"]]):
            self.draw_current_menu()
        elif (self.state[GameState.states["WINNER"]]):
            self.scoreboard.draw_winner(self.currentWinner)

        self.event_check()
        self.check_option_hover()
        pygame.display.flip()
        self.__control_handler()

    def __draw_players(self):
        "draws players in game"
        for player in self.players:
            player.draw()

    def __draw_middle_lines(self):
        """Draws middle white lines and colored player lines
		Colored player lines represent how far the player is from winning.
		"""
        screenHeight = self.screen.get_height()
        screenWidth = self.screen.get_width()
        screenCenterX = self.get_screen_center(X=True)

        #player1 progress
        player1 = self.players[Player.PLAYER_1]
        percentageToMaxPoints = float(Pong.MAX_POINTS -
                                      player1.points) / Pong.MAX_POINTS
        pygame.draw.line(
            self.screen, player1["color"],
            (screenCenterX - 3, screenHeight * percentageToMaxPoints),
            (screenCenterX - 3, self.screen.get_height()), 3)
        #middleline
        pygame.draw.line(
            self.screen, white, (self.get_screen_center(X=True), 0),
            (self.get_screen_center(X=True), self.screen.get_height()))

        #player2 progress
        player2 = self.players[Player.PLAYER_2]
        percentageToMaxPoints = float(Pong.MAX_POINTS -
                                      player2.points) / Pong.MAX_POINTS
        pygame.draw.line(
            self.screen, player2["color"],
            (screenCenterX + 3, screenHeight * percentageToMaxPoints),
            (screenCenterX + 3, screenHeight), 3)

    def set_game_state_to(self, gameState):
        "Sets the game state"
        #set all to false
        for i, state in enumerate(self.state):
            self.state[i] = False

        self.state[gameState] = True

    def __control_handler(self):
        keyDown = pygame.key.get_pressed()
        if (keyDown[pygame.K_p]):
            self.pause()
        elif (keyDown[pygame.K_RETURN]):
            if (self.state[GameState.states["START"]]):
                self.ball.start_count_down()
                self.play()
            if (self.state[GameState.states["WINNER"]]):
                self.restart()
        elif (keyDown[pygame.K_ESCAPE]
              and not self.state[GameState.states["PLAY"]]):
            quit()

    def pause(self):
        "Pauses the game"
        self.set_game_state_to(GameState.states["PAUSE"])

    def play(self):
        "Continues the game"
        self.set_game_state_to(GameState.states["PLAY"])

    def start_game(self):
        "Starts game from beginning"
        self.set_game_state_to(GameState.states["PLAY"])
        self.ball.start_count_down()

    def get_screen_center(self, **kwargs):
        """
		Returns a tuple of the screen center by default
		if X is set it returns just the widths middle
		if Y is set it returns just the widths middle
		if X and Y are set to True it returns the default tuple
		"""
        widthCenter = self.screen.get_width() / 2
        heightCenter = self.screen.get_height() / 2
        if ("X" in kwargs and "Y" in kwargs):
            return (widthCenter, heightCenter)
        if ("X" in kwargs):
            return widthCenter
        if ("Y" in kwargs):
            return heightCenter

        return (widthCenter, heightCenter)

    def set_current_menu(self, menu):
        "Sets the current menu to be drawn"
        self.currentMenu = menu

    def draw_current_menu(self):
        "Draws the current menu"
        title = self.currentMenu.title
        options = self.currentMenu.options

        #draw menu title
        if (pygame.font):
            font = pygame.font.Font(None, self.FONT_SIZE)
        text = font.render(title, 1, (255, 255, 255))
        textpos = text.get_rect(centerx=self.get_screen_center(X=True),
                                centery=self.get_screen_center(Y=True) / 4)
        self.screen.blit(text, textpos)
        #draw menu options
        for i, option in enumerate(options):
            if (pygame.font):
                font = pygame.font.Font(None, self.FONT_SIZE)
            text = font.render(option.text, 1, option.color, option.background)
            xPosition = self.get_screen_center(X=True)
            yPosition = (self.get_screen_center(Y=True) /
                         2) + (self.FONT_SIZE + 10) * i
            option.set_rect(text.get_rect(centerx=xPosition,
                                          centery=yPosition))
            self.screen.blit(text, option.get_rect())

    def event_check(self):
        for e in pygame.event.get():
            if (e.type == pygame.QUIT): self.close()

            if (e.type == pygame.MOUSEBUTTONUP):
                self.check_option_clicked()
            if (e.type == pygame.VIDEORESIZE):
                self.screen = pygame.display.set_mode(e.size, pygame.RESIZABLE)
                self.update()

    def check_option_hover(self):
        "Checks if a menu option is hovered and does a hover effect if true"
        mousePos = pygame.mouse.get_pos()
        for option in self.currentMenu.options:
            if (option.get_rect().collidepoint(mousePos)):
                option.hover(True)
            else:
                option.hover(False)

    def check_option_clicked(self):
        "Checks if a menu option in the currentMenu is clicked and performs action if so"
        mousePos = pygame.mouse.get_pos()
        for option in self.currentMenu.options:
            if (option.get_rect().collidepoint(mousePos)):
                option.action()

    def check_for_winner(self):
        "Checks if there is a winner and sets game state to winner is so"
        for player in self.players:
            if (player.points == Pong.MAX_POINTS):
                self.currentWinner = player
                self.play_sound(Sounds.WIN)
                self.set_game_state_to(GameState.states["WINNER"])

    def update(self):
        "Calls update methods for when window resizes"
        for player in self.players:
            player.update()
        self.ball.update()

    def play_sound(self, sound):
        self.sound.play(self.soundFiles[sound])

    def restart(self):
        "Reset the game points and players"
        for player in self.players:
            player.reset()
        self.ball.reset()
        self.currentWinner = None
        self.set_game_state_to(GameState.states["START"])

    def close(self):
        "Closes application and does cleanup if needed"
        quit()
示例#19
0
class Scene:

    def __init__(self, positions, main):
        self._players = [ Player("Ninja", "ninja", positions[1], self, 0), Player("Pirate", "pirate", positions[0], self, 1) ] 
        self._collision = Collision(self._players[0], self._players[1])
        self._eventOccured = [ False, False ]
        self._soundManager = SoundManager()
        self._elapsedTime = 0;
        self.main = main
    def _decelerate(self, playerIndex, elapsedTime, ratio=1.0):
        player = self._players[playerIndex]
        for i in range(0,2):
            speed = player.speed()[i]
            if speed < epsilon and speed > -epsilon:
                speed = 0
            else:
                if speed > 0:
                    speed -= (acceleration + deceleration) * elapsedTime * ratio
                else:
                    speed += (acceleration + deceleration) * elapsedTime * ratio
            player.setSpeed(speed, i)

    def newFrame(self, elapsedTime):
        for playerIndex in range(0, 2):
            player = self._players[playerIndex]
            if not self._eventOccured[playerIndex]:
                if player.isJumping:
                    ratio = 0.5
                else:
                    ratio = 1.0
                self._decelerate(playerIndex, elapsedTime, ratio)
        self._eventOccured = [ False, False ]
        self._elapsedTime = elapsedTime

        for player in self._players:
            player.update(elapsedTime)
        for playerIndex in range(0, 2):
            self._collision.moveForward(playerIndex, self._players[playerIndex].speed()[0] * self._elapsedTime)
            self._collision.moveSide(playerIndex, self._players[playerIndex].speed()[1] * self._elapsedTime)

    def _move(self, playerIndex, elapsedTime, axe, delta):
        self._eventOccured[playerIndex] = True
        accel = delta * elapsedTime * acceleration
        decel = delta * elapsedTime * deceleration
        self._decelerate(playerIndex, elapsedTime, 0.08)

        consMaxSpeed = maxSpeed

        if axe == 1:
            dist = 0.5 + (self._collision.getDistance() / maxDist) / 2
            consMaxSpeed *= dist
            

        if delta * self._players[playerIndex].speed()[axe] < 0:
            if axe == 0:
                self._players[playerIndex].incrementSpeed(accel + decel, 0)
            else:
                self._players[playerIndex].incrementSpeed(0, decel + accel)
        if delta * self._players[playerIndex].speed()[axe] < consMaxSpeed:
            if axe == 0:
                self._players[playerIndex].incrementSpeed(accel, 0)
            else:
                self._players[playerIndex].incrementSpeed(0, accel)
            if delta * self._players[playerIndex].speed()[axe] > consMaxSpeed:
                self._players[playerIndex].setSpeed(delta * consMaxSpeed, axe)

    def moveForward(self, playerIndex, elapsedTime):
        isJumping = self._players[playerIndex].isJumping()
        if isJumping:
            self._decelerate(playerIndex, elapsedTime, 0.15)
            elapsedTime /= 1.8
        self._move(playerIndex, elapsedTime, 0, 1)

    def moveBackward(self, playerIndex, elapsedTime):
        isJumping = self._players[playerIndex].isJumping()
        if isJumping:
            self._decelerate(playerIndex, elapsedTime, 0.15)
            elapsedTime /= 1.8
        
        self._move(playerIndex, elapsedTime, 0, -1)

    def moveRight(self, playerIndex, elapsedTime):
        isJumping = self._players[playerIndex].isJumping()
        if isJumping:
            self._decelerate(playerIndex, elapsedTime, 0.25)
            elapsedTime /= 2.5
        self._move(playerIndex, elapsedTime, 1, 1)

    def moveLeft(self, playerIndex, elapsedTime):
        isJumping = self._players[playerIndex].isJumping()
        if isJumping:
            self._decelerate(playerIndex, elapsedTime, 0.25)
            elapsedTime /= 2.5
        self._move(playerIndex, elapsedTime, 1, -1)

    def jump(self, playerIndex, elapsedTime):
        self._players[playerIndex].jump(elapsedTime)

    def attack(self, playerIndex, elapsedTime):
        self._players[playerIndex].attack(elapsedTime, self._collision.getDistance())
    
    def getOtherPlayer(self, player):
        if player == self._players[0]:
            return self._players[1]
        else:
            return self._players[0]


    def getPlayer(self, playerId):
        """ retourne le joueur playerId.
            playerId vaut 0 ou 1
        """
        return self._players[playerId]

    def getCollision(self):
        return self._collision
    
    def introEnd(self):
        self._soundManager.introEnd()
    
    def getSoundManager(self):
        return self._soundManager;
示例#20
0



    def on_close(self):
        if self.id not in clients: return
        del clients[self.id]

    def get_buttons(self, device_id):
        return all_buttons[(device_id-1)*BUTTONS_NUM:device_id*BUTTONS_NUM]

app = tornado.web.Application([
    (r'/', IndexHandler),
    (r'/dashboard', DashboardHandler),
    (r'/socket', WebSocketHandler),
    ],
    static_path=os.path.join(os.path.dirname(__file__), "static"),
    autoreload=True,
)

if __name__ == '__main__':
    parse_command_line()
    app.listen(options.port)
    sound_manager = SoundManager()
    sound_manager.daemon = True
    sound_manager.start()
    quest_room = QuestRoom(clients)
    quest_room.sound_manager = sound_manager
    quest_room.start()
    tornado.ioloop.IOLoop.instance().start()
示例#21
0
#                  artist = "hichkas",
#                  genre = "Rap",
#                  duration = 150.5,
#                  url = "https://www.youtube.com/watch?v=4qw3qTV4608")

songs_list = [
    SongModel(id=50,
              name="ye mosht sarbaz",
              artist="hichkas",
              genre="Rap",
              duration=150.5,
              url="https://www.youtube.com/watch?v=4qw3qTV4608"),
    SongModel(id=51,
              name="ye mosht sarbaz",
              artist="ho3ein",
              genre="Rap",
              duration=150.5,
              url="https://www.youtube.com/watch?v=4qw3qTV4608"),
    SongModel(id=52,
              name="ye mosht sarbaz",
              artist="sadegh",
              genre="Rap",
              duration=150.5,
              url="https://www.youtube.com/watch?v=4qw3qTV4608")
]

SoundManager.get_instance().play_songs(songs_list, 1)
SoundManager.get_instance().next_song()
SoundManager.get_instance().previous_song()
SoundManager.get_instance().pause_song()
示例#22
0
import BuzzManager, time
#import QuartzScoreManager
from SoundManager import SoundManager
import sys, time

bm = BuzzManager.BuzzManager()
#qsm = QuartzScoreManager.QuartzScoreManager()
sm = SoundManager()


qs_red   = "1,0.3,0.3,1"
qs_white = "1,1,1,1"
qs_black = "0,0,0,0"

colors = {
  'A Blue': '0,0,1,1',
  'B Orange': '1,0.5,0,1',
  'C Green': '0,1,0,1',
  'D Yellow': '1,1,0,1',
  'RED': '1,0,0,1'
}

"""
for e in  bm.ir.elements[26:len(bm.ir.elements)]:
    print e
    for x in [0,2,4,255]:
        time.sleep(0.5)
        try:
            e.write(x)
            print " - wrote OK"
            sys.exit(0)