Example #1
0
    def on_execute(self):

        if self.on_init() == False:
            self._running = False

        #x = 50
        #y = 50

        #self.spawn_lots()
        #self.spawn_concrete()
        clock = pygame.time.Clock()

        while (self._running):

            #self.orig_surf = self.board.copy()
            #self.new_surf = pygame.surface.Surface()
            first = time.time()

            for event in pygame.event.get():
                self.on_event(event)

            #pygame.draw.rect(self.board, (255, 255, 102), [x, y, 15, 15])

            #Animate the fall for each particle

            #x += 3
            #y += 1

            #time.sleep(0.01)
            self.on_loop()
            self.on_render()
            second = time.time()
            print(second - first)
            clock.tick(60)
    def play(self, media_file, loop=False, vol=0):
        t1 = time.time()
        self.stop(3)  # Up to 3 second delay to let the old player stop.
        logging.debug('Time palyer stoped: {0}'.format(time.time() - t1))

        if media_file.lower().endswith(".jpg") or media_file.lower().endswith(".gif"):
            self._print('Display image: {0}'.format(media_file))
            self._display_image(media_file)
            logging.debug('Time image done: {0}'.format(time.time() - t1))
        else:
            self._print('Display video: {0}'.format(media_file))
            self._display_video(media_file, loop=False, vol=0)
            logging.debug(
                'Time video  displayed: {0}'.format(time.time() - t1))
    def play(self, media_file, loop=False, vol=0):
        t1 = time.time()
        self.stop(3)  # Up to 3 second delay to let the old player stop.
        logging.debug('Time player stoped: {0}'.format(time.time() - t1))

        if media_file.lower().endswith(".jpg") or media_file.lower().endswith(".gif"):
            self._print('Display image: {0}'.format(media_file))
            self._display_image(media_file)
            logging.debug('Time image done: {0}'.format(time.time() - t1))
        else:
            self._print('Display video: {0}'.format(media_file))
            self._display_video(media_file, loop=False, vol=0)
            logging.debug(
                'Time video displayed: {0}'.format(time.time() - t1))
Example #4
0
 def on_mouse_button_down(self, pos, button): 
     if button==3:
         self.blockedkeys=False
     if button==1:
         if self.intervallo_mouse:
             self.mousenow=time.time()
             if 'arco' in self.mag.selezionabili:
                 if self.mag.selezionabili['arco']:
                     utensile=Proiettile(self,pos)
             if 'lasso' in self.mag.selezionabili:
                 if self.mag.selezionabili['lasso']:
                     utensile=Proiettile(self,pos)
             if 'spada' in self.mag.selezionabili:
                 if self.mag.selezionabili['spada']:
                     utensile=UtensileSpada(self,pos)
             if 'piccone' in self.mag.selezionabili:
                 if self.mag.selezionabili['piccone']:
                     utensile=UtensilePiccone(self,pos)
             if 'mappa' in self.mag.selezionabili:
                 if self.mag.selezionabili['mappa']:
                     pgu=PguApp(self,inizio="mappa")
             if 'utensile' in locals():
                 utensile.mostra()
             else:
                 if not 'pgu' in locals():
                     dialog = DialogoAvvisi(testo="Seleziona un'arma o uno strumento da usare! (tasto T) (tasto H)")
Example #5
0
 def __init__(self):
     #Width and Height of pygame window 
     self.screenwidth = 640
     self.screenlength = 640
     #Width and Heigth of paddle
     self.paddlewidth = 10
     self.paddleheight = 100
     #Left paddle initial position co-ordinates
     self.startpaddleleftx= 0
     self.startpaddlelefty= 400
     #Right paddle initial position co-ordinates
     self.startpaddlerightx= 640 - self.paddlewidth
     self.startpaddlerighty= 400
     #Ball initial co-ordinates
     self.ballx = 320
     self.bally = 320
     self.radius = 20
     self.thickness = 0
     #Colors
     self.red = (255,0,0)
     self.blue = (0,0,255)
     self.green = (0,255,0)
     self.clock = pygame.time.Clock()
     self.left_player_score_coord = (0,0)
     self.right_player_score_coord = (480,0)
     self.start_time = time.time()
     self.time_coord = (320,0)
     self.game_over_coord = (320,240)
     self.game_over_time = 60
    def update_inertial_states(self, data):
            #print(current_inertial_states)
            current_inertial_state = data
            quatx, quaty, quatz, quatw = current_inertial_state[15:]
            yaw, pitch, roll = SO3Rotation.quaternion_to_euler_angles((quatw, quatx, quaty, quatz))

            print('GUI State Update!')
            start_time = time.time()
            #print(current_inertial_states, current_inertial_state)
            self.entry_posx.delete(0,tk.END)
            self.entry_posx.insert(0, str(current_inertial_state[0]))
            self.entry_posy.delete(0,tk.END)
            self.entry_posy.insert(0, str(current_inertial_state[1]))
            self.entry_posz.delete(0,tk.END)
            self.entry_posz.insert(0, str(current_inertial_state[2]))
            self.entry_velx.delete(0,tk.END)
            self.entry_velx.insert(0, str(current_inertial_state[3]))
            self.entry_vely.delete(0,tk.END)
            self.entry_vely.insert(0, str(current_inertial_state[4]))
            self.entry_velz.delete(0,tk.END)
            self.entry_velz.insert(0, str(current_inertial_state[5]))
            self.entry_accx.delete(0,tk.END)
            self.entry_accx.insert(0, str(current_inertial_state[6]))
            self.entry_accy.delete(0,tk.END)
            self.entry_accy.insert(0, str(current_inertial_state[7]))
            self.entry_accz.delete(0,tk.END)
            self.entry_accz.insert(0, str(current_inertial_state[8]))
            self.entry_roll.delete(0,tk.END)
            self.entry_roll.insert(0, str(roll))
            self.entry_pitch.delete(0,tk.END)
            self.entry_pitch.insert(0, str(pitch))
            self.entry_yaw.delete(0,tk.END)
            self.entry_yaw.insert(0, str(yaw))
            self.entry_rollrate.delete(0,tk.END)
            self.entry_rollrate.insert(0, str(current_inertial_state[9]))
            self.entry_pitchrate.delete(0,tk.END)
            self.entry_pitchrate.insert(0, str(current_inertial_state[10]))
            self.entry_yawrate.delete(0,tk.END)
            self.entry_yawrate.insert(0, str(current_inertial_state[11]))
            self.entry_angaccx.delete(0,tk.END)
            self.entry_angaccx.insert(0, str(current_inertial_state[12]))
            self.entry_angaccy.delete(0,tk.END)
            self.entry_angaccy.insert(0, str(current_inertial_state[13]))
            self.entry_angaccz.delete(0,tk.END)
            self.entry_angaccz.insert(0, str(current_inertial_state[14]))
            print('GUI State Update Time! ', time.time() - start_time)        
Example #7
0
 def intervallo_mouse(self):
     if not hasattr(self,'mousenow'): return True
     tnow=time.time()
     if tnow>self.mousenow+2:
         self.suono_noncolpito.play()
         return True
     else: 
         self.suono_cilecca.play()
         return False
Example #8
0
def speak(text, lang='en'):
    if spoken:
        a = str(int(time.time()))
        tts = gTTS(text=text, lang=lang)
        tts.save(a + '.mp3')
        mixer.init()
        mixer.music.load(a + '.mp3')
        mixer.music.play()
        while mixer.music.get_busy() == True:
            continue
 def update_inertial_states(self, data):
     #print(current_inertial_states)
     current_inertial_state = data
     print('GUI State Update!')
     start_time = time.time()
     #print(current_inertial_states, current_inertial_state)
     self.entry_posx.delete(0, tk.END)
     self.entry_posx.insert(0, str(current_inertial_state[0]))
     self.entry_posy.delete(0, tk.END)
     self.entry_posy.insert(0, str(current_inertial_state[1]))
     self.entry_posz.delete(0, tk.END)
     self.entry_posz.insert(0, str(current_inertial_state[2]))
     self.entry_velx.delete(0, tk.END)
     self.entry_velx.insert(0, str(current_inertial_state[3]))
     self.entry_vely.delete(0, tk.END)
     self.entry_vely.insert(0, str(current_inertial_state[4]))
     self.entry_velz.delete(0, tk.END)
     self.entry_velz.insert(0, str(current_inertial_state[5]))
     self.entry_accx.delete(0, tk.END)
     self.entry_accx.insert(0, str(current_inertial_state[6]))
     self.entry_accy.delete(0, tk.END)
     self.entry_accy.insert(0, str(current_inertial_state[7]))
     self.entry_accz.delete(0, tk.END)
     self.entry_accz.insert(0, str(current_inertial_state[8]))
     #            self.entry_roll.delete(0,tk.END)
     #            self.entry_roll.insert(0, str(current_inertial_state[9]))
     #            self.entry_pitch.delete(0,tk.END)
     #            self.entry_pitch.insert(0, str(current_inertial_state[10]))
     #            self.entry_yaw.delete(0,tk.END)
     #            self.entry_yaw.insert(0, str(current_inertial_state[11]))
     self.entry_rollrate.delete(0, tk.END)
     self.entry_rollrate.insert(0, str(current_inertial_state[9]))
     self.entry_pitchrate.delete(0, tk.END)
     self.entry_pitchrate.insert(0, str(current_inertial_state[10]))
     self.entry_yawrate.delete(0, tk.END)
     self.entry_yawrate.insert(0, str(current_inertial_state[11]))
     self.entry_angaccx.delete(0, tk.END)
     self.entry_angaccx.insert(0, str(current_inertial_state[12]))
     self.entry_angaccy.delete(0, tk.END)
     self.entry_angaccy.insert(0, str(current_inertial_state[13]))
     self.entry_angaccz.delete(0, tk.END)
     self.entry_angaccz.insert(0, str(current_inertial_state[14]))
     print('GUI State Update Time! ', time.time() - start_time)
Example #10
0
    def eval_result(self, res):
        self.clock_hand.stop()
        
        if not self.state.is_playing():
            return
        
        if not self.answered:
            if res is None:
                self.level.wrong_answer()
                self.shadow_wrong.visible = 1
                self.shadow_wrong.dirty = 1
                self.log_res("NO ANSW ", time.time() - self.clock_hand.init_time)
            elif res:
                self.level.correct_answer()
                self.shadow_correct.visible = 1
                self.shadow_correct.dirty = 1
                self.log_res("CORRECT ", time.time() - self.clock_hand.init_time)

            else: 
                self.level.wrong_answer()
                self.shadow_wrong.visible = 1
                self.shadow_wrong.dirty = 1
                self.log_res("WRONG ", time.time() - self.clock_hand.init_time)

            self.answered = True 
            self.plane_ticks = 0           
        
            self.refresh_game_indicators()
            
        if self.level.is_won():
            print "ganaste"
            self.sprites_group.add(Message("GANASTE", "ESPACIO PARA JUGAR DE NUEVO O ESC PARA SALIR"), layer=MSG_lyr)
            self.state.lost()
            
        if self.level.is_lost():
            print "perdiste"
            if self.level.lost_by_miss():
                self.sprites_group.add(Message("PERDISTE", "ESPACIO PARA JUGAR DE NUEVO O ESC PARA SALIR"), layer=MSG_lyr)
            elif self.level.lost_by_time():
                self.sprites_group.add(Message("TE QUEDASTE SIN TIEMPO", "ESPACIO PARA JUGAR DE NUEVO O ESC PARA SALIR"), layer=MSG_lyr)
            self.state.lost()
    def _display_with_pygame(self, imagefile):
        try:
            t1 = time.time()
            # Clear the screen
            self._blank_screen()
            logging.debug('Time: {0}'.format(time.time() - t1))
            img = image.load(imagefile)
#            img = pygame.image.load(imagefile).convert()
            logging.debug(time.time() - t1)
            img, offset_x, offset_y = self.scale_image(img)
            logging.debug(time.time() - t1)
            self._screen.blit(img, (offset_x, offset_y))
            logging.debug(time.time() - t1)

            # update the display
            display.update()
            logging.debug('Time image displayed: {0}'.format(time.time() - t1))
            ''' fadeIn? from black '''
            # pygame.display.flip()
            # pause
            pygame_time.wait(self._image_display_time * 1000)

            # time.sleep(self._image_display_time)
            ''' fadeOut? to black '''

        except Exception, e:
            logging.error('Error: ' + str(e))
    def _display_with_pygame(self, imagefile):
        try:
            t1 = time.time()
            # Clear the screen
            self._blank_screen()
            logging.debug('Time: {0}'.format(time.time() - t1))
            img = image.load(imagefile)
#            img = pygame.image.load(imagefile).convert()
            logging.debug(time.time() - t1)
            img, offset_x, offset_y = self.scale_image(img)
            logging.debug(time.time() - t1)
            self._screen.blit(img, (offset_x, offset_y))
            logging.debug(time.time() - t1)

            # update the display
            display.update()
            logging.debug('Time image displayed: {0}'.format(time.time() - t1))
            ''' fadeIn? from black '''
            # pygame.display.flip()
            # pause
            pygame_time.wait(self._image_display_time * 1000)

            # time.sleep(self._image_display_time)
            ''' fadeOut? to black '''

        except Exception, e:
            logging.error('Error: ' + str(e))
 def update_image_feeds(self, data):
     scalar = 3
     col_count = 0
     row_count = 0
     
     sim_images = data
     print("GUI Image Update:")
     start_time = time.time()
     
     for key in sim_images:
         if len(sim_images[key][0]) > 0:
             
     
     
     for i in range(self.num_video_feeds):
         sim_image = sim_images[:,:,scalar*i:scalar*(i+1)]
         if scalar == 1:
             sim_image = np.reshape(sim_image, (sim_image.shape[0], sim_image.shape[1]))
         if ((i % 3) == 0):
             col_count = 0
             row_count += 1
         #print('sim image shape ', sim_image.shape, type(sim_image), sim_image, self.isNormal)
         if self.isNormal:
             sim_image = np.array(sim_image * 255, dtype = np.uint8)
         else:
             sim_image = np.array(sim_image, dtype = np.uint8)
         img = Image.fromarray(sim_image)
         imgtk = ImageTk.PhotoImage(image = img)
         if self.VideoFeeds[i] is None: # Initialize the image panel
             self.VideoFeeds[i] = Label(self.VideoFrame, image=imgtk)
             self.VideoFeeds[i].image = imgtk
             self.VideoFeeds[i].grid(row = row_count, column = col_count)
         else:
             self.VideoFeeds[i].configure(image = imgtk)
             self.VideoFeeds[i].image = imgtk
         col_count += 1
     col_count = 0
     row_count = 0
     print("Feed Update Time: ", time.time() - start_time)
 def stop(self, block_timeout_sec=None):
     """Stop the video player.  block_timeout_sec is how many seconds to
     block waiting for the player to stop before moving on.
     """
     t1 = time.time()
     # Stop the player if it's running.
     if self._process is not None and self._process.returncode is None:
         # There are a couple processes used by omxplayer, so kill both
         # with a pkill command.
         # subprocess.call(['pkill', '-9', 'fbi'])
         # subprocess.call(['killall' 'fbi'])
         subprocess.call(['pkill', '-9', 'omxplayer'])
     # If a blocking timeout was specified, wait up to that amount of time
     # for the process to stop.
     start = time.time()
     while self._process is not None and self._process.returncode is None:
         if (time.time() - start) >= block_timeout_sec:
             break
         time.sleep(0)
     # Let the process be garbage collected.
     self._process = None
     # Clear the screen
     self._blank_screen()
 def stop(self, block_timeout_sec=None):
     """Stop the video player.  block_timeout_sec is how many seconds to
     block waiting for the player to stop before moving on.
     """
     t1 = time.time()
     # Stop the player if it's running.
     if self._process is not None and self._process.returncode is None:
         # There are a couple processes used by omxplayer, so kill both
         # with a pkill command.
         # subprocess.call(['pkill', '-9', 'fbi'])
         # subprocess.call(['killall' 'fbi'])
         subprocess.call(['pkill', '-9', 'omxplayer'])
     # If a blocking timeout was specified, wait up to that amount of time
     # for the process to stop.
     start = time.time()
     while self._process is not None and self._process.returncode is None:
         if (time.time() - start) >= block_timeout_sec:
             break
         time.sleep(0)
     # Let the process be garbage collected.
     self._process = None
     # Clear the screen
     self._blank_screen()
Example #16
0
 def start_the_game(self):
     self.welcome_message()
     pygame.init()
     while 1:
         self.refresh_game()
         self.find_helicopter_rocket_collide()
         self.draw_helicopter_in_screen()
         self.helicopter_draw_time -= 1
         pygame.display.flip()
         self.get_kesy_from_player()
         self.move_airplane()
         game_time = time.time()
         if self.time_elapse < self.MAX_ELAPSE:
             self.time_progress(game_time)
         print(self.rocket_velocity, self.time_elapse_set)
Example #17
0
    def eval_result(self, res):
        self.clock_hand.stop()
        current_checkpoint = self.level.checkpoint
        if not self.state.is_playing():
            return

        if not self.answered:
            if res is None:
                self.level.wrong_answer()
                self.log_res("NO ANSW ",
                             time.time() - self.clock_hand.init_time)
            elif res:
                self.level.correct_answer()
                self.log_res("CORRECT ",
                             time.time() - self.clock_hand.init_time)

            else:
                self.level.wrong_answer()
                self.log_res("WRONG ", time.time() - self.clock_hand.init_time)
            self.shadow.visible = 1
            self.shadow.dirty = 1

            self.answered = True
            self.plane_ticks = 0

            self.refresh_game_indicators()

            if (current_checkpoint != self.level.checkpoint
                    and self.level.checkpoint < len(self.level.level_order)):
                self.show_instructions()

        if self.level.is_won():
            print "ganaste"
            self.sprites_group.add(Message("GANASTE", "ESC PARA SALIR"),
                                   layer=MSG_lyr)
            self.state.lost()
Example #18
0
def show_first_card(screen, card_deck, xy_of_card_selected, difficulty):
    """
    makes the first selected card visible

    :param screen: pygame screen
    :param card_deck: string array, cards image paths
    :param xy_of_card_selected: tuple, location of selected card
    :param difficulty: int
    :return: float, current time in seconds
    """
    card_range = 3 + difficulty
    screen.blit(
        card_deck[card_range * xy_of_card_selected[1] +
                  xy_of_card_selected[0]],
        (CARDS_WIDTH * xy_of_card_selected[0],
         SCREEN_INCREASE + CARDS_HEIGHT * xy_of_card_selected[1]))
    return time.time()  # First card has been flipped
Example #19
0
	def drawCharacters(self):  
		self.surfCharacters.fill((10,10,10));
		for player in self.players: 
			if (time.time() - player.lastMoved) > .5:
				self.surfCharacters.blit(self.getTex("entities/player" + player.tex + ".png"), (player.x * 48, player.y * 48))
			else:
				if player.lastX < player.x:
					self.surfCharacters.blit(self.getTex("entities/player" + player.tex + "Right.png"), (player.x * 48, player.y * 48))
				elif player.lastX > player.x:
					self.surfCharacters.blit(self.getTex("entities/player" + player.tex + "Left.png"), (player.x * 48, player.y * 48))
				elif player.lastY < player.y:
					self.surfCharacters.blit(self.getTex("entities/player" + player.tex + ".png"), (player.x * 48, player.y * 48))
				elif player.lastY > player.y:
					self.surfCharacters.blit(self.getTex("entities/player" + player.tex + "Up.png"), (player.x * 48, player.y * 48))
				else:
					self.surfCharacters.blit(self.getTex("entities/player" + player.tex + ".png"), (player.x * 48, player.y * 48))
			 
		self.screen.blit(self.surfCharacters, (self.surfCharactersX, self.surfCharactersY));
Example #20
0
 def __init__(self):
     self.WIDTH = 600
     self.HEIGHT = 800
     self.START_TIME = time.time()
     self.TIME_ELAPSE_INCREASE_SPEED = 25
     self.MAX_ELAPSE = 10
     self.time_elapse = 0
     self.time_elapse_set = set()
     self.rocket_velocity = 10
     self.helicopter_velocity = 1
     self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
     self.keys = [False, False]
     self.air_plane_location_begin = [self.WIDTH//3, self.HEIGHT-150]
     self.rockets_positions = []
     self.helicopter_draw_time = 100
     self.helicopter_elapse_time = 50
     self.helicopter_draw_position = [[100, 20]]
     self.air_plane = pygame.image.load("files/airplane.png")
     self.sky = pygame.image.load("files/sky.gif")
     self.rocket = pygame.image.load("files/bomb.png")
     self.helicopter = pygame.image.load("files/heli.png")
Example #21
0
	def drawHud(self): 
		if self.surfHud.get_alpha() == 0: return;
 		             
		self.surfHud.fill(self.COLOR_TRANSPARENT)        
		pygame.draw.rect(self.surfHud, (22,22,22), (0, 0, 768, 32))

		txtBanner = self.fontDefault.render("Greyvar v0.0", False, (120, 120, 120));
		pos = txtBanner.get_rect();
		pos.x += 4;
		pos.y += 4;
		self.surfHud.blit(txtBanner, pos)

		txtHostname = self.fontDefault.render("Server: " + (self.serverHostname if not self.serverHostname == None else "NOT CONNECTED"), False, (120, 120, 120))
		pos = txtHostname.get_rect();
		pos.x = 320;
		pos.y = 4;
		self.surfHud.blit(txtHostname, pos)
		   
		txt, pos = self.createTextAndPosition("FPS: " + str(int(self.clock.get_fps())), (50, 150, 50), 640, 4)
		self.surfHud.blit(txt, pos);
		 
		now = time.time()
		renderedMessages = 0    
		for timestamp in self.messages.copy(): 
			if (timestamp + self.MESSAGE_DISPLAY_TIME < now): 
				logging.debug("Deleting old message: " + self.messages[timestamp]);
				del self.messages[timestamp]
			else:  
				txtMessage = self.fontDefault.render(self.messages[timestamp], False, (150, 50, 50))
				pos = txtMessage.get_rect()
				pos.x = 20    
				pos.y = 600 - ((len(self.messages) - renderedMessages) * pos.h) 
				self.surfHud.blit(txtMessage, pos) 
				 
				renderedMessages += 1
	 
#		textpos.centerx = self.surfHud.get_rect().centerx
#		self.surfHud.set_colorkey((0,0,0)) 
		self.screen.blit(self.surfHud, (0, 0))
Example #22
0
#Creating left paddle object    
paddleleft = paddle(screen, objhelper.startpaddleleftx, objhelper.startpaddlelefty, objhelper.paddlewidth,
                    objhelper.paddleheight,objhelper.red)

#Creating right paddle object
paddleright = paddle(screen, objhelper.startpaddlerightx, objhelper.startpaddlerighty, objhelper.paddlewidth,
                     objhelper.paddleheight,objhelper.blue)

#Creating a ball
ball_1 = ball(screen,objhelper.ballx, objhelper.bally,objhelper.radius, objhelper.thickness, objhelper.green)

while True:
    #Tell how many frames per second
    objhelper.clock.tick(200)
    time_end = time.time()
    #Refreshes the screen
    pygame.display.update()
    #Fills screen with black each time in while True
    screen.fill((0,0,0))
    #Movement of left paddle
    paddleleft.move(screen)
    #Movement of right paddle
    paddleright.move(screen)
    #Movement of ball
    ball_1.move(screen)
    #Check boundary
    ball_1.checkboundaries(screen)
    #Check right paddle collision 
    paddleright.detectpaddlecollision(screen,ball_1,"right")
    #Check left paddle collision 
Example #23
0
def main(arraytype=None):
    """play various sndarray effects

    If arraytype is provided then use that array package. Valid
    values are 'numeric' or 'numpy'. Otherwise default to NumPy,
    or fall back on Numeric if NumPy is not installed.

    """

    main_dir = os.path.split(os.path.abspath(__file__))[0]

    if arraytype not in ("numpy", None):
        raise ValueError("Array type not supported: %r" % arraytype)

    print("Using %s array package" % sndarray.get_arraytype())
    print("mixer.get_init %s" % (mixer.get_init(),))

    samples_per_second = pygame.mixer.get_init()[0]

    print(("-" * 30) + "\n")
    print("loading sound")
    sound = mixer.Sound(os.path.join(main_dir, "data", "car_door.wav"))

    print("-" * 30)
    print("start positions")
    print("-" * 30)

    start_pos = 0.1
    sound2 = sound_from_pos(sound, start_pos, samples_per_second)

    print("sound.get_length %s" % (sound.get_length(),))
    print("sound2.get_length %s" % (sound2.get_length(),))
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("waiting 2 seconds")
    pygame.time.wait(2000)
    print("playing original sound")

    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("waiting 2 seconds")
    pygame.time.wait(2000)

    # if 0:
    #    #TODO: this is broken.
    #    print (("-" * 30) + "\n")
    #    print ("Slow down the original sound.")
    #    rate = 0.2
    #    slowed_sound = slow_down_sound(sound, rate)
    #    slowed_sound.play()
    #    while mixer.get_busy():
    #        pygame.time.wait(200)

    print("-" * 30)
    print("echoing")
    print("-" * 30)

    t1 = time.time()
    sound2 = make_echo(sound, samples_per_second)
    print("time to make echo %i" % (time.time() - t1,))

    print("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("echoed sound")
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    sound = mixer.Sound(os.path.join(main_dir, "data", "secosmic_lo.wav"))

    t1 = time.time()
    sound3 = make_echo(sound, samples_per_second)
    print("time to make echo %i" % (time.time() - t1,))

    print("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("echoed sound")
    sound3.play()
    while mixer.get_busy():
        pygame.time.wait(200)
Example #24
0
                # utils.show_chord_keys_by_ascii(self.chord_keys_bound)
                (is_beat_at_right_most, current_play_percent,
                 progress_multi_lines, page_end_offset_x) = self.piano.show_notes_staff_in_page(
                     self.enabled_tracks, self.tracks_order_idx,
                     self.notes_in_all_staff, self.last_timestamp,
                     self.staff_top,
                     parse_midi.g_bar_duration,
                     parse_midi.g_time_signature_n,
                     self.staff_offset_x, self.is_pause)

                # scroll page automatically
                if not self.is_pause and is_beat_at_right_most and (current_play_percent == 0 or current_play_percent > (100 - 50 / progress_multi_lines)):
                    self.staff_offset_x = page_end_offset_x

                utils.sync_play_time(self, pitch_timestamp, old_time)
                old_time = time.time()
                self.last_timestamp = pitch_timestamp
                self.chord_keys_bound = []
                self.play_commands = []
                if self.is_pause and self.play_one_timestamp_while_paused:
                    self.play_one_timestamp_while_paused = False
                    continue

            self.play_commands += [(cmd, pitch, volecity)]
            # playtrack
            if cmd == "NOTE_ON":
                # build chord
                if pitch not in self.chord_keys_bound:
                    self.chord_keys_bound += [pitch]

            # show keys
def main():
    pygame.init()
    estado_pj1 = 0
    estado_pj2 = 0
    final_pj1 = 0 #este genera la condicion para que no siga moviendo las animacion y detemina finalmente quien es el personaje a ocupar
    final_pj2 = 0
    v = 0
    w = 4
    n = 35
    time = 75  #milisegundos (en estapa de prueba para decir el mejor tiempo de espera)
    ID_pj1 = 0 #ID pj va de 1-4, representa al personaje para despues cargarlo, esto cuenta el caso random
    ID_pj2 = 0
    screen = pygame.display.set_mode((screen_w,screen_h))
    pygame.display.set_caption("Seleccion de Personaje") #nombre de la ventana
    fondo = pygame.image.load("Screens/imgs/Fondo.jpg").convert()# permite cargar imagenes
    screen.blit(fondo,(0,0))
    pygame.display.flip()
    
    Imagen = {}#bibliotecas con las imagenes
    Imagen[0]=("Screens/imgs/Sel_pj.jpg")
    Imagen[1]=("Screens/imgs/Sel_pj1.jpg")
    Imagen[2]=("Screens/imgs/Sel_pj2.jpg")
    Imagen[3]=("Screens/imgs/Sel_pj1pj2.jpg")
    
    Cuadro = {}
    Cuadro[0]=("Screens/imgs/Fondo_pj0.jpg")
    Cuadro[1]=("Screens/imgs/Fondo_pj1.jpg")
    Cuadro[2]=("Screens/imgs/Fondo_pj2.jpg")
    Cuadro[3]=("Screens/imgs/Fondo_pj3.jpg")
    Cuadro[4]=("Screens/imgs/Fondo_pj4.jpg")

    Tiempo = {}
    Tiempo[0] = pygame.image.load("Screens/imgs/t0.png").convert()
    Tiempo[1] = pygame.image.load("Screens/imgs/t1.png").convert()
    Tiempo[2] = pygame.image.load("Screens/imgs/t2.png").convert()
    Tiempo[3] = pygame.image.load("Screens/imgs/t3.png").convert()
    Tiempo[4] = pygame.image.load("Screens/imgs/t4.png").convert()
    Tiempo[5] = pygame.image.load("Screens/imgs/t5.png").convert()
    Tiempo[6] = pygame.image.load("Screens/imgs/t6.png").convert()
    Tiempo[7] = pygame.image.load("Screens/imgs/t7.png").convert()
    Tiempo[8] = pygame.image.load("Screens/imgs/t8.png").convert()
    Tiempo[9] = pygame.image.load("Screens/imgs/t9.png").convert()

    Reloj = pygame.image.load("Screens/imgs/Reloj.png").convert()
    Fondo_reloj = pygame.image.load("Screens/imgs/Fondo_reloj.jpg").convert()
    reloj = int(time.time())
    while True:         
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if pygame.key.get_pressed()[K_RIGHT]:
                    estado_pj1 = 1
                elif pygame.key.get_pressed()[K_LEFT]:
                    estado_pj1 = 2           
                if pygame.key.get_pressed()[K_d]:
                    estado_pj2 = 1
                elif pygame.key.get_pressed()[K_a]:
                    estado_pj2 = 2
                if pygame.key.get_pressed()[K_RETURN]:
                    final_pj1 = 1
                if pygame.key.get_pressed()[K_BACKSPACE]:
                    final_pj1 = 0
                if pygame.key.get_pressed()[K_SPACE]:
                    final_pj2 = 1
                if pygame.key.get_pressed()[K_TAB]:
                    final_pj2 = 0
                if pygame.key.get_pressed()[K_ESCAPE]:
                    pygame.quit()
                    sys.exit()

            elif event.type == KEYUP:
                if estado_pj1 == 1 or 2:
                    estado_pj1 = 0
                    
                if estado_pj2 == 1 or 2:
                    estado_pj2 = 0
                
        if not final_pj1 == 1: 
            if estado_pj1 == 1:
                v += 1
                ID_pj1 += 1
                if v == 5:
                    v = 0
                if ID_pj1 == 5:
                    ID_pj1 = 0
            if estado_pj1 == 2:
                v -= 1
                ID_pj1 -= 1
                if v == -1:
                    v = 4
                if ID_pj1 == -1:
                    ID_pj1 = 4
                    
        if not final_pj2 == 1:
            if estado_pj2 == 1:
                w += 1
                ID_pj2 += 1
                if w == 5:
                    w = 0
                if ID_pj2 == 5:
                    ID_pj2 = 0
            if estado_pj2 == 2:
                w -= 1
                ID_pj2 -= 1
                if w == -1:
                    w = 4
                if ID_pj2 == -1:
                    ID_pj2 = 4            
        a=0
        b=0
        c=0
        d=0
        e=0
        x=(0,1,2,3,4)  #casos que corresponden para poder actualizar las imagenes de los cuadros de los personajes ha seleccionar + una lista auxiliar :)
        if ID_pj1==0:
            a=1          
        if ID_pj1==1:
            b=1            
        if ID_pj1==2:
            c=1           
        if ID_pj1==3:
            d=1          
        if ID_pj1==4:
            e=1        
        if ID_pj2==0:
            a=2
        if ID_pj2==1:
            b=2          
        if ID_pj2==2:
            c=2          
        if ID_pj2==3:
            d=2         
        if ID_pj2==4:
            e=2
        if ID_pj1==ID_pj2:
            X=x[ID_pj1]
            if X==0:
                a=3
            if X==1:
                b=3
            if X==2:
                c=3
            if X==3:
                d=3
            if X==4:
                e=3
       
        Bloque = {} #las imagenes de los cuadros de personajes se tienen que resetear cada vez que se cambia la posicion para que se pueda actualizar la imagen a mostrar
        Bloque[0]=pygame.image.load(Imagen[a]).convert()
        Bloque[1]=pygame.image.load(Imagen[b]).convert()
        Bloque[2]=pygame.image.load(Imagen[c]).convert()
        Bloque[3]=pygame.image.load(Imagen[d]).convert()
        Bloque[4]=pygame.image.load(Imagen[e]).convert()
        
        cuadro1 = pygame.image.load(Cuadro[v]).convert()
        cuadro2 = pygame.image.load(Cuadro[w]).convert()
        screen.blit(cuadro1,(50,40))
        screen.blit(cuadro2,(718,40))
            
        screen.blit(Bloque[0],(30,510))
        screen.blit(Bloque[1],(234,580))
        screen.blit(Bloque[2],(435,620))
        screen.blit(Bloque[3],(640,580))
        screen.blit(Bloque[4],(845,510))       
        pygame.display.flip()
        pygame.time.wait(time)
        

        if final_pj1 == 1  and final_pj2 == 1:                ##Observacion## (Estas corresponden a los numeros asigados a ellos para que el nucleo, sepa cual cargar)
            if ID_pj1 == 2:                                     #1-Musician    
                while not ID_pj1 == 2:                          #2-Medic
                    ID_pj1 = random.randint(0,4)                #3-Enginner
            if ID_pj2 == 2:                                     #4-Psyco
                while not ID_pj2 == 2:
                    ID_pj2 = random.randint(0,4)
            if ID_pj1 == 0:
                ID_pj1 = 1
            if ID_pj1 == 1:
                ID_pj1 = 2
            if ID_pj2 == 0:
                ID_pj2 = 1
            if ID_pj2 == 1:
                ID_pj2 = 2

            return ID_pj1,ID_pj2
                    

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
Example #26
0
def main(*args):
    """Display multiple images bounce off each other using collition detection

    Positional arguments:
      one or more image file names.

    This pygame.masks demo will display multiple moving sprites bouncing
    off each other. More than one sprite image can be provided.

    """
    
    if len(args) == 0:
        raise ValueError("Require at least one image file name: non given")
    print ('Press any key to quit')
    screen = pygame.display.set_mode((640,480))
    images = []
    masks = []
    for impath in args:
        images.append(pygame.image.load(impath).convert_alpha())
        masks.append(maskFromSurface(images[-1]))

    numtimes = 10
    import time
    t1 = time.time()
    for x in range(numtimes):
        m = maskFromSurface(images[-1])
    t2 = time.time()

    print ("python maskFromSurface :%s" % (t2-t1))

    t1 = time.time()
    for x in range(numtimes):
        m = pygame.mask.from_surface(images[-1])
    t2 = time.time()

    print ("C pygame.mask.from_surface :%s" % (t2-t1))

    sprites = []
    for i in range(20):
        j = i % len(images)
        s = Sprite(images[j],masks[j])
        s.setPos((random.uniform(0,screen.get_width()),
                  random.uniform(0,screen.get_height())))
        s.setVelocity((random.uniform(-5,5),random.uniform(-5,5)))
        sprites.append(s)
    pygame.time.set_timer(pygame.USEREVENT,33)
    while 1:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:
            return
        elif event.type == pygame.USEREVENT:
            """Do both mechanics and screen update"""
            screen.fill((240,220,100))
            for i in range(len(sprites)):
                for j in range(i+1,len(sprites)):
                    sprites[i].collide(sprites[j])
            for s in sprites:
                s.update(1)
                if s.pos[0] < -s.surface.get_width()-3:
                    s.pos[0] = screen.get_width()
                elif s.pos[0] > screen.get_width()+3:
                    s.pos[0] = -s.surface.get_width()
                if s.pos[1] < -s.surface.get_height()-3:
                    s.pos[1] = screen.get_height()
                elif s.pos[1] > screen.get_height()+3:
                    s.pos[1] = -s.surface.get_height()
                screen.blit(s.surface,s.pos)
            pygame.display.update()
        elif event.type == pygame.KEYDOWN:
            return
Example #27
0
def main(arraytype=None):
    """play various sndarray effects

    If arraytype is provided then use that array package. Valid
    values are 'numeric' or 'numpy'. Otherwise default to NumPy,
    or fall back on Numeric if NumPy is not installed.

    """

    global zeros, int16, int32

    main_dir = os.path.split(os.path.abspath(__file__))[0]

    if arraytype is None:
        if 'numpy' in sndarray.get_arraytypes():
            sndarray.use_arraytype('numpy')
        elif 'numeric' in sndarray.get_arraytype():
            sndarray.use_arraytype('numeric')
        else:
            raise ImportError('No array package is installed')
    else:
        sndarray.use_arraytype(arraytype)
    pygame.surfarray.use_arraytype(sndarray.get_arraytype())

    if sndarray.get_arraytype() == 'numpy':
        from numpy import zeros, int16, int32
    else:
        from Numeric import zeros, Int16 as int16, Int32 as int32

    print("Using %s array package" % sndarray.get_arraytype())
    print("mixer.get_init %s" % (mixer.get_init(), ))
    inited = mixer.get_init()

    samples_per_second = pygame.mixer.get_init()[0]

    print(("-" * 30) + "\n")
    print("loading sound")
    sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav'))

    print("-" * 30)
    print("start positions")
    print("-" * 30)

    start_pos = 0.1
    sound2 = sound_from_pos(sound, start_pos, samples_per_second)

    print("sound.get_length %s" % (sound.get_length(), ))
    print("sound2.get_length %s" % (sound2.get_length(), ))
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("waiting 2 seconds")
    pygame.time.wait(2000)
    print("playing original sound")

    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("waiting 2 seconds")
    pygame.time.wait(2000)

    if 0:
        #TODO: this is broken.
        print(("-" * 30) + "\n")
        print("Slow down the original sound.")
        rate = 0.2
        slowed_sound = slow_down_sound(sound, rate)

        slowed_sound.play()
        while mixer.get_busy():
            pygame.time.wait(200)

    print("-" * 30)
    print("echoing")
    print("-" * 30)

    t1 = time.time()
    sound2 = make_echo(sound, samples_per_second)
    print("time to make echo %i" % (time.time() - t1, ))

    print("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("echoed sound")
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav'))

    t1 = time.time()
    sound3 = make_echo(sound, samples_per_second)
    print("time to make echo %i" % (time.time() - t1, ))

    print("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print("echoed sound")
    sound3.play()
    while mixer.get_busy():
        pygame.time.wait(200)
Example #28
0
	def addMessage(self, message):  
		self.messages[time.time()] = message;
def main(arraytype=None):
    """play various sndarray effects

    If arraytype is provided then use that array package. Valid
    values are 'numeric' or 'numpy'. Otherwise default to NumPy,
    or fall back on Numeric if NumPy is not installed.

    """

    main_dir = os.path.split(os.path.abspath(__file__))[0]

    if arraytype not in ('numpy', None):
        raise ValueError('Array type not supported: %r' % arraytype)

    print ("Using %s array package" % sndarray.get_arraytype())
    print ("mixer.get_init %s" % (mixer.get_init(),))
    inited = mixer.get_init()

    samples_per_second = pygame.mixer.get_init()[0]

    

    print (("-" * 30) + "\n")
    print ("loading sound")
    sound = mixer.Sound(os.path.join(main_dir, 'data', 'car_door.wav'))



    print ("-" * 30)
    print ("start positions")
    print ("-" * 30)

    start_pos = 0.1
    sound2 = sound_from_pos(sound, start_pos, samples_per_second)

    print ("sound.get_length %s" % (sound.get_length(),))
    print ("sound2.get_length %s" % (sound2.get_length(),))
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print ("waiting 2 seconds")
    pygame.time.wait(2000)
    print ("playing original sound")

    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print ("waiting 2 seconds")
    pygame.time.wait(2000)



    if 0:
        #TODO: this is broken.
        print (("-" * 30) + "\n")
        print ("Slow down the original sound.")
        rate = 0.2
        slowed_sound = slow_down_sound(sound, rate)

        slowed_sound.play()
        while mixer.get_busy():
            pygame.time.wait(200)


    print ("-" * 30)
    print ("echoing")
    print ("-" * 30)

    t1 = time.time()
    sound2 = make_echo(sound, samples_per_second)
    print ("time to make echo %i" % (time.time() - t1,))


    print ("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)

    print ("echoed sound")
    sound2.play()
    while mixer.get_busy():
        pygame.time.wait(200)


    sound = mixer.Sound(os.path.join(main_dir, 'data', 'secosmic_lo.wav'))

    t1 = time.time()
    sound3 = make_echo(sound, samples_per_second)
    print ("time to make echo %i" % (time.time() - t1,))

    print ("original sound")
    sound.play()
    while mixer.get_busy():
        pygame.time.wait(200)


    print ("echoed sound")
    sound3.play()
    while mixer.get_busy():
        pygame.time.wait(200)
def main():
    pygame.init()
    estado_pj1 = 0
    estado_pj2 = 0
    final_pj1 = 0  #este genera la condicion para que no siga moviendo las animacion y detemina finalmente quien es el personaje a ocupar
    final_pj2 = 0
    v = 0
    w = 4
    n = 35
    time = 75  #milisegundos (en estapa de prueba para decir el mejor tiempo de espera)
    ID_pj1 = 0  #ID pj va de 1-4, representa al personaje para despues cargarlo, esto cuenta el caso random
    ID_pj2 = 0
    screen = pygame.display.set_mode((screen_w, screen_h))
    pygame.display.set_caption("Seleccion de Personaje")  #nombre de la ventana
    fondo = pygame.image.load(
        "Screens/imgs/Fondo.jpg").convert()  # permite cargar imagenes
    screen.blit(fondo, (0, 0))
    pygame.display.flip()

    Imagen = {}  #bibliotecas con las imagenes
    Imagen[0] = ("Screens/imgs/Sel_pj.jpg")
    Imagen[1] = ("Screens/imgs/Sel_pj1.jpg")
    Imagen[2] = ("Screens/imgs/Sel_pj2.jpg")
    Imagen[3] = ("Screens/imgs/Sel_pj1pj2.jpg")

    Cuadro = {}
    Cuadro[0] = ("Screens/imgs/Fondo_pj0.jpg")
    Cuadro[1] = ("Screens/imgs/Fondo_pj1.jpg")
    Cuadro[2] = ("Screens/imgs/Fondo_pj2.jpg")
    Cuadro[3] = ("Screens/imgs/Fondo_pj3.jpg")
    Cuadro[4] = ("Screens/imgs/Fondo_pj4.jpg")

    Tiempo = {}
    Tiempo[0] = pygame.image.load("Screens/imgs/t0.png").convert()
    Tiempo[1] = pygame.image.load("Screens/imgs/t1.png").convert()
    Tiempo[2] = pygame.image.load("Screens/imgs/t2.png").convert()
    Tiempo[3] = pygame.image.load("Screens/imgs/t3.png").convert()
    Tiempo[4] = pygame.image.load("Screens/imgs/t4.png").convert()
    Tiempo[5] = pygame.image.load("Screens/imgs/t5.png").convert()
    Tiempo[6] = pygame.image.load("Screens/imgs/t6.png").convert()
    Tiempo[7] = pygame.image.load("Screens/imgs/t7.png").convert()
    Tiempo[8] = pygame.image.load("Screens/imgs/t8.png").convert()
    Tiempo[9] = pygame.image.load("Screens/imgs/t9.png").convert()

    Reloj = pygame.image.load("Screens/imgs/Reloj.png").convert()
    Fondo_reloj = pygame.image.load("Screens/imgs/Fondo_reloj.jpg").convert()
    reloj = int(time.time())
    while True:
        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if pygame.key.get_pressed()[K_RIGHT]:
                    estado_pj1 = 1
                elif pygame.key.get_pressed()[K_LEFT]:
                    estado_pj1 = 2
                if pygame.key.get_pressed()[K_d]:
                    estado_pj2 = 1
                elif pygame.key.get_pressed()[K_a]:
                    estado_pj2 = 2
                if pygame.key.get_pressed()[K_RETURN]:
                    final_pj1 = 1
                if pygame.key.get_pressed()[K_BACKSPACE]:
                    final_pj1 = 0
                if pygame.key.get_pressed()[K_SPACE]:
                    final_pj2 = 1
                if pygame.key.get_pressed()[K_TAB]:
                    final_pj2 = 0
                if pygame.key.get_pressed()[K_ESCAPE]:
                    pygame.quit()
                    sys.exit()

            elif event.type == KEYUP:
                if estado_pj1 == 1 or 2:
                    estado_pj1 = 0

                if estado_pj2 == 1 or 2:
                    estado_pj2 = 0

        if not final_pj1 == 1:
            if estado_pj1 == 1:
                v += 1
                ID_pj1 += 1
                if v == 5:
                    v = 0
                if ID_pj1 == 5:
                    ID_pj1 = 0
            if estado_pj1 == 2:
                v -= 1
                ID_pj1 -= 1
                if v == -1:
                    v = 4
                if ID_pj1 == -1:
                    ID_pj1 = 4

        if not final_pj2 == 1:
            if estado_pj2 == 1:
                w += 1
                ID_pj2 += 1
                if w == 5:
                    w = 0
                if ID_pj2 == 5:
                    ID_pj2 = 0
            if estado_pj2 == 2:
                w -= 1
                ID_pj2 -= 1
                if w == -1:
                    w = 4
                if ID_pj2 == -1:
                    ID_pj2 = 4
        a = 0
        b = 0
        c = 0
        d = 0
        e = 0
        x = (
            0, 1, 2, 3, 4
        )  #casos que corresponden para poder actualizar las imagenes de los cuadros de los personajes ha seleccionar + una lista auxiliar :)
        if ID_pj1 == 0:
            a = 1
        if ID_pj1 == 1:
            b = 1
        if ID_pj1 == 2:
            c = 1
        if ID_pj1 == 3:
            d = 1
        if ID_pj1 == 4:
            e = 1
        if ID_pj2 == 0:
            a = 2
        if ID_pj2 == 1:
            b = 2
        if ID_pj2 == 2:
            c = 2
        if ID_pj2 == 3:
            d = 2
        if ID_pj2 == 4:
            e = 2
        if ID_pj1 == ID_pj2:
            X = x[ID_pj1]
            if X == 0:
                a = 3
            if X == 1:
                b = 3
            if X == 2:
                c = 3
            if X == 3:
                d = 3
            if X == 4:
                e = 3

        Bloque = {
        }  #las imagenes de los cuadros de personajes se tienen que resetear cada vez que se cambia la posicion para que se pueda actualizar la imagen a mostrar
        Bloque[0] = pygame.image.load(Imagen[a]).convert()
        Bloque[1] = pygame.image.load(Imagen[b]).convert()
        Bloque[2] = pygame.image.load(Imagen[c]).convert()
        Bloque[3] = pygame.image.load(Imagen[d]).convert()
        Bloque[4] = pygame.image.load(Imagen[e]).convert()

        cuadro1 = pygame.image.load(Cuadro[v]).convert()
        cuadro2 = pygame.image.load(Cuadro[w]).convert()
        screen.blit(cuadro1, (50, 40))
        screen.blit(cuadro2, (718, 40))

        screen.blit(Bloque[0], (30, 510))
        screen.blit(Bloque[1], (234, 580))
        screen.blit(Bloque[2], (435, 620))
        screen.blit(Bloque[3], (640, 580))
        screen.blit(Bloque[4], (845, 510))
        pygame.display.flip()
        pygame.time.wait(time)

        if final_pj1 == 1 and final_pj2 == 1:  ##Observacion## (Estas corresponden a los numeros asigados a ellos para que el nucleo, sepa cual cargar)
            if ID_pj1 == 2:  #1-Musician
                while not ID_pj1 == 2:  #2-Medic
                    ID_pj1 = random.randint(0, 4)  #3-Enginner
            if ID_pj2 == 2:  #4-Psyco
                while not ID_pj2 == 2:
                    ID_pj2 = random.randint(0, 4)
            if ID_pj1 == 0:
                ID_pj1 = 1
            if ID_pj1 == 1:
                ID_pj1 = 2
            if ID_pj2 == 0:
                ID_pj2 = 1
            if ID_pj2 == 1:
                ID_pj2 = 2

            return ID_pj1, ID_pj2

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
Example #31
0
def main(*args):
    """Display multiple images bounce off each other using collition detection

    Positional arguments:
      one or more image file names.

    This pygame.masks demo will display multiple moving sprites bouncing
    off each other. More than one sprite image can be provided.

    """

    if len(args) == 0:
        raise ValueError("Require at least one image file name: non given")
    print('Press any key to quit')
    screen = pygame.display.set_mode((640, 480))
    images = []
    masks = []
    for impath in args:
        images.append(pygame.image.load(impath).convert_alpha())
        masks.append(maskFromSurface(images[-1]))

    numtimes = 10
    import time
    t1 = time.time()
    for x in range(numtimes):
        m = maskFromSurface(images[-1])
    t2 = time.time()

    print("python maskFromSurface :%s" % (t2 - t1))

    t1 = time.time()
    for x in range(numtimes):
        m = pygame.mask.from_surface(images[-1])
    t2 = time.time()

    print("C pygame.mask.from_surface :%s" % (t2 - t1))

    sprites = []
    for i in range(20):
        j = i % len(images)
        s = Sprite(images[j], masks[j])
        s.setPos((random.uniform(0, screen.get_width()),
                  random.uniform(0, screen.get_height())))
        s.setVelocity((random.uniform(-5, 5), random.uniform(-5, 5)))
        sprites.append(s)
    pygame.time.set_timer(pygame.USEREVENT, 33)
    while 1:
        event = pygame.event.wait()
        if event.type == pygame.QUIT:
            return
        elif event.type == pygame.USEREVENT:
            """Do both mechanics and screen update"""
            screen.fill((240, 220, 100))
            for i in range(len(sprites)):
                for j in range(i + 1, len(sprites)):
                    sprites[i].collide(sprites[j])
            for s in sprites:
                s.update(1)
                if s.pos[0] < -s.surface.get_width() - 3:
                    s.pos[0] = screen.get_width()
                elif s.pos[0] > screen.get_width() + 3:
                    s.pos[0] = -s.surface.get_width()
                if s.pos[1] < -s.surface.get_height() - 3:
                    s.pos[1] = screen.get_height()
                elif s.pos[1] > screen.get_height() + 3:
                    s.pos[1] = -s.surface.get_height()
                screen.blit(s.surface, s.pos)
            pygame.display.update()
        elif event.type == pygame.KEYDOWN:
            return