Exemplo n.º 1
0
def play_audio(samples, wait_for_end=False):
    """
    Uses PyGame to play the audio samples given as a list of samples.
    
    """
    init_mixer()
    from pygame.mixer import music
    from pygame.sndarray import make_sound
    from pygame import USEREVENT, event
    import numpy

    # Prepare the wave data to play
    # Make it stereo and the right number format
    smp_array = numpy.array(zip(samples, samples)).astype(numpy.int16)

    # Generate the sound object from the sample array
    snd = make_sound(smp_array)
    # Set it playing
    channel = snd.play()
    # Set an event to be triggered when the music ends, so we can
    #  wait for it if necessary
    channel.set_endevent(USEREVENT)

    if wait_for_end:
        # Wait until the music finishes
        event.wait()
Exemplo n.º 2
0
def play_audio(samples, wait_for_end=False):
    """
    Uses PyGame to play the audio samples given as a list of samples.
    
    """
    init_mixer()
    from pygame.mixer import music
    from pygame.sndarray import make_sound
    from pygame import USEREVENT, event
    import numpy
    
    # Prepare the wave data to play
    # Make it stereo and the right number format
    smp_array = numpy.array(zip(samples,samples)).astype(numpy.int16)
    
    # Generate the sound object from the sample array
    snd = make_sound(smp_array)
    # Set it playing
    channel = snd.play()
    # Set an event to be triggered when the music ends, so we can 
    #  wait for it if necessary
    channel.set_endevent(USEREVENT)
    
    if wait_for_end:
        # Wait until the music finishes
        event.wait()
Exemplo n.º 3
0
def main(argv=[]):
    display.init()
    joystick.init()

    if len(argv) > 1:
        for sz in argv[1:]:
            try:
                joystick.Joystick(int(sz)).init()
            except:
                pass
    else:
        for i in xrange(joystick.get_count()):
            joystick.Joystick(i).init()

    e = event.wait()
    while e.type != QUIT:
        if e.type == JOYAXISMOTION:
            print 'js', e.joy, 'axis', e.axis, round(e.value, P)
        elif e.type == JOYBALLMOTION:
            print 'js', e.joy, 'ball', e.ball, round(e.rel, P)
        elif e.type == JOYHATMOTION:
            print 'js', e.joy, 'hat', e.hat, h[e.value]
        elif e.type == JOYBUTTONUP:
            print 'js', e.joy, 'button', e.button, 'up'
        elif e.type == JOYBUTTONDOWN:
            print 'js', e.joy, 'button', e.button, 'down'
        e = event.wait()
Exemplo n.º 4
0
 def input(self):
     #event = pygame.event.wait()
     evt = event.wait()
     if evt.type == KEYDOWN:
         if evt.key == K_SPACE:
             return "QUIT"
     return None
Exemplo n.º 5
0
def getResponse(
        player,
        correct):  #retrun the option number if correct answer or -1 if wrong
    countdown = 0
    pygame.event.clear()
    pygame.time.set_timer(pygame.USEREVENT,
                          1000)  #give x seconds for an answer or return zero
    done = False
    while not done:
        displayCountdown(countdown)
        e = event.wait()
        #for event in pygame.event.get():
        if e.type == USEREVENT:
            countdown += 1
            if countdown == 5:
                pygame.time.set_timer(pygame.USEREVENT,
                                      0)  #turn off user timer
                done = True
                return 0
        if cfg.keyboardControl == True:
            if e.type == KEYDOWN:
                if e.key == K_1:
                    done = True
                    if correct == 1:
                        return correct
                    else:
                        return -1
                elif e.key == K_2:
                    done = True
                    if correct == 2:
                        return correct
                    else:
                        return -2
                elif e.key == K_3:
                    done = True
                    if correct == 3:
                        return correct
                    else:
                        return -3
                elif e.key == K_4:
                    done = True
                    if correct == 4:
                        return correct
                    else:
                        return -4
        if cfg.bigButtonControl == True:
            if e.type == JOYBUTTONDOWN:
                if e.button != 6:  #dont accept big button
                    if e.joy == cfg.players[
                            player -
                            1].controller:  #check for correct player controller ignore other controllers
                        if (e.button + 1) == correct:
                            done = True
                            print("correct = " + str(correct) + " button = " +
                                  str(e.button))
                            return correct
                        else:
                            print("correct = " + str(correct) + "-button = " +
                                  str((-(e.button + 1))))
                            return ((e.button + 1) * -1)
Exemplo n.º 6
0
    def _get_continue_signal(self):
        self._print('Getting continue signal')
        while True:
            evt = event.wait()

            if evt.type == pygame.QUIT:
                return False

            if evt.type == pygame.KEYUP:
                if evt.key == pygame.K_RETURN or evt.key == pygame.K_KP_ENTER:
                    return True
Exemplo n.º 7
0
 def input(self):
     evt = event.wait()
     if evt.type == KEYDOWN:
         if evt.key == K_SPACE:
             return "SEL"
         if evt.key == K_ESCAPE:
             return "QUIT"
         if evt.key == K_DOWN:
             return "DOWN"
         if evt.key == K_UP:
             return "UP"
     return None
Exemplo n.º 8
0
def check_for_exit(wait=False):
    global DETAILED_PROGRESS

    if wait:
        ev = event.wait()
    else:
        ev = event.poll()

    if ev and ev.type == pygame.KEYDOWN and ev.key == pygame.K_SPACE:
        end()
        sys.exit(0)
    elif ev and ev.type == pygame.KEYDOWN and ev.key == pygame.K_DELETE:
        DETAILED_PROGRESS = not DETAILED_PROGRESS
        clear_progress()
Exemplo n.º 9
0
 def run(self):
     mixer.music.set_endevent(USEREVENT)
     while True:
         error = False
         try:
             ev = event.wait()
         except:
             # If anything went wrong with the queue, just give up waiting
             error = True
         
         if error or ev.type == USEREVENT:
             # This usually gets fired a bit too early, so wait a 
             #  bit before we call the cleanup
             time.sleep(0.1)
             self.__dict__["callback"]()
             if self.event is not None:
                 self.event.set()
             return
Exemplo n.º 10
0
    def run(self):
        mixer.music.set_endevent(USEREVENT)
        while True:
            error = False
            try:
                ev = event.wait()
            except:
                # If anything went wrong with the queue, just give up waiting
                error = True

            if error or ev.type == USEREVENT:
                # This usually gets fired a bit too early, so wait a
                #  bit before we call the cleanup
                time.sleep(0.1)
                self.__dict__["callback"]()
                if self.event is not None:
                    self.event.set()
                return
Exemplo n.º 11
0
    def run(self):
        self.start()
        self.clock.start()
        while True:
            while True:
                wait_time = self.clock.time_remaining()
                if wait_time > 0:
                    e = event.wait(wait_time)
                else:
                    e = event.poll()
                if e.type == pygame.NOEVENT:
                    break
                self.event(e)
            self.clock.advance()

            update_ret = self.update()
            if update_ret is not None:
                return update_ret

            self.render()
Exemplo n.º 12
0
    def test_issue_208(self):
        """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection

           Copying into theX11 PRIMARY selection (mouse copy/paste) would not
           work due to a confusion between content type and clipboard type.

        """

        from pygame import display, event, freetype
        from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
        from pygame.locals import KEYDOWN, K_y, QUIT

        success = False
        freetype.init()
        font = freetype.Font(None, 24)
        display.init()
        display.set_caption("Interactive X11 Paste Test")
        screen = display.set_mode((600, 200))
        screen.fill(pygame.Color("white"))
        text = "Scrap put() succeeded."
        msg = (
            "Some text has been placed into the X11 clipboard."
            " Please click the center mouse button in an open"
            " text window to retrieve it."
            '\n\nDid you get "{}"? (y/n)'
        ).format(text)
        word_wrap(screen, msg, font, 6)
        display.flip()
        event.pump()
        scrap.init()
        scrap.set_mode(SCRAP_SELECTION)
        scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
        while True:
            e = event.wait()
            if e.type == QUIT:
                break
            if e.type == KEYDOWN:
                success = e.key == K_y
                break
        pygame.display.quit()
        self.assertTrue(success)
Exemplo n.º 13
0
    def test_issue_208(self):
        """PATCH: pygame.scrap on X11, fix copying into PRIMARY selection

           Copying into theX11 PRIMARY selection (mouse copy/paste) would not
           work due to a confusion between content type and clipboard type.

        """

        from pygame import display, event, freetype
        from pygame.locals import SCRAP_SELECTION, SCRAP_TEXT
        from pygame.locals import KEYDOWN, K_y, QUIT

        success = False
        freetype.init()
        font = freetype.Font(None, 24)
        display.init()
        display.set_caption("Interactive X11 Paste Test")
        screen = display.set_mode((600, 200))
        screen.fill(pygame.Color("white"))
        text = "Scrap put() succeeded."
        msg = (
            "Some text has been placed into the X11 clipboard."
            " Please click the center mouse button in an open"
            " text window to retrieve it."
            '\n\nDid you get "{}"? (y/n)'
        ).format(text)
        word_wrap(screen, msg, font, 6)
        display.flip()
        event.pump()
        scrap.init()
        scrap.set_mode(SCRAP_SELECTION)
        scrap.put(SCRAP_TEXT, text.encode("UTF-8"))
        while True:
            e = event.wait()
            if e.type == QUIT:
                break
            if e.type == KEYDOWN:
                success = e.key == K_y
                break
        pygame.display.quit()
        self.assertTrue(success)
def readjoythread():
    """Read joystick loop and pass result onto processor"""
    global channelsglb, trimglb
    output = [0, 0, 0, 0, 0, 0]
    trim = [0, 0, 0, 0, 0, 0]
    joystick.init()
    joystick.Joystick(0).init()
    time.sleep(1)
    for evt in pygame.event.get():
        time.sleep(.02)

    for i in range(0, len(JOY_AXIES)):
        if JOY_AXIES[i] > -1:
            output[JOY_AXIES[i]] = round(joystick.Joystick(0).get_axis(i), 4)
            if output[JOY_AXIES[i]] is None:
                output[JOY_AXIES[i]] = 0
    for chan in JOY_BUTTONS:
        output[chan] = -1

    channelsglb = output[:]

    while RUNNING:
        haschanged = False
        evt = event.wait()
        if evt.type == JOYAXISMOTION:
            if evt.axis < len(JOY_AXIES) and JOY_AXIES[evt.axis] > -1:
                output[JOY_AXIES[evt.axis]] = round(evt.value, 4)
                haschanged = True
        if evt.type == JOYHATMOTION:
            trim[0] = trim[0] + round((evt.value[0] * .01), 4)
            trim[1] = trim[1] + 0 - (round((evt.value[1] * .01), 4))
            haschanged = True
        elif evt.type == JOYBUTTONUP or evt.type == JOYBUTTONDOWN:
            if evt.button < len(JOY_BUTTONS) and JOY_BUTTONS[evt.button] > -1:
                output[JOY_BUTTONS[
                    evt.button]] = -1 if evt.type == JOYBUTTONUP else 1
                haschanged = True
        if haschanged:
            channelsglb = output[:]
            trimglb = trim[:]
Exemplo n.º 15
0
def errorbox(title, msg):
    "display a pygame error box"
    clean_screen()
    init_screen()
    screen = set_mode((450, 150))
    normal_cursor()
    set_caption(title)
    show_message(msg, (10, 10), 12, ("bold"))
    ok_rect = imgv_button(screen, " OK ", 20, screen.get_height() - 40, "midtop")
    while 1:
        event = wait()
        cursor = get_pos()
        check_quit(event)
        hover_button(ok_rect, cursor, screen, " OK ", 20, screen.get_height() - 40, "midtop")
        hover_cursor(cursor, [ok_rect])
        if left_click(event):
            if ok_rect.collidepoint(cursor):
                clean_screen()
                raise SystemExit
        if hit_key(event, K_SPACE):
            clean_screen()
            raise SystemExit
Exemplo n.º 16
0
rarm.moving_speed = 0
rarm.goal_position = P180
rarm.torque_enable = 1

rshoulder = network.get_servo_by_label("rshoulder")
rshoulder.synchronized = False
rshoulder.max_torque = 1023
rshoulder.torque_limit = 1023
rshoulder.moving_speed = 0
rshoulder.goal_position = P180
rshoulder.torque_enable = 1


import time
while 1:
	e = event.wait()
	if e.type == 7:
		print repr(e)
		if e.axis == 0:
			head.goal_position = int(HEAD_FORWARD - HEAD_MAX * e.value)
			
	elif e.type == 10:
		print "10 %s" % e.button
		if e.button == 7:
			rarm.goal_position = P270
			larm.goal_position = P90 
		elif e.button == 6:
			rarm.goal_position = P90
			larm.goal_position = P270
		elif e.button == 0:
			rarm.goal_position = P270
Exemplo n.º 17
0
def wait(l):
    e=event.wait()
    _foo(l,e)
    return e
Exemplo n.º 18
0
	buttonColour=cfg.red
elif button==4:
	buttonText="YELLOW"
	buttonColour=cfg.blue



text="Press your small"
#def blit_text(surface, text, pos, font, bgcolour, txtcolour):
blit_text(gamescreen, text, (100,100), cfg.questionfont, cfg.black, cfg.white)
blit_text(gamescreen, buttonText, (200,200), cfg.questionfont, cfg.black, buttonColour)
blit_text(gamescreen, "button", (200,300), cfg.questionfont, cfg.black, cfg.white)
pygame.display.flip()

button-=1	#to make it equal to wee buttopn on controller
e=event.wait()
if e.type==JOYBUTTONDOWN:
	if e.button!=6:		#dont accept big button
#		if e.joy==cfg.players[player-1].controller:       #check for correct player controller ignore other controllers
		if (e.button)==button:
			done=True
			#print("correct = "+str(correct)+" button = "+str(e.button))
			#return correct
			cfg.players[e.joy].score+=10
			text=cfg.players[e.joy].name
			blit_text(gamescreen, text, (200, 400), cfg.questionfont, cfg.black, cfg.white)
		else:
			print("correct = "+str(correct)+"-button = "+str((-(e.button+1))))
			#return ((e.button+1)*-1)

done = False
Exemplo n.º 19
0
from pygame import mixer, event
mixer.init()  #iniciando o uso da biblioteca do pygame
mixer.music.load('ex1.mp3')  #busca a música
mixer.music.play()  #inicia a música
input()
event.wait()  #encerra a música quando acabar
''''while mixer.music.get_busy():
    time.Clock().tick(10)'''
Exemplo n.º 20
0
def wait():
    ev=event.wait()
    _foo(ev)
    return ev
Exemplo n.º 21
0
""" 15/03/2020 jan Mesu
Faça um programa em python que abra e reproduza um audio de um arquivo em
MP3
"""
from pygame import mixer, init, event

init()
mixer.init()
mixer.music.load('desafio21.mp3')
mixer.music.play()
event.wait()
Exemplo n.º 22
0
def wait(l):
    e = event.wait()
    _foo(l, e)
    return e
Exemplo n.º 23
0
    def __init__(self):
        parser = OptionParser(
            usage="Usage: %prog [OPTIONS] [HOST]",
            version="NATOcubes 0.5",
            epilog="If HOST is not specified, the game will start in local mode. Otherwise it will start in client mode, with HOST as server.")
        parser.add_option('-s', '--server', action="store_true", dest="server", default=False, help="server mode")
        parser.add_option('-p', '--port', type="int", dest="port", default=12345, help="set port (client & server mode) [default: %default]")
        parser.add_option('-x', type="int", dest="x", default=5, help="field width (server & local mode) [default: %default]")
        parser.add_option('-y', type="int", dest="y", default=5, help="field height (server & local mode) [default: %default]")
        parser.add_option('-z', '--size', type="int", dest="size", default=75, help="size of one field [default: %default]")
        parser.add_option('-l', '--player', type="int", dest="numplayers", default=2, help="number of players (local mode) [default: %default]")
        options, args = parser.parse_args()

        self.xsize, self.ysize, self.fieldsize = options.x, options.y, options.size

        if options.server:
            self.handler = server('', options.port, options.x, options.y)
        else:
            if len(args) > 0:
                self.handler = client(args[0], options.port)
                self.xsize, self.ysize = self.handler.getsize()
            else:
                self.handler = local(options.numplayers)

        self.player, self.localplayer, self.numplayers = self.handler.getopts()
        self.counts = []

        self.f = Field(self.xsize, self.ysize, self.fieldsize)
        display.set_mode(((self.xsize * (self.fieldsize + 1) - 1), 18 + (self.ysize * (self.fieldsize + 1) - 1)))
        display.set_caption('NATOcubes')
        surf = self.f.render()
        self.handler.surface(surf, self.player, self.fieldsize)
        display.get_surface().blit(surf, (0, 0))
        display.update()

        ev = event.wait()
        while ev.type != QUIT:
            event.clear()
            display.update()
            if self.player == self.localplayer or self.localplayer == -1:
                ev = event.wait()
                if ev.type == MOUSEBUTTONDOWN:
                    px, py = ev.pos
                    x = px / (self.fieldsize + 1)
                    y = (py - 18) / (self.fieldsize + 1)
                    if self.f.turn(self.player, x, y):
                        self.handler.onTurn(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(), self.fieldsize)
                        display.get_surface().blit(surf, (0, 0))
                        display.update()
                        if self.after_turn():
                            return
            else:
                recv = self.handler.recv_data()
                if recv and len(recv) == 2:
                    x = ord(recv[0])
                    y = ord(recv[1])
                    if self.f.turn(self.player, x, y):
                        self.handler.distribute_data(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(), self.fieldsize)
                        display.get_surface().blit(surf, (0,0))
                        display.update()
                        if self.after_turn():
                            return
                    else:
                        self.handler.failed_turn()
                elif recv == '\x00':
                    s = smallfont.render('Lost Connection', True, Color('#FFFFFF'), Color('#000000'))
                    sw, sh = s.get_size()
                    display.get_surface().blit(s, (((self.xsize * self.fieldsize) - sw) / 2, ((self.ysize * self.fieldsize) - sh) / 2 + 18))
                    display.update()
                    while event.wait().type != QUIT:
                        pass
                    return
                else:
                    sleep(0.1)
                ev = event.poll()
Exemplo n.º 24
0
    def __init__(self):
        parser = OptionParser(
            usage="Usage: %prog [OPTIONS] [HOST]",
            version="NATOcubes 0.5",
            epilog=
            "If HOST is not specified, the game will start in local mode. Otherwise it will start in client mode, with HOST as server."
        )
        parser.add_option('-s',
                          '--server',
                          action="store_true",
                          dest="server",
                          default=False,
                          help="server mode")
        parser.add_option(
            '-p',
            '--port',
            type="int",
            dest="port",
            default=12345,
            help="set port (client & server mode) [default: %default]")
        parser.add_option(
            '-x',
            type="int",
            dest="x",
            default=5,
            help="field width (server & local mode) [default: %default]")
        parser.add_option(
            '-y',
            type="int",
            dest="y",
            default=5,
            help="field height (server & local mode) [default: %default]")
        parser.add_option('-z',
                          '--size',
                          type="int",
                          dest="size",
                          default=75,
                          help="size of one field [default: %default]")
        parser.add_option(
            '-l',
            '--player',
            type="int",
            dest="numplayers",
            default=2,
            help="number of players (local mode) [default: %default]")
        options, args = parser.parse_args()

        self.xsize, self.ysize, self.fieldsize = options.x, options.y, options.size

        if options.server:
            self.handler = server('', options.port, options.x, options.y)
        else:
            if len(args) > 0:
                self.handler = client(args[0], options.port)
                self.xsize, self.ysize = self.handler.getsize()
            else:
                self.handler = local(options.numplayers)

        self.player, self.localplayer, self.numplayers = self.handler.getopts()
        self.counts = []

        self.f = Field(self.xsize, self.ysize, self.fieldsize)
        display.set_mode(((self.xsize * (self.fieldsize + 1) - 1),
                          18 + (self.ysize * (self.fieldsize + 1) - 1)))
        display.set_caption('NATOcubes')
        surf = self.f.render()
        self.handler.surface(surf, self.player, self.fieldsize)
        display.get_surface().blit(surf, (0, 0))
        display.update()

        ev = event.wait()
        while ev.type != QUIT:
            event.clear()
            display.update()
            if self.player == self.localplayer or self.localplayer == -1:
                ev = event.wait()
                if ev.type == MOUSEBUTTONDOWN:
                    px, py = ev.pos
                    x = px / (self.fieldsize + 1)
                    y = (py - 18) / (self.fieldsize + 1)
                    if self.f.turn(self.player, x, y):
                        self.handler.onTurn(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(),
                                             self.fieldsize)
                        display.get_surface().blit(surf, (0, 0))
                        display.update()
                        if self.after_turn():
                            return
            else:
                recv = self.handler.recv_data()
                if recv and len(recv) == 2:
                    x = ord(recv[0])
                    y = ord(recv[1])
                    if self.f.turn(self.player, x, y):
                        self.handler.distribute_data(x, y)
                        surf = self.f.render(x, y)
                        self.handler.surface(surf, self.newplayer(),
                                             self.fieldsize)
                        display.get_surface().blit(surf, (0, 0))
                        display.update()
                        if self.after_turn():
                            return
                    else:
                        self.handler.failed_turn()
                elif recv == '\x00':
                    s = smallfont.render('Lost Connection', True,
                                         Color('#FFFFFF'), Color('#000000'))
                    sw, sh = s.get_size()
                    display.get_surface().blit(
                        s, (((self.xsize * self.fieldsize) - sw) / 2,
                            ((self.ysize * self.fieldsize) - sh) / 2 + 18))
                    display.update()
                    while event.wait().type != QUIT:
                        pass
                    return
                else:
                    sleep(0.1)
                ev = event.poll()
Exemplo n.º 25
0
def getPlayer(delay):

    pygame.event.clear()
    player = 0
    pygame.time.set_timer(
        pygame.USEREVENT, delay
    )  #setup timer of x seconds for someone to click their big answer button
    done = False

    while not done:
        e = event.wait()
        if e.type == USEREVENT:
            pygame.time.set_timer(pygame.USEREVENT, 0)  #turn off user timer
            done = True
        if cfg.keyboardControl == True:
            if e.type == KEYDOWN:
                if e.key == K_1:
                    if cfg.player1.excluded == False:
                        player = 1
                        done = True
                elif e.key == K_2:
                    if cfg.player2.excluded == False:
                        player = 2
                        done = True
                elif e.key == K_3:
                    if cfg.player3.excluded == False:
                        player = 3
                        done = True
                elif e.key == K_4:
                    if cfg.player4.excluded == False:
                        player = 4
                        done = True
        if cfg.bigButtonControl == True:
            if e.type == JOYBUTTONDOWN:
                print("joy button down dtected")
                if e.button == 6:  #big button on controller
                    for f in range(
                            len(cfg.players)
                    ):  #cycle through players to find who pressed their big button
                        if e.joy == cfg.players[f].controller:
                            if cfg.players[f].excluded == False:
                                player = f + 1  #might be needed to make sure correct player is passed
                                done = True

        # for event in pygame.event.get():
        #       if event.type == USEREVENT:
        #               pygame.time.set_timer(pygame.USEREVENT, 0)      #turn off user timer
        #               done = True
        #       elif event.type == KEYDOWN:
        #               if event.key==K_a:
        #                       if cfg.player1.excluded==False:
        #                               player=1
        #                               done=True
        #               if event.key==K_b:
        #                       if cfg.player2.excluded==False:
        #                               player=2
        #                               done=True
        #               if event.key==K_c:
        #                       if cfg.player3.excluded==False:
        #                               player=3
        #                               done=True
    return player
Exemplo n.º 26
0
def wait():
    ev = event.wait()
    _foo(ev)
    return ev