예제 #1
0
def scheduler_loop(timestamp_dictionary, stack):
    global now
    while active:        
        now = pgtime.get_ticks()
        # now schedule pending events ... thus we're having a fixed point of time ('now')
        while len(stack) > 0:
            delayed_event = stack.pop()
            # correct future time if wait was not precise
            future_time = delayed_event[1]                               
            if future_time not in timestamp_dictionary:
                timestamp_dictionary[future_time] = {}
            # get objects uuid
            key = delayed_event[0]
            # store function to be scheduled under the object uuid (necessary for cleaning) 
            timestamp_dictionary[future_time][key] = delayed_event[2]
        # after everything has been said and done, check if there's any garbage left ...
        time_points = timestamp_dictionary.keys()
        past_time_points = [x for x in time_points if x < now]
        for time_point in past_time_points:                    
            #print(str(len(timestamp_dictionary[past])) + " EVENTS at " + str(past))
            for past_event in timestamp_dictionary[time_point]:                
                try:                    
                    async = threading.Thread(target=timestamp_dictionary[time_point][past_event], args=(time_point, now))
                    async.start()
                except Exception as e:
                    print(e) 
                    raise e
            del timestamp_dictionary[time_point]            
            # wait one microsecond              
        pgtime.wait(1) 
예제 #2
0
def ledoff():
    print("LED OFF")
    uff = requests.get(
        "http://10.0.1.73:8087/set/wled.0.483fda499ffa.on?value=false")
    lp.LedCtrlRaw(206, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(206, 0, 3)
예제 #3
0
파일: np_client.py 프로젝트: oncer/netproto
    def authenticate(self):
        """ call this before opening the game
        gets the current tick from the server
        and synchronizes the game state """

        def threaded_recv(retlist):
            response, addr = self.client.recv()
            retlist.append(response)

        pkg_request = Packet(0)
        self.client.send(pkg_request)
        retlist = []
        t = Thread(target=lambda: threaded_recv(retlist))
        t.daemon = True
        t.start()
        wait_start = time.get_ticks()
        wait_end = wait_start + 1000
        while len(retlist) <= 0 and time.get_ticks() < wait_end:
            time.wait(1)

        if len(retlist) > 0:
            response = retlist[0]
            pkg_response = Packet.unpack(response)
            self.start_tick = pkg_response.tick
            if len(pkg_response.players) <= 0:
                raise RuntimeError("Invalid response: %s" % pkg_response)
            self.id = pkg_response.players[0][0]
            self.set_state(pkg_response, backtrack=False)
        else:
            raise RuntimeError("Server not responding")
예제 #4
0
def stopTripod(t, turnAngle=0, back=False, duty_turn=0):
    """ Adds an ending point to the tripod gait and returns to a
	    standing position. """

    xjusAnalysis.endAccel(PLOT_ANALYSIS)
    xjusAnalysis.endAvgVelocity()
    #acc = xjusAnalysis.getAvgAbsZAccel()
    #print("===============================================")
    #print("Stability measure: %.4f" % (acc))
    current = xjusAnalysis.getAvgCurrent()
    #print("Power usage measure: %.4f" % (current))
    #print("===============================================")

    pytime.wait(DT)
    for node in nodes:
        [nA, pA, vA, tA] = addTripodPoint(t,
                                          turnAngle,
                                          back=back,
                                          end=True,
                                          duty_turn=duty_turn)
        addPvtArray(nA, pA, vA, tA)

    for node in nodes:
        xjus.stopIPM(node)
        xjus.printIpmStatus(node)

    wait()

    returnToStand()
예제 #5
0
def nice():
    z = 0
    while z < 1200:
        time.wait(random.randint(0, 30))
        lp.LedCtrlRaw(random.randint(0, 127), random.randint(0, 3),
                      random.randint(0, 3))
        z = z + 1
예제 #6
0
def main(file_path=None):
    """Play an audio file as a buffered sound sample

    Option argument:
        the name of an audio file (default data/secosmic_low.wav

    """
    if file_path is None:
        file_path = os.path.join(main_dir, 'data', 'secosmic_lo.wav')

    #choose a desired audio format
    mixer.init(11025)  #raises exception on fail

    #load the sound
    sound = mixer.Sound(file_path)

    #start playing
    print('Playing Sound...')
    channel = sound.play()

    #poll until finished
    while channel.get_busy():  #still playing
        print('  ...still going...')
        time.wait(1000)
    print('...Finished')
예제 #7
0
파일: conwaysa.py 프로젝트: pez2001/Stuff
def setup():
	random.seed()
	mixer.init()
	#screen = pygame.display.set_mode ((640, 480), 0, 32)
	samples = get_samples("./samples")
	init_playfield(samples)
	tick()
	print_playfield()
	pygame.init ()
	#screen.fill ((100, 100, 100))
	#pygame.display.flip ()
	#pygame.key.set_repeat (500, 30)
	#mixer.init(11025)
	#mixer.init(44100)
	#sample = samples[random.randint(0,len(samples)-1)]
	#print("playing sample:",sample)
	#sound = mixer.Sound(sample)
	#channel = sound.play()

	while True:
		play_sounds()
		#for i in range(2):	
		mutate_playfield()
		tick()
		print_playfield()
		#time.wait(int((1000*60)/80)) # 128bpm
		time.wait(50)

	#while channel.get_busy(): #still playing
	#	print("  ...still going...")
	#	time.wait(1000)
	#print("...Finished")
	pygame.quit()
예제 #8
0
파일: np_server.py 프로젝트: oncer/netproto
    def run(self):
        self.net_tick = 0
        self.clients = {}
        self.lock = Lock()
        self.server = UdpServer(25000)

        self.socket_thread = SocketThread(self)
        self.socket_thread.start()

        print "Server up and running."

        self.input_thread = InputThread(self)
        self.input_thread.start()

        ticks_start = time.get_ticks()
        while not self.quit:
            ticks = time.get_ticks() - ticks_start - self.net_tick * FRAMETIME
            update_count = ticks / FRAMETIME
            with self.lock:
                for i in xrange(update_count):
                    self.update()
                    self.send_new_state()
                    dead_clients = []
                    for addr, client in self.clients.items():
                        client.countdown()
                        if client.is_dead():
                            dead_clients.append(addr)
                    for addr in dead_clients:
                        print "removing client %s (timeout)" % str(addr)
                        del self.clients[addr]
            time.wait(1)
예제 #9
0
def normal():
    print("Wled normal")
    uff = requests.get(
        "http://10.0.1.73:8087/set/wled.0.483fda499ffa.seg.0.fx?value=0")
    lp.LedCtrlRaw(204, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(204, 0, 3)
예제 #10
0
def ledctrlfn(dev, list, buffer_time_lists, buffer_time_numbers, red, green):
    from pygame import time
    for i in list:
        dev.LedCtrlRaw(i, red, green)
        print(i)
        time.wait(buffer_time_numbers)
        dev.Reset()
예제 #11
0
def stop():
    print("stop")
    uff = requests.get(
        "http://10.0.1.73:8087/set/hm-rega.0.4180.ProgramExecute?value=true")
    lp.LedCtrlRaw(0, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(0, 0, 3)
예제 #12
0
def stopTripod(t, turnAngle=0, back=False, duty_turn=0):
	""" Adds an ending point to the tripod gait and returns to a
	    standing position. """

	xjusAnalysis.endAccel(PLOT_ANALYSIS)
	xjusAnalysis.endAvgVelocity()
	#acc = xjusAnalysis.getAvgAbsZAccel()
	#print("===============================================")
	#print("Stability measure: %.4f" % (acc))
	current = xjusAnalysis.getAvgCurrent()
	#print("Power usage measure: %.4f" % (current))
	#print("===============================================")
	
	pytime.wait(DT)
	for node in nodes:
		[nA, pA, vA, tA] = addTripodPoint(t, turnAngle, back=back, end=True, duty_turn=duty_turn)
		addPvtArray(nA, pA, vA, tA)

	for node in nodes:
		xjus.stopIPM(node)
		xjus.printIpmStatus(node)

	wait()

	returnToStand()
예제 #13
0
def main():

    LP = launchpad.Launchpad(
    )  # creates a Launchpad instance (first Launchpad found)
    LP.Open()  # start it

    LP.LedCtrlString('HELLO   ', 0, 3, -1)  # scroll "HELLO" from right to left

    # random output until button "arm" (lower right) is pressed
    print("---\nRandom madness. Stop by hitting the ARM button (lower right)")
    print("Remember the PyGame MIDI bug:")
    print("If the ARM button has no effect, hit an automap button (top row)")
    print("and try again...")

    while 1:
        LP.LedCtrlRaw(random.randint(0, 127), random.randint(0, 3),
                      random.randint(0, 3))
        time.wait(5)
        but = LP.ButtonStateRaw()
        if but != []:
            print(but)
            if but[0] == 120:
                break

    LP.Reset()  # turn all LEDs off
    LP.Close()  # close the Launchpad
예제 #14
0
 def draw_initial_chips(self, chip_array):
     for row in reversed(range(len(chip_array))):
         for col in range(len(chip_array)):
             time.wait(7)
             chip_array[row][col].update(self.__display.get_display())
             pygame.display.update()
     self.update_effects()
예제 #15
0
파일: fps.py 프로젝트: HieuLsw/sbfury
    def update(self):
        
        self.tick = get_ticks()
        delta = self.tick - self.last_tick

        if self.slow_motion_delay > 0:
            self.slow_motion_delay -= 1

            if self.slow_motion_delay <= 0:
                self.frecuency = self.normal_frecuency


        if delta > self.frecuency:
            skips = delta / self.frecuency

            if skips > self.maxframeskip:
                skips = self.maxframeskip
                self.last_tick = self.tick
            else:
                self.last_tick += skips * self.frecuency

            self._update_status()
            return skips
        else:
            wait(1)
            return 0
예제 #16
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

    ball_image_path = os.path.join(IMAGES_DIR_PATH, "ball.png")
    ball_img = pygame.image.load(ball_image_path).convert_alpha()
    ball_rect = ball_img.get_rect()
    ball_rect.centery = SCREEN_HEIGHT / 2
    ball_rect.centerx = SCREEN_WIDTH / 2

    paddle_image_path = os.path.join(IMAGES_DIR_PATH, "paddle.png")
    paddle_img = pygame.image.load(paddle_image_path).convert_alpha()
    paddle_rect = paddle_img.get_rect()
    paddle_rect.centery = SCREEN_HEIGHT / 2

    paddle_img_2 = paddle_img.copy()
    paddle_rect_2 = paddle_img_2.get_rect()
    paddle_rect_2.right = SCREEN_WIDTH
    paddle_rect_2.centery = SCREEN_HEIGHT / 2

    background_image_path = os.path.join(IMAGES_DIR_PATH, "background.jpg")
    background = pygame.image.load(background_image_path)

    move_x = RECT_STEP
    move_y = 0
    while True:
        screen.blit(background, (0, 0))
        screen.blit(ball_img, ball_rect)
        screen.blit(paddle_img, paddle_rect)
        screen.blit(paddle_img_2, paddle_rect_2)

        ball_rect.move_ip(move_x, move_y)

        pygame.display.flip()
        wait(TIME)
예제 #17
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    ball_image_path = os.path.join(IMAGES_DIR_PATH, "ball.png")
    ball_img = pygame.image.load(ball_image_path).convert_alpha()
    ball_rect = ball_img.get_rect()

    paddle_image_path = os.path.join(IMAGES_DIR_PATH, "paddle.png")
    paddle_img = pygame.image.load(paddle_image_path).convert_alpha()
    paddle_rect = paddle_img.get_rect()

    background_image_path = os.path.join(IMAGES_DIR_PATH, "background.jpg")
    background = pygame.image.load(background_image_path)

    move_x = RECT_STEP
    move_y = 0
    while True:
        screen.blit(background, (0, 0))
        screen.blit(ball_img, ball_rect)
        screen.blit(paddle_img, paddle_rect)
        wall = draw_wall(100, 300, 0, True, RECT_COLOR, screen)

        if strike(ball_rect, wall):
            move_x = -RECT_STEP
            move_y = RECT_STEP

        ball_rect.move_ip(move_x, move_y)

        pygame.display.flip()
        wait(TIME)
예제 #18
0
def ledctrlc(dev, list, buffer_time_lists, buffer_time_numbers):
    from pygame import time
    franum_total = 0
    for frame in list:
        franum_total += 1
    franum = 1
    print("#####ANIMATION START#####")
    for frame in list:
        colnum = 1
        print("+++++FRAME " + str(franum) + " / " + str(franum_total) +
              " +++++")
        for color in frame:
            for i in color:
                if colnum == 1:
                    dev.LedCtrlRaw(i, 3, 0)
                    print(str(i) + " -> red")
                elif colnum == 2:
                    dev.LedCtrlRaw(i, 3, 3)
                    print(str(i) + " -> yellow")
                elif colnum == 3:
                    dev.LedCtrlRaw(i, 0, 3)
                    print(str(i) + " -> green")
                else:
                    dev.LedCtrlRaw(i, 3, 3)
                    print(str(i) + " -> yellow by else case")
            colnum += 1
            time.wait(buffer_time_numbers)
        time.wait(buffer_time_lists)
        dev.Reset()
        franum += 1
    print("#####ANIMATION END#####\n")
예제 #19
0
def rauf():
    print("rauf")
    uff = requests.get(
        "http://10.0.1.73:8087/set/hm-rega.0.4156.ProgramExecute?value=true")
    lp.LedCtrlRaw(200, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(200, 0, 3)
예제 #20
0
 def update(self):
     if self.rect.centery < Game.current.background.get_rect().centery:
         self.rect.centery = min(self.rect.centery + self.__frame_step,
                                 Game.current.background.get_rect().centery)
     else:
         wait(self.game_over_delay)
         Game.current.shutdown()
예제 #21
0
def ledon():
    print("LED ON")
    uff = requests.get(
        "http://10.0.1.73:8087/set/wled.0.483fda499ffa.on?value=true")
    lp.LedCtrlRaw(205, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(205, 0, 3)
예제 #22
0
def main():

    LP = launchpad.Launchpad()  # creates a Launchpad instance (first Launchpad found)
    LP.Open()  # start it

    LP.LedCtrlString("HELLO ", 0, 3, -1)  # scroll "HELLO" from right to left

    # random output until button "arm" (lower right) is pressed
    print("---\nRandom madness. Stop by hitting the ARM button (lower right)")
    print("Remember the PyGame MIDI bug:")
    print("If the ARM button has no effect, hit an automap button (top row)")
    print("and try again...")

    while 1:
        LP.LedCtrlRaw(random.randint(0, 127), random.randint(0, 3), random.randint(0, 3))

        # some extra time to give the button events a chance to come through...
        time.wait(5)

        but = LP.ButtonStateRaw()
        if but != []:
            print(but)
            if but[0] == 120:
                break

    LP.Reset()  # turn all LEDs off
    LP.Close()  # close the Launchpad
예제 #23
0
def mpdctrl(bs):
    if len(bs) > 1:
        if bs[0] == 1 and bs[1] == 8 and bs[2] == 127:
            call(["mpc", "toggle"])
            lp.LedCtrlXY( 1, 8, 0, 20, 100 )

        if bs[0] == 1 and bs[1] == 7 and bs[2] == 127:
            call(["mpc", "next"])
            lp.LedCtrlXY( 1, 7, 0, 0, 255 )
            time.wait(50)

        if bs[0] == 1 and bs[1] == 7 and bs[2] == 0:
            lp.LedCtrlXY( 1, 7, 0, 0, 10 )

        if bs[0] == 1 and bs[1] == 6 and bs[2] == 127:
            call(["mpc", "prev"])
            lp.LedCtrlXY( 1, 6, 0, 0, 255 )
            time.wait(50)

        if bs[0] == 1 and bs[1] == 6 and bs[2] == 0:
            lp.LedCtrlXY( 1, 6, 0, 0, 10 )

        if bs[0] == 1 and bs[1] == 5 and bs[2] == 127:
            call(["mpc", "single","on"])
            lp.LedCtrlXY( 1, 5, 0, 20, 0 )
            single = 1
        if bs[0] == 1 and bs[1] == 4 and bs[2] == 127:
            call(["mpc", "single","off"])
            lp.LedCtrlXY( 1, 4, 20, 0, 0 )
            single = 0
예제 #24
0
def runter():
    print("runter")
    uff = requests.get(
        "http://10.0.1.73:8087/set/hm-rega.0.4168.ProgramExecute?value=true")
    lp.LedCtrlRaw(201, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(201, 0, 3)
def main():

	# create two Launchpad instances
	lp1 = launchpad.Launchpad()
	lp2 = launchpad.Launchpad()

	# open them
	lp1.Open(0)
	lp2.Open(1)


	while 1:
	
		# random light show
		lp1.LedCtrlRaw( random.randint(0,127), random.randint(0,3), random.randint(0,3) )
		lp2.LedCtrlRaw( random.randint(0,127), random.randint(0,3), random.randint(0,3) )
		
		# some extra time to give the button events a chance to come through...
		time.wait( 5 )

		# wait until the arm button (lower right) is hit
		but = lp1.ButtonStateRaw()
		if but != []:
			print( but )
			if but[0] == 120:
				break
def start(LP):
  snake = {}
  
  init_snake(LP, snake)
  
  LP.LedCtrlXY(0, 0, 0, 1)
  LP.LedCtrlXY(1, 0, 0, 1)
  LP.LedCtrlXY(8, 8, 1, 0)
  
  time.wait(500)
  
  while True:
    time.wait(500)
    
    but = LP.ButtonStateXY()
    while but != [] and not but[2]:
      but = LP.ButtonStateXY()
    
    if but != [] and but[2]:
      if but[0:2] == [8, 8]:
        break
      if but[0:2] == snake["food"]:
        snake["head"] = [3, 3]
      elif but[0:2] == [0, 0]:
        snake["dir"] = (snake["dir"] - 1) % 4
      elif but[0:2] == [1, 0]:
        snake["dir"] = (snake["dir"] + 1) % 4
    
    update(LP, snake)
예제 #27
0
def rainbow():
    print("WLED RAINBOW")
    uff = requests.get(
        "http://10.0.1.73:8087/set/wled.0.483fda499ffa.seg.0.fx?value=9")
    lp.LedCtrlRaw(207, 3, 1)
    time.wait(560)
    lp.LedCtrlRaw(207, 0, 3)
예제 #28
0
def main(file_path=None):
    """Play an audio file as a buffered sound sample

    Option argument:
        the name of an audio file (default data/secosmic_low.wav

    """
    if file_path is None:
        file_path = os.path.join(main_dir,
                                 'data',
                                 'secosmic_lo.wav')

    #choose a desired audio format
    mixer.init(11025) #raises exception on fail


    #load the sound    
    sound = mixer.Sound(file_path)


    #start playing
    print ('Playing Sound...')
    channel = sound.play()


    #poll until finished
    while channel.get_busy(): #still playing
        print ('  ...still going...')
        time.wait(1000)
    print ('...Finished')
예제 #29
0
 def play(self, obj_sonido):
     sonido = mixer.Sound(obj_sonido["path_archivo"])
     if obj_sonido["nombre"] != "":
         self.__sonido_actual = obj_sonido["nombre"]
     if obj_sonido["caracteristicas"] != "":
         if "loop" in obj_sonido["caracteristicas"]:
             self.__canal.play(sonido, -1)
         elif "volumen" in obj_sonido["caracteristicas"]:
             derecha = obj_sonido["caracteristicas"]["volumen"]["derecha"]
             izquierda = obj_sonido["caracteristicas"]["volumen"][
                 "izquierda"]
             self.__canal.set_volume(izquierda, derecha)
             self.__canal.play(sonido)
         elif "grupo_sonido" in obj_sonido["caracteristicas"]:
             self.nombre_grupo_sonido = obj_sonido["caracteristicas"][
                 "grupo_sonido"]
             self.__canal.play(sonido)
             if self.__sonido_actual == "wait_input":
                 self.nombre_grupo_sonido = ""
         else:
             log.warn("Faltan acciones para las demas caracteristicas")
     else:
         self.__canal.play(sonido)
     while self.__canal.get_busy():
         time.wait(100)
     self.__end_sound_event = True
예제 #30
0
파일: defrag.py 프로젝트: siddv/Defrag.py
def progress():

	global posX
	global posY
	global colour
	global delay

	# Progress by a random number between 2 and 6 blocks
	progression = random.randint(2,6)

	# Run 3 times, one for each state.
	for x in range(0, 3):

		for y in range(0, progression):

			# If progression has reached the 8th column, increase the row number and reset the column number.
			if posX[x] == 8:
				posY[x] += 1
				posX[x] = 0

			# Set LED Colours according to the state and colour var in setup.
			LP.LedCtrlXY(posX[x], posY[x], colour[x][0], colour[x][1])

			# Increase column number.
			posX[x] = posX[x]+1

		# Wait a rancom number of milliseconds according to the delay var.
		time.wait(random.randint(delay[x][0],delay[x][1]))
예제 #31
0
def ledctrlfn(dev,list,buffer_time_lists,buffer_time_numbers,red,green):
 from pygame import time
 for i in list:
  dev.LedCtrlRaw(i,red,green)
  print(i)
  time.wait(buffer_time_numbers)
  dev.Reset()
예제 #32
0
def ledctrlc(dev,list,buffer_time_lists,buffer_time_numbers):
 from pygame import time
 franum_total = 0
 for frame in list:
  franum_total += 1
 franum = 1
 print("#####ANIMATION START#####")
 for frame in list:
  colnum = 1
  print("+++++FRAME " + str(franum) + " / " + str(franum_total) + " +++++")
  for color in frame:
   for i in color:
    if colnum == 1:
     dev.LedCtrlRaw(i,3,0)
     print(str(i) + " -> red")
    elif colnum == 2:
     dev.LedCtrlRaw(i,3,3)
     print(str(i) + " -> yellow")
    elif colnum == 3:
     dev.LedCtrlRaw(i,0,3)
     print(str(i) + " -> green")
    else:
     dev.LedCtrlRaw(i,3,3)
     print(str(i) + " -> yellow by else case")
   colnum += 1
   time.wait(buffer_time_numbers)
  time.wait(buffer_time_lists)
  dev.Reset()
  franum += 1
 print("#####ANIMATION END#####\n")
def test():
    sp = SoundPlayer()
    for i in range(8):
        sp.load(i)
    t = sp.sounds[1].get_length() * 1000
    sp.play(1)
    time.wait(t)
예제 #34
0
def game_loop():
    """basic game loop"""

    # now setup and initialize everything
    scr = display.set_mode(size=(800, 600))
    d = display
    d.set_caption("Pysnake")
    init()

    # make some black `background`
    bkg = Surface(scr.get_size())
    bkg = bkg.convert()

    # font to be incorporated TODO:
    fn = font.Font(None, 36)
    tex = fn.render("Hello world", 1, (255, 255, 255))
    tex_pos = tex.get_rect()
    tex_pos.centerx = bkg.get_rect().centerx
    tex.blit(bkg, tex_pos)

    # basic _not so_ `global` variables
    position = (0, 0)   # current snake position
    vector = (20, 0)    # mr. Snakes moves to right
    snakes = [(0, 0)]   # snake is array of cells
    length = 5          # initial snake's lenght
    appleh = spawn_apple(scr, snakes) # initial apple

    while 1:
        # game loop
        for e in event.get():
            if e.type == QUIT:
                quit()
            if e.type == KEYDOWN:
                if e.key == K_d:
                    vector = (20, 0)
                if e.key == K_a:
                    vector = (-20, 0)
                if e.key == K_w:
                    vector = 0, -20
                if e.key == K_s:
                    vector = 0, 20
        bkg.fill((0, 0, 0))
        position = position[0] + vector[0], position[1] + vector[1] # move the snake
        if position in snakes:   # collision detected
            vector = (0, 0)      # TODO:
        if appleh == position:   # collision with apple
            length += 1
            appleh = spawn_apple(scr, snakes)
        snakes.insert(0, position) # add current position to snake array
        if len(snakes) > length:   # if the snake is longer, than he should be
            snakes.pop()           # pop his tail
        for pos in snakes:         # for each cell in snake's list
            draw_cell(pos, bkg)    # draw the cell
        draw_appleh(appleh, bkg)    
        scr.blit(bkg, (0, 0))
        d.flip()
        # print(snakes)
        print(appleh)
        time.wait(125)              # you may set this to smaller number
예제 #35
0
def check_for_exit(poll_time=KEY_PRESS_POLL_TIME):
    time.wait(poll_time)
    if not event.peek():
        return

    ev = event.poll()
    if ev.type == pygame.KEYDOWN and ev.key == pygame.K_SPACE:
        sys.exit(0)
예제 #36
0
파일: demo.py 프로젝트: xujinjie151/wxpy
 def play(self, filename):
     f = open(filename, 'rb')
     mixer.music.load(f)
     mixer.music.play()
     while mixer.music.get_busy():  # still playing
         time.wait(1000)
     f.close()
     list_free.append(filename)
예제 #37
0
    def gameover(self):
        """Display a screen of end."""

        game_over = image.load(GAME_OVER_IMG).convert()
        self.screen.blit(game_over, (0, 0))
        display.flip()
        time.wait(1500)
        self.screen.fill((0, 0, 0))
예제 #38
0
파일: demo.py 프로젝트: xujinjie151/wxpy
 def play(self):
     f = open(self.name, 'rb')
     mixer.music.load(f)
     mixer.music.play(loops=0, start=0.0)
     while mixer.music.get_busy():  # still playing
         time.wait(600)
     f.close()
     list_free.append(self.name)
    def plan_mr(self):
        [r1, r2, r3, r4] = [[50, 100], [50, 130], [750, 100], [750, 130]]
        payload = [43, 80]
        game_display = self.pygame.display_game(self.display_mode,
                                                self.caption)
        game_exit = False
        while not game_exit:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
            if self.count_steps < 250:
                r1[0] += 1
                r2[0] += 1
                r3[0] -= 1
                r4[0] -= 1
                payload[0] += 1
                self.count_steps += 1

            if self.count_steps == 250:
                r1 = [r1[0], r1[1]]
                r2 = [r2[0], r2[1]]
                p_center = self.math.find_center(r1, r2)
                #print p_center
                traj_r1 = self.math.plan_circular_trajectory(
                    r1, p_center, self.angle_unit)
                traj_r2 = self.math.plan_circular_trajectory(
                    r2, p_center, self.angle_unit)
                self.count_steps += 1
            if ((self.count_steps > 250) and (self.traj_steps < 18)):
                r1 = traj_r1[self.traj_steps]
                r2 = traj_r2[self.traj_steps]
                r3[0] -= 1
                r4[0] -= 1
                payload[0] += 1
                self.count_steps += 1
                self.traj_steps += 1

            if ((self.traj_steps >= 18) and (self.traj_steps < 400)):
                r1[1] += 1
                r2[1] += 1
                r3[0] -= 1
                r4[0] -= 1
                payload[0] += 1
                self.count_steps += 1
                self.traj_steps += 1

            game_display.fill(self.color[0])
            pygame.draw.circle(game_display, self.color[3], r1, 12)
            pygame.draw.circle(game_display, self.color[3], r2, 12)
            pygame.draw.circle(game_display, self.color[1], r3, 12)
            pygame.draw.circle(game_display, self.color[1], r4, 12)
            pygame.draw.rect(game_display, self.color[2],
                             [payload[0], payload[1], 14, 70])

            pygame.display.update()
            time.wait(50)
        pygame.quit()
        quit()
    def plan_mr_img(self):
        [r1,  r2, r3, r4] = [[50, 95],[50,135], [750, 100], [750, 130]]
        payload = [30,95]
        payload_img = pygame.image.load('payload.jpg')
        payload_img = pygame.transform.scale(payload_img, (45, 40))
        game_display = self.pygame.display_game(self.display_mode, self.caption)
        game_exit = False
        while not game_exit:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
            if self.count_steps < 90:
                r1[0] +=3
                r2[0] +=3
                r3[0] -=3
                r4[0] -=3
                payload[0] +=3
                self.count_steps +=1 
            
            if self.count_steps == 90:
                r1 = [r1[0], r1[1]]
                r2 = [r2[0], r2[1]]
                p_center = self.math.find_center(r1, r2)
                #print p_center
                traj_r1 = self.math.plan_circular_trajectory(r1, p_center, self.angle_unit)
                traj_r2 = self.math.plan_circular_trajectory(r2, p_center, self.angle_unit)
                traj_payload = self.math.plan_circular_trajectory(payload, p_center, self.angle_unit)
                self.count_steps +=1
            if ((self.count_steps > 90) and (self.traj_steps < 30)):
                r1 = traj_r1[self.traj_steps]
                r2 = traj_r2[self.traj_steps]
                r3[0] -=1
                r4[0] -=1
                payload = traj_payload[self.traj_steps]
                self.count_steps +=1
                self.traj_steps +=1

            if ( (self.traj_steps >= 30) and (self.traj_steps < 150) ):
                r1[1] +=3
                r2[1] +=3
                r3[0] -=3
                r4[0] -=3
                payload[1] +=3
                self.count_steps +=1
                self.traj_steps +=1
            payload_tuple = (payload[0], payload[1])
            game_display.fill(self.color[0])
            pygame.draw.circle(game_display, self.color[3], r1,12)
            pygame.draw.circle(game_display, self.color[3], r2,12)
            pygame.draw.circle(game_display, self.color[1], r3,12)
            pygame.draw.circle(game_display, self.color[1], r4,12)
            game_display.blit(payload_img, payload_tuple)
            #pygame.draw.circle(game_display, self.color[2], payload,25)

            pygame.display.update()
            time.wait(100)          
        pygame.quit()
        quit()
예제 #41
0
 def step(self):
     """Step forwards one frame."""
     t = time()
     dt = self.t + self.frame - t
     if dt > 0:
         wait(int(1000 * dt))
         self.t = t + dt
     else:
         self.t = t
예제 #42
0
 def show(self):
     if not self.__power:
         return
     else:
         self.__screen_buffer[:] = self.buffer
         self.__pygame_signal(REQUEST_ACTION_REFRESH,
                              rect=(0, 0, self.width, self.height))
     # sleep(0.05) # emu refresh speed
     wait(50)
예제 #43
0
파일: timer.py 프로젝트: chozabu/Neinjarz
def tick():
    global turntime, totaltime, totalturns, fps
    totalturns+=1
    turntime = clock.tick()# / steptime
    if turntime > maxturntime:turntime = maxturntime
    time.wait(maxturntime-turntime)
    totaltime = time.get_ticks()
    #fps = 1000/(fps*0.1+(totaltime/totalturns)*0.9)
    #print fps
예제 #44
0
def start(LP):
  while True:
    LP.LedCtrlXY(random.randint(0,8), random.randint(0,8), random.randint(0,3), random.randint(0,3))
    
    time.wait(5)
    
    but = LP.ButtonStateXY()
    if but != [] and but[0:2] == [8, 8]:
      break
예제 #45
0
파일: sched.py 프로젝트: ikn/wvoas
 def step (self):
     """Step forwards one frame."""
     t = time()
     dt = self.t + self.frame - t
     if dt > 0:
         wait(int(1000 * dt))
         self.t = t + dt
     else:
         self.t = t
예제 #46
0
파일: sched.py 프로젝트: Anstow/TeamAwesome
 def step(self):
     """Step forwards one frame."""
     t = time()
     t_left = self.t + self.frame - t
     if t_left > 0:
         wait(int(1000 * t_left))
         self.t = t + t_left
     else:
         self.t = t
예제 #47
0
 def run(self):
     while(recording):
         if self.inst.poll():
             midi_events = self.inst.read(10)
             for note in midi_events:
                 if note[0][2] > 0: # filter out notes with velocity 0
                     self.noteList.append(midi_events[0])
                     time.wait(10)
     self.inst.close()
예제 #48
0
파일: sched.py 프로젝트: Anstow/TeamAwesome
    def run(self, cb, *args, **kwargs):
        """Run indefinitely or for a specified amount of time.

run(cb, *args[, seconds][, frames]) -> remain

cb: a function to call every frame.
args: extra arguments to pass to cb.
seconds, frames: keyword-only arguments that determine how long to run for.  If
                 seconds is passed, frames is ignored; if neither is given, run
                 forever (until Timer.stop is called).  Either can be a float.
                 Time passed is based on the number of frames that have passed,
                 so it does not necessarily reflect real time.

remain: the number of frames/seconds left until the timer has been running for
        the requested amount of time (or None, if neither were given).  This
        may be less than 0 if cb took a long time to run.

"""
        self.stopped = False
        seconds = kwargs.get("seconds")
        frames = kwargs.get("frames")
        if seconds is not None:
            seconds = max(seconds, 0)
        elif frames is not None:
            frames = max(frames, 0)
        # main loop
        t0 = time()
        while 1:
            frame = self.frame
            cb(*args)
            t = time()
            t_gone = min(t - t0, frame)
            if self.stopped:
                if seconds is not None:
                    return seconds - t_gone
                elif frames is not None:
                    return frames - t_gone / frame
                else:
                    return None
            t_left = frame - t_gone  # until next frame
            if seconds is not None:
                t_left = min(seconds, t_left)
            elif frames is not None:
                t_left = min(frames, t_left / frame)
            if t_left > 0:
                wait(int(1000 * t_left))
                t0 = t + t_left
            else:
                t0 = t
            if seconds is not None:
                seconds -= t_gone + t_left
                if seconds <= 0:
                    return seconds
            elif frames is not None:
                frames -= (t_gone + t_left) / frame
                if frames <= 0:
                    return frames
예제 #49
0
def main():

	# create an instance
	lp = launchpad.Launchpad();

	# try the first Mk2
	if lp.Check( 0, "mk2" ):
		lp = launchpad.LaunchpadMk2()
		if lp.Open( 0, "mk2" ):
			print( " - Launchpad Mk2: OK" )
		else:
			print( " - Launchpad Mk2: ERROR")
			return
		
	# try the first Mk3
	elif lp.Check( 1, "mk3" ):
		lp = launchpad.LaunchpadMk3()
		if lp.Open( 1, "mk3" ):
			print( " - Launchpad Mk3: OK" )
		else:
			print( " - Launchpad Mk3: ERROR")
			return

	# try the first Pro
	elif lp.Check( 0, "pro" ):
		lp = launchpad.LaunchpadPro()
		if lp.Open( 0, "pro" ):
			print( " - Launchpad Pro: OK" )
		else:
			print( " - Launchpad Pro: ERROR")
			return
		
	else:
		print( " - No Launchpad available" )
		return


	lp.ButtonFlush()

	for i in [ 5, 21, 79, 3]:
		lp.LedAllOn( i )
		time.wait(500)
	lp.LedAllOn( 0 )

	colors = [ [63,0,0],[0,63,0],[0,0,63],[63,63,0],[63,0,63],[0,63,63],[63,63,63] ]
	for i in range(4):
		for y in range( i + 1, 8 - i + 1 ):
			for x in range( i, 8 - i ):
				lp.LedCtrlXY( x, y, colors[i][0], colors[i][1], colors[i][2])
		time.wait(500)

	# turn all LEDs off
	lp.Reset()

	# close this instance
	lp.Close()
예제 #50
0
def main(con="conf",dat="data",pic="pix",cf="wx.json"):
    print "pyg start"
    global screen,scr,tdata,defont,ren,load
    
    # configuration
    #bogus_config(con,cf)
        
    # initialize pygame
    pygame.init()
    screen=dsp.set_mode((320,240))  # the display object
    dsp.set_caption('Weather Demo')
    defont=pygame.font.Font(None,20)

    ren=defont.render
    load=pygame.image.load
        
    # run test code
#    testing(tdata)
       
    # initialize screen
    # fields are defined
    # fields are not displayed yet
    wxf=scr()
    ccff=con+'/'+cf
    wxf.config(ccff)
    #############print "(fields)" , wxf.fields
    # set data directory and data file name
    ddd="data"
    wxf.set_data_dir(ddd)
    wxf.set_data_file_name("wxdata.json")
    wxf.get_data()
    screen.fill((200,0,200))
    dsp.flip()

    print "::::::::::::",wxf.ddict
#    import pdb; pdb.set_trace()
    # the main loop is a do-forever
    onward=True
    while(onward):  
        ###################### button check
        # data acquisition
        wxf.get_data()
        ###################### data format
        # display new screen data
        wxf.display_fields()
        dsp.flip()
        tm.wait(3000)
#        onward=False    
        # exit test?
        # end of main loop
     

    print "I'm waiting..."
    tm.wait(wait_time)
    pygame.quit()
    sys.exit(100)
예제 #51
0
 def message(self, m):
     t = Drawable.String(self.window, m)
     p = CirclePath(duration=10)
     t.set_path(p)
     try:
         t.runPath()
     except:
         pass
     wait(2000)
     os._exit(0)
예제 #52
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((320, 240))
    rect = pygame.Rect(0, 0, 10, 10)

    while True:
        pygame.draw.rect(screen, (255, 255, 255), rect)
        rect.right += 20
        pygame.display.flip()
        wait(1000)
    def plan_mr(self):
        [r1,  r2, r3, r4] = [[50, 100],[50,130], [750, 100], [750, 130]]
        payload = [43,80] 
        game_display = self.pygame.display_game(self.display_mode, self.caption)
        game_exit = False
        while not game_exit:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
            if self.count_steps < 250:
                r1[0] +=1
                r2[0] +=1
                r3[0] -=1
                r4[0] -=1
                payload[0] +=1
                self.count_steps +=1 
            
            if self.count_steps == 250:
                r1 = [r1[0], r1[1]]
                r2 = [r2[0], r2[1]]
                p_center = self.math.find_center(r1, r2)
                #print p_center
                traj_r1 = self.math.plan_circular_trajectory(r1, p_center, self.angle_unit)
                traj_r2 = self.math.plan_circular_trajectory(r2, p_center, self.angle_unit)
                self.count_steps +=1
            if ((self.count_steps > 250) and (self.traj_steps < 18)):
                r1 = traj_r1[self.traj_steps]
                r2 = traj_r2[self.traj_steps]
                r3[0] -=1
                r4[0] -=1
                payload[0] +=1
                self.count_steps +=1
                self.traj_steps +=1

            if ( (self.traj_steps >= 18) and (self.traj_steps < 400) ):
                r1[1] +=1
                r2[1] +=1
                r3[0] -=1
                r4[0] -=1
                payload[0] +=1
                self.count_steps +=1
                self.traj_steps +=1
                
            game_display.fill(self.color[0])
            pygame.draw.circle(game_display, self.color[3], r1,12)
            pygame.draw.circle(game_display, self.color[3], r2,12)
            pygame.draw.circle(game_display, self.color[1], r3,12)
            pygame.draw.circle(game_display, self.color[1], r4,12)
            pygame.draw.rect(game_display, self.color[2], [payload[0], payload[1],14,70])
            

            pygame.display.update()
            time.wait(50)          
        pygame.quit()
        quit()
예제 #54
0
파일: egg.py 프로젝트: MrGecko/pyguane
 def run(self):
     self.Renderer(None) #make a default renderer if there is not
     event_update = self._event_manager.update
     draw = self.renderer.draw
     updateWorld = self._updateWorld
     
     while self.continue_pyguane:
         wait(2)  #don't waste the cpu
         event_update()
         updateWorld()
         draw()
예제 #55
0
def main():

	# some basic info
	print( "\nRunning..." )
	print( " - Python " + str( sys.version.split()[0] ) )
	print( " - PyGame " + str( pygame.ver ) )

	# create an instance
	lp = launchpad.LaunchpadMk2();

	# open the first Launchpad Mk2
	if lp.Open( 0, "mk2" ):
		print( " - Launchpad Mk2: OK" )
	else:
		print( " - Launchpad Mk2: ERROR" )
		return

	# Clear the buffer because the Launchpad remembers everything
	lp.ButtonFlush()

	# List the class's methods
	print( " - Available methods:" )
	for mName in sorted( dir( lp ) ):
		if mName.find( "__") >= 0:
			continue
		if callable( getattr( lp, mName ) ):
			print( "     " + str( mName ) + "()" )

	# LedAllOn() test
	print( " - Testing LedAllOn()" )
	for i in [ 5, 21, 79, 3]:
		lp.LedAllOn( i )
		time.wait(500)
	lp.LedAllOn( 0 )

	# LedCtrlXY() test
	# -> LedCtrlRaw()
	#    -> midi.RawWriteSysEx()
	#       -> devOut.write_sys_ex()
	print( " - Testing LedCtrlXY()" )
	colors = [ [63,0,0],[0,63,0],[0,0,63],[63,63,0],[63,0,63],[0,63,63],[63,63,63] ]
	for i in range(4):
		for y in range( i + 1, 8 - i + 1 ):
			for x in range( i, 8 - i ):
				lp.LedCtrlXY( x, y, colors[i][0], colors[i][1], colors[i][2])
		time.wait(500)

	# turn all LEDs off
	print( " - Testing Reset()" )
	lp.Reset()

	# close this instance
	print( " - More to come, goodbye...\n" )
	lp.Close()
예제 #56
0
def audio_preguntas(foo):
    if foo == 'a':
        aud_inicio()
    elif foo == 'b':
        pytime.wait(1000)
        sound = py.mixer.Sound("imagenes/autores.ogg")
        sound.play()
    elif foo == 'c':
        pytime.wait(1000)
        sound = py.mixer.Sound("imagenes/instrucciones2.ogg")
        sound.play()
예제 #57
0
 def play(self, *args, **kwargs):        
     current_pitch = self.pitch.pitch.midi
     pg_time.wait(self.additional_latency)
     if current_pitch not in notes_on:            
         notes_on[current_pitch] = True
         velocity = int(127.0 * self.gain)
         midi_out.note_on(current_pitch, velocity)
         pg_time.wait(int(self.dur))
         if not self.portamento:
             midi_out.note_off(current_pitch, velocity)
         del notes_on[current_pitch]        
예제 #58
0
def handleButton(but, drone, currentV, currentY):
	scale = 0.2 #what scale is this (from example)
	vert = 0.4 #what scale is this (from example)

        # print 'navdata: ', drone.navdata

	if (but[1] > 0 and but[0] < 8):
		if (but[0] < 4):
			sX = (but[0] - 4)*scale
		else:
			sX = (but[0] - 3)*scale
		if (but[1] < 5):
			sY = (but[1] - 5)*scale
		else:
			sY = (but[1] - 4)*scale
		if (sX == currentV[0] and sY == currentV[1]):
			currentV[0] = 0
			currentV[1] = 0
		else:
			currentV[0] = sX
			currentV[1] = sY
                print 'change XY'
	elif (but[0] < 2 and but[1] == 0):
		sZ = -(but[0]*2-1)*vert
		if (sZ == currentV[2]):
			currentV[2] = 0
		else:
			currentV[2] = sZ
                print 'change height'
	elif ((but[0] == 2 or but[0] == 3) and but[1] == 0):
		sR = ((but[0]-2)*2-1)*scale
                if sR == currentY:
                        currentY = 0
                else:
                        currentY = sR
                print 'change yaw'
	elif (but == [4, 0, True]):
		currentV, currentY = stabilizeParrot(drone)
                print 'stabilize'
	elif (but == [8, 8, True]):
                while drone.navdata['drone_state']['fly_mask'] == 0:
                        print('taking off')
		        drone.takeoff() # REPEAT UNTIL TAKEOFF
                        time.wait(16)
                print 'takeoff successful'
	elif (but == [8, 5, True]):
                while drone.navdata['drone_state']['fly_mask'] == 1:
                        print('landing')
		        drone.land() # REPEAT UNTIL LANDING
                        time.wait(16)
                print 'landing successful'

	drone.at(libardrone.at_pcmd, True, currentV[0], currentV[1], currentV[2], currentY)
	return currentV, currentY
예제 #59
0
def main():
    # Intro
    pygame.init()
    screen = pygame.display.set_mode((640, 400))
    pygame.display.set_caption('Fire Balls')

    background = pygame.Surface(screen.get_size())
    background = background.convert()
    bgcolor = (250, 250, 200)
    background.fill(bgcolor)
    screen.blit(background, (0, 0))

    text = write('Ready?', None, 50, (0,0,0), background.get_rect().centerx, background.get_rect().centery)
    screen.blit(text["surface"], text["rect"])

    # Init the game
    balls = pygame.sprite.Group()
    ispeed = (15, -60)
    fireball(ispeed, balls)
    
    dirty = pygame.Surface(balls.sprites()[0].get_size()).convert()
    dirty.fill(bgcolor)
    
    pygame.display.flip()
    time.wait(1000)
    text["surface"].fill(bgcolor)
    screen.blit(text["surface"], text["rect"])
    
    text = write('Press F to fire a ball, and q to quit', None, 25, (0,0,0), background.get_rect().centerx, background.get_rect().y)
    screen.blit(text["surface"], text["rect"])
    
    #Game Loop
    #pygame.time.Clock.tick(25)
    n = 0
    while 1:
        n += 1          # actually tick does not work for me, so it's orribly patched :(
        if n == 499999: #
            n = 0       #
            for event in pygame.event.get():
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_q):
                    return
                if event.type == KEYDOWN and event.key == K_f:
                    fireball(ispeed, balls)
            #Recalculate the image to be displayed
            i = 0
            for b in balls.sprites():
                screen.blit(dirty, b.position)
                b.update(screen)
                screen.blit(b.image, b.position)
                
            screen.blit(text["surface"], text["rect"])
            pygame.display.flip()