Exemplo n.º 1
0
 def send_game_message(self):
     self.__can_contrarios = 0
     self.__contrarios = []
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             self.__contrarios.append(participante)
             mesh.send_to(participante, "JUEGO?")
     self.__can_contrarios = len(self.__contrarios)
     self.__conf_men_juego = 0
Exemplo n.º 2
0
 def send_game_message(self):
     self.__can_contrarios = 0
     self.__contrarios = []
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             self.__contrarios.append(participante)
             mesh.send_to(participante, "JUEGO?")
     self.__can_contrarios = len(self.__contrarios)
     self.__conf_men_juego = 0
Exemplo n.º 3
0
def checkSetEN_RED():


    if(EN_RED == False):
        def on_buddy(buddy):
            global EN_RED
            EN_RED = buddy.props.nick
        
        mesh.lookup_buddy(mesh.my_handle(),on_buddy)
Exemplo n.º 4
0
 def process_event(self, event):
     if event.type==mesh.CONNECT:
         log.debug("CONNECT")
         self.connected = True
         if mesh.is_initiating():
             self.initiator = True
     elif event.type==mesh.PARTICIPANT_ADD:
         log.debug("PARTICIPANT_ADD")
         # If participant added to the application, not me
         if event.handle <> mesh.my_handle():
             self.friend_connected = True
             self.friend_handle = event.handle                
     elif event.type==mesh.PARTICIPANT_REMOVE:
         log.debug("PARTICIPANT_REMOVE")
         # If friend I am playing with stopped
         if event.handle == self.friend_handle:
             self.friend_connected = False
             self.friend_handle = None
             if self.game<>None:
                 self.game.stop()               
     elif event.type==mesh.MESSAGE_MULTI:
         log.debug("MESSAGE_MULTI")
     elif event.type==mesh.MESSAGE_UNI:
         log.debug("MESSAGE_UNI: " + event.content)
         toks = event.content.split(':')
         if toks[0]<>'startedGame' and self.game==None:
             log.error("Message received without Game opened")
         # startedGame Message
         elif toks[0]=='startedGame':            
             if self.initiator:
                 log.error("startedGame from other not initiator")
             else:
                 # Start game at receiving friend side
                 self.invitation_started = True
                 # Receive sorted cards                    
                 mazo = eval(toks[1])     
                 self.invitation_mazo = mazo
         # openCards Message
         elif toks[0]=='openCards':
             self.game.open_cards(True)
         # attributeSelected Message
         elif toks[0]=='attributeSelected':
             attr = eval(toks[1])                    
             self.game.attribute_selected(attr, True)
         # stop Message
         elif toks[0]=='stop':
             self.game.stop(True)
         # finishShowingCards Message
         elif toks[0]=='finishShowCards':
             insertion_order = eval(toks[1])
             self.game.finish_show_cards(True, insertion_order)
     else:
         return False
     return True                    
Exemplo n.º 5
0
 def __set_up(self):
     envio_mensaje = False
     self.__can_contrarios = 0
     self.__conf_men_juego = 0
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             envio_mensaje = True
             mesh.send_to(participante, "HAY_ALGUIEN?")
             self.__can_contrarios += 1
     if not envio_mensaje:
         self.__audio.play_voice_sound("club","esperando oponente")
         self.__estado = ESPERANDO_OPONENTE
Exemplo n.º 6
0
 def __set_up(self):
     envio_mensaje = False
     self.__can_contrarios = 0
     self.__conf_men_juego = 0
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             envio_mensaje = True
             mesh.send_to(participante, "HAY_ALGUIEN?")
             self.__can_contrarios += 1
     if not envio_mensaje:
         self.__audio.play_voice_sound("club", "esperando oponente")
         self.__estado = ESPERANDO_OPONENTE
Exemplo n.º 7
0
 def withBuddy(buddy):
     if event.handle == mesh.my_handle():
         log.debug("Me: %s - %s", buddy.props.nick, buddy.props.color)
         # README: this is a workaround to use an unique
         # identifier instead the nick of the buddy
         # http://dev.laptop.org/ticket/10750
         count = ""
         for i, player in enumerate(self.localplayers):
             if i > 0:
                 count = "-%d" % i
             player.uid = mesh.my_handle() + count
     else:
         log.debug("Join: %s - %s", buddy.props.nick, buddy.props.color)
         player = Player(buddy)
         player.uid = event.handle
         self.remoteplayers[event.handle] = player
         self.allplayers.append(player)
         self.allplayers.extend(player.bonusPlayers())
         self.markPointDirty(player.position)
         # send a test message to the new player
         mesh.broadcast("Welcome %s" % player.nick)
         # tell them which maze we are playing, so they can sync up
         mesh.send_to(
             event.handle,
             "maze:%d,%d,%d,%d"
             % (self.game_running_time(), self.maze.seed, self.maze.width, self.maze.height),
         )
         for player in self.localplayers:
             if not player.hidden:
                 mesh.send_to(
                     event.handle,
                     "move:%s,%d,%d,%d,%d"
                     % (
                         player.uid,
                         player.position[0],
                         player.position[1],
                         player.direction[0],
                         player.direction[1],
                     ),
                 )
Exemplo n.º 8
0
 def remove_me(self):
     if self.__estado == JUGANDO:
         mesh.send_to(self.__oponente, "SALGO")
     dbus_handle = mesh.my_handle()
     #mesh.instance(self.__tube_id).ordered_bus_names.remove(dbus_handle)
     PEvent.post(PEvent.Event(mesh.PARTICIPANT_REMOVE, handle=dbus_handle))
Exemplo n.º 9
0
 def __get_oponent_handle(self):
     for handle in self._buddies.keys():
         if mesh.my_handle() != handle:
             return handle
Exemplo n.º 10
0
 def eventAction(self, event):
     "detect events, and select action"
     if event.type == pygame.QUIT:
         self.music_player.freeze()
         self.running = False
     elif event.type == pygame.USEREVENT:
         if hasattr(event, "action"):
             if event.action.startswith("Parameter"):
                 args = event.action.split('|')
                 if args[1] == "Horizontal":
                     self.Hparam = args[2]
                     self.selectedInstrument.Touch = True
                 elif args[1] == "Vertical":
                     self.Vparam = args[2]
                     self.selectedInstrument.Touch = True
                 else:
                     raise ValueError, 'Unknown Parameter Action %s' % args
             elif event.action.startswith('Reload'):
                 #should look always like this: "Reload|name|key:mode|tempo|defaults"
                 args = event.action.split('|')
                 name = args[1]
                 key = ('E' if args[2] == 'None' else args[2])
                 mode = ('minor' if args[3] == 'None' else args[3])
                 tempo = (117 if args[4] == 'None' else int(args[4]))
                 d = eval(args[5])
                 defaults = (d if d else {})
                 self.load_scene(name, key, mode, tempo,
                                 defaults)  #this call blocks
                 if self.pending_instrument_assignment:  #now check if we are waiting to assign instruments and params.
                     self.receiveMessage(
                         "AuthorisedInstrument|%s|%s" %
                         (self.pending_instrument_assignment[0],
                          self.pending_instrument_assignment[1]),
                         self.myself)
             elif event.action.startswith("Shared"):
                 self.sharer = "Pending"
                 log.info("Sharing activity")
             elif event.action.startswith("Joined"):
                 log.info("Joined Activity")
             else:
                 log.debug("unknown parameter change: %s", event.action)
         else:
             log.debug("ignoring USEREVENT %s", event)
     elif event.type == pygame.MOUSEBUTTONDOWN:
         x, y = event.pos
         Ins = self.selectedInstrument
         if Ins.Rect.collidepoint(x, y):
             self.movingInstrument = Ins
         else:
             for Panndx in range(len(self.PanelInstruments)):
                 Pan = self.PanelInstruments[Panndx]
                 if Pan.Rect.collidepoint(x, y):
                     if Pan.active: self.requestInstrument(Pan.name)
                     break
     elif event.type == pygame.MOUSEMOTION:
         if self.movingInstrument:
             insname = self.movingInstrument.name
             self.scene.Params.setValue(
                 self.Hparam, insname,
                 rescale(event.pos[0], self.playArea.left,
                         self.playArea.right, 0, 1))
             self.scene.Params.setValue(
                 self.Vparam, insname,
                 limit(
                     rescale(event.pos[1], self.playArea.bottom,
                             self.playArea.top, 0, 1), 0, 1))
             self.movingInstrument.Touch = True
     elif event.type == pygame.MOUSEBUTTONUP:
         self.movingInstrument = False
     elif platform == 'Sugar' and event.type == mesh.CONNECT:
         log.info("""Connected to the mesh!| %s""", event)
         self.connected = True
         self.music_player.resetBeat()
     elif event.type == pygame.KEYDOWN:
         try:
             iaction = self.keycode[event.key]
             self.keyActions.append(iaction)
         except KeyError:
             pass
     elif event.type == pygame.KEYUP:
         try:
             self.keyActions.remove(self.keycode[event.key])
         except ValueError:
             pass
         except KeyError:
             pass
     elif self.connected and event.type == mesh.PARTICIPANT_ADD:
         if not self.myself: self.myself = mesh.my_handle()
         if event.handle == self.myself:
             if self.sharer == "Pending": self.sharer = self.myself
         elif len(self.occupiedInstruments) == 4:
             pass
         else:
             if self.sharer == self.myself:
                 giveupInstrument = [
                     p for p in self.PanelInstruments if p.active
                 ][0].name
                 giveupparameters = getInstrumentParameters(
                     self.scene, giveupInstrument)
                 mesh.send_to(
                     event.handle, "Welcome|%s|%s|%s" %
                     (self.scene.scene_name, giveupInstrument,
                      giveupparameters))
                 self.stealInstrument(giveupInstrument, handle=event.handle)
                 if self.connected:
                     mesh.broadcast('Occupied|%s' %
                                    self.occupiedInstruments)
                 olpcgames.ACTIVITY.J2JToolbar.deactivate_scene_change()
                 if len(self.occupiedInstruments
                        ) >= 2 and not self._syncloop_running:
                     self._syncloop_running = True
                     self.sendSync()
             else:
                 self.latency_checker()
                 log.info("Waiting to be assigned instrument from sharer")
     elif self.connected and event.type == mesh.PARTICIPANT_REMOVE:
         "return instrument to the sharer if a jammer leaves."
         try:
             relname = [
                 n for n in self.occupiedInstruments
                 if self.occupiedInstruments[n] == str(event.handle)
             ][0]
             relpanel = [
                 p for p in self.PanelInstruments if p.name == relname
             ][0]
             del self.occupiedInstruments[relname]
             relpanel.Touch = True
             if self.sharer == self.myself:
                 self.music_player.mutelist.remove(relname)
             if len(self.occupiedInstruments) == 1:
                 olpcgames.ACTIVITY.J2JToolbar.reactivate_scene_change()
             if len(self.occupiedInstruments) <= 1:
                 self._syncloop_running = False
         except IndexError:
             log.debug("Index error while removing jammer %s occ = %s" %
                       (str(event.handle), self.occupiedInstruments))
         except KeyError:
             pass
         except ValueError:
             pass
         if self.sharer == self.myself:
             mesh.broadcast('Occupied|%s' % self.occupiedInstruments)
         log.info("""Removed jammer| %s""", event)
     elif self.connected and (event.type == mesh.MESSAGE_MULTI
                              or event.type == mesh.MESSAGE_UNI):
         if event.handle == self.myself:
             pass
         else:
             self.receiveMessage(event.content, event.handle)
Exemplo n.º 11
0
    def run(self):
        running = True
        while running:
            milliseconds = self.clock.tick(25) # maximum number of frames per second
            
            # Procesamos los eventos pendientes
            # Estos eventos son los que se disparan mientras el oponente esta haciendo su jugada
            events = pygame.event.get() 
            if events:
                for event in events:
                    log.debug("Event: %s", event)
                    if event.type == pygame.QUIT:
                        running = False
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            running = False
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        if event.button == 1:
                            # Si no estaba jugando, conecto y comienzo
                            if self.estoyConectado and self.hayAmigo and not self.jugando:
                                 # inicio juego
                                self.iniciarJuego(True, None)
                    elif event.type==mesh.CONNECT :
                        log.debug("CONNECT")
                        self.estoyConectado = True
                        if mesh.is_initiating():
                            #self.miJugador = 1 # Cruz
                            self.miJugador = self.juego.X
                        else:
                            #self.miJugador = -1 # Circulo
                            self.miJugador = self.juego.O
                    elif event.type==mesh.PARTICIPANT_ADD:
                        log.debug("PARTICIPANT_ADD")
                        # Si no soy yo
                        if event.handle <> mesh.my_handle():
                            self.hayAmigo = True
                            self.handleAmigo = event.handle
                            
                            # Si soy el servidor comienzo el primer juego
                            if mesh.is_initiating():
                                self.iniciarJuego(True, None)
                    elif event.type==mesh.PARTICIPANT_REMOVE:
                        log.debug("PARTICIPANT_REMOVE")
                    elif event.type==mesh.MESSAGE_MULTI:
                        log.debug("MESSAGE_MULTI")
                    elif event.type==mesh.MESSAGE_UNI:
                        log.debug("MESSAGE_UNI: " + event.content)
                        toks = event.content.split(':')
                        if toks[0] == 'configJugadores':
                             # inicio juego
                            self.iniciarJuego(False, toks[1] == 'True')
                        elif toks[0] == 'registroJugada':
                            jugada = int(toks[1])
                            self.juego.registroJugada(jugada, self.miJugador)
                            self.miTurno = True
                            self.jugadas += 1
                            self.evaluarJuego()
                            #juego.printText("Empate")
                            #Fin chequeo de ganador

                pygame.display.flip()
                
            # Tomamos acciones
                
            if self.jugando and self.miTurno:
                jugada = self.juego.playMe(self.miJugador)
                self.miTurno = False
                self.jugadas += 1
                mesh.send_to(self.handleAmigo, "registroJugada:" + str(jugada))
                self.evaluarJuego()
Exemplo n.º 12
0
 def __send_waiting_message(self):
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             mesh.send_to(participante, "ESPERANDO_JUEGO_NUEVO")
Exemplo n.º 13
0
 def __send_waiting_message(self):
     for participante in mesh.get_participants():
         if mesh.my_handle() != participante:
             mesh.send_to(participante, "ESPERANDO_JUEGO_NUEVO")
Exemplo n.º 14
0
 def remove_me(self):
     if self.__estado == JUGANDO:
         mesh.send_to(self.__oponente, "SALGO")
     dbus_handle = mesh.my_handle()
     #mesh.instance(self.__tube_id).ordered_bus_names.remove(dbus_handle)
     PEvent.post(PEvent.Event(mesh.PARTICIPANT_REMOVE, handle=dbus_handle))
Exemplo n.º 15
0
def sharing_handler(type, handle, content):
    global buddy
    global _my_handle
    global players_in_game
    global check_withBuddy
    global _is_shared
    global _is_connected

    if type == mesh.CONNECT:
        _is_shared = True
        print "Connected to the mesh."

    elif type == mesh.PARTICIPANT_ADD:
        mesh.lookup_buddy(handle, callback=withBuddy)
        while check_withBuddy == False:
            pass

        if handle == mesh.my_handle():

            _my_handle = mesh.my_handle()
            xoOwner = presenceService.get_owner()
            player = Player(handle, xoOwner)
            players_in_game[_my_handle] = player

            print "Me:", buddy.props.nick
            check_withBuddy = False

        else:
            _is_connected = True
            print "Join:", buddy.props.nick

            player = Player(handle, buddy)
            players_in_game[handle] = player

            #remove these in real game - just for testing
            # send a test message to the new player
            broadcast_msg(['Welcome player.nick', 'get in the game'])
            # tell them which maze we are playing, so they can sync up
            unicast_msg(
                handle,
                ['Trying to send you personal msgs', 'hope you dont mind'])
            check_withBuddy = False

    elif type == mesh.PARTICIPANT_REMOVE:
        if players_in_game.has_key(handle):
            player = players_in_game[handle]
            print "Leave:", player.nick

            del players_in_game[handle]

            if handle == _my_handle:  #XXX: not sure whether if we will leave the game, we ourselves will receive the message
                _is_shared = False  #or not
                _is_connected = False
                players_in_game.clear()

            elif len(players_in_game) == 1:
                _is_connected = False

        print 'someone is removed'

    elif type == mesh.MESSAGE_MULTI:
        if handle == mesh.my_handle():
            # ignore messages from ourselves
            print 'I have broadcasted '

        elif players_in_game.has_key(handle):
            player = players_in_game[handle]
            try:

                print "got a broadcasted msg from %s" % (player.nick)
                '''
                    if content==types.IntType:
                        pass
                    if content==types.FloatType:
                        pass
                    if content==types.LongType:
                        pass
                    #if content==types.StringType:
                    #    pass
                    if content==types.DictType:
                        pass
                    if content==types.TupleType:
                        pass
                    #if content==types.ListType:
                       # pass
                    for i,v in enumerate(content):
                        print i,v
                    
                    
                    #unicast the person who has broadcasted
                    
                    for p in players_in_game.itervalues():
                        if p==player:
                            unicast_msg(p.handle, "Succeeded in unicasting")
                    '''
                for i, v in enumerate(content):
                    print i, v
                messageResponderBroadcast(handle, player.nick, content)

            except:
                print "Error handling message: %s\n%s" % (type, sys.exc_info())

        else:
            print "Message from unknown buddy?"

    elif type == mesh.MESSAGE_UNI:
        if handle == mesh.my_handle():
            # ignore messages from ourselves
            print 'I have unicasted myself,might be of trouble'

        elif players_in_game.has_key(handle):
            player = players_in_game[handle]
            try:

                print "got a unicasted msg from %s" % (player.nick)

                if content == types.IntType:
                    pass
                if content == types.FloatType:
                    pass
                if content == types.LongType:
                    pass
                #if content==types.StringType:
                #   pass
                if content == types.DictType:
                    pass
                if content == types.TupleType:
                    pass
            #  if content==types.ListType:
            #     pass
                for i, v in enumerate(content):
                    print i, v

                messageResponderUnicast(handle, player.nick, content)

            except:
                print "Error handling message: %s\n%s" % (type, sys.exc_info())

        else:
            print "Message from unknown buddy?"
Exemplo n.º 16
0
 def run(self):
     running = True
     while running:
         milliseconds = self.clock.tick(25) # maximum number of frames per second
         
         # Event-management loop with support for pausing after X seconds (20 here)
         events = pausescreen.get_events()
         # Now the main event-processing loop
         if events:
             for event in events:
                 log.debug( "Event: %s", event )
                 if event.type == pygame.QUIT:
                     running = False
                 elif event.type == pygame.KEYDOWN:
                     if event.key == pygame.K_ESCAPE:
                         running = False
                 elif event.type == pygame.MOUSEBUTTONDOWN:
                     if event.button == 1:
                         # Si no estaba jugando, conecto y comienzo
                         if self.estoyConectado and self.hayAmigo and not self.jugando:
                              # inicio juego
                             self.iniciarJuego(True, None)
                 elif event.type==mesh.CONNECT :
                     log.debug("CONNECT")
                     self.estoyConectado = True
                     if mesh.is_initiating():
                         self.miJugador = 1 # Cruz
                     else:
                         self.miJugador = -1 # Circulo
                 elif event.type==mesh.PARTICIPANT_ADD:
                     log.debug("PARTICIPANT_ADD")
                     # Si no soy yo
                     if event.handle <> mesh.my_handle():
                         self.hayAmigo = True
                         self.handleAmigo = event.handle
                         
                         # Si soy el servidor comienzo el primer juego
                         if mesh.is_initiating():
                             self.iniciarJuego(True, None)
                 elif event.type==mesh.PARTICIPANT_REMOVE:
                     log.debug("PARTICIPANT_REMOVE")
                 elif event.type==mesh.MESSAGE_MULTI:
                     log.debug("MESSAGE_MULTI")
                 elif event.type==mesh.MESSAGE_UNI:
                     log.debug("MESSAGE_UNI: " + event.content)
                     toks = event.content.split(':')
                     if toks[0] == 'configJugadores':
                          # inicio juego
                         self.iniciarJuego(False, toks[1] == 'True')
                     elif toks[0] == 'registroJugada':
                         jugada = int(toks[1])
                         self.juego.registroJugada(jugada, self.miJugador)
                         self.miTurno = True
                         self.jugadas += 1
                         self.evaluarJuego()
             			#juego.printResult("Empate")
             			#Fin chequeo de ganador
 
             pygame.display.flip()
             
         # Tomamos acciones
         
         if self.jugando and self.miTurno:
             jugada = self.juego.playMe(self.miJugador)
             self.miTurno = False
             self.jugadas += 1
             mesh.send_to(self.handleAmigo, "registroJugada:" + str(jugada))
             self.evaluarJuego()
Exemplo n.º 17
0
    def processEvent(self, event):
        """Process a single pygame event.  This includes keystrokes
        as well as multiplayer events from the mesh."""
        if event.type == pygame.QUIT:
            self.running = False
        elif event.type == pygame.KEYDOWN:
            if event.key in (pygame.K_PLUS, pygame.K_EQUALS):
                self.harder()
            elif event.key == pygame.K_MINUS:
                self.easier()
            elif event.key in self.arrowkeys:
                playernum, direction = self.arrowkeys[event.key]
                player = self.localplayers[playernum]
                player.hidden = False

                if direction == pygame.K_UP:
                    player.direction = (0, -1)
                elif direction == pygame.K_DOWN:
                    player.direction = (0, 1)
                elif direction == pygame.K_LEFT:
                    player.direction = (-1, 0)
                elif direction == pygame.K_RIGHT:
                    player.direction = (1, 0)

                if len(self.remoteplayers) > 0:
                    mesh.broadcast(
                        "move:%s,%d,%d,%d,%d"
                        % (player.uid, player.position[0], player.position[1], player.direction[0], player.direction[1])
                    )
        elif event.type == pygame.KEYUP:
            pass
        elif event.type == pygame.MOUSEMOTION:
            pass
        elif event.type == pygame.MOUSEBUTTONDOWN:
            self.mouse_in_use = 1
            self.prev_mouse_pos = pygame.mouse.get_pos()

        elif event.type == pygame.MOUSEBUTTONUP:
            if self.mouse_in_use:
                new_mouse_pos = pygame.mouse.get_pos()
                mouse_movement = (new_mouse_pos[0] - self.prev_mouse_pos[0], new_mouse_pos[1] - self.prev_mouse_pos[1])

                if (abs(mouse_movement[0]) > 10) or (abs(mouse_movement[1]) > 10):
                    player = self.localplayers[0]
                    player.hidden = False
                    # x movement larger
                    if abs(mouse_movement[0]) > abs(mouse_movement[1]):
                        # direction == pygame.K_RIGHT
                        if mouse_movement[0] > 0:
                            player.direction = (1, 0)
                        else:
                            # direction == pygame.K_LEFT
                            player.direction = (-1, 0)
                    else:
                        if mouse_movement[1] < 0:
                            # direction == pygame.K_UP
                            player.direction = (0, -1)
                        else:  # direction == pygame.K_DOWN
                            player.direction = (0, 1)

                    if len(self.remoteplayers) > 0:
                        mesh.broadcast(
                            "move:%s,%d,%d,%d,%d"
                            % (
                                player.nick,
                                player.position[0],
                                player.position[1],
                                player.direction[0],
                                player.direction[1],
                            )
                        )

            self.mouse_in_use = 0

        elif event.type == mesh.CONNECT:
            log.debug("Connected to the mesh")

        elif event.type == mesh.PARTICIPANT_ADD:
            log.debug("mesh.PARTICIPANT_ADD")

            def withBuddy(buddy):
                if event.handle == mesh.my_handle():
                    log.debug("Me: %s - %s", buddy.props.nick, buddy.props.color)
                    # README: this is a workaround to use an unique
                    # identifier instead the nick of the buddy
                    # http://dev.laptop.org/ticket/10750
                    count = ""
                    for i, player in enumerate(self.localplayers):
                        if i > 0:
                            count = "-%d" % i
                        player.uid = mesh.my_handle() + count
                else:
                    log.debug("Join: %s - %s", buddy.props.nick, buddy.props.color)
                    player = Player(buddy)
                    player.uid = event.handle
                    self.remoteplayers[event.handle] = player
                    self.allplayers.append(player)
                    self.allplayers.extend(player.bonusPlayers())
                    self.markPointDirty(player.position)
                    # send a test message to the new player
                    mesh.broadcast("Welcome %s" % player.nick)
                    # tell them which maze we are playing, so they can sync up
                    mesh.send_to(
                        event.handle,
                        "maze:%d,%d,%d,%d"
                        % (self.game_running_time(), self.maze.seed, self.maze.width, self.maze.height),
                    )
                    for player in self.localplayers:
                        if not player.hidden:
                            mesh.send_to(
                                event.handle,
                                "move:%s,%d,%d,%d,%d"
                                % (
                                    player.uid,
                                    player.position[0],
                                    player.position[1],
                                    player.direction[0],
                                    player.direction[1],
                                ),
                            )

            mesh.lookup_buddy(event.handle, callback=withBuddy)
        elif event.type == mesh.PARTICIPANT_REMOVE:
            log.debug("mesh.PARTICIPANT_REMOVE")
            if event.handle in self.remoteplayers:
                player = self.remoteplayers[event.handle]
                log.debug("Leave: %s", player.nick)
                self.markPointDirty(player.position)
                self.allplayers.remove(player)
                for bonusplayer in player.bonusPlayers():
                    self.markPointDirty(bonusplayer.position)
                    self.allplayers.remove(bonusplayer)
                del self.remoteplayers[event.handle]
        elif event.type == mesh.MESSAGE_UNI or event.type == mesh.MESSAGE_MULTI:
            log.debug("mesh.MESSAGE_UNI or mesh.MESSAGE_MULTI")
            if event.handle == mesh.my_handle():
                # ignore messages from ourself
                pass
            elif event.handle in self.remoteplayers:
                player = self.remoteplayers[event.handle]
                try:
                    self.handleMessage(player, event.content)
                except:
                    log.debug("Error handling message: %s\n%s", event, sys.exc_info())
            else:
                log.debug("Message from unknown buddy?")

        elif event.type == pygame.USEREVENT:
            # process our buttons
            if hasattr(event, "action") and event.action == "harder_button":
                self.harder()
            elif hasattr(event, "action") and event.action == "easier_button":
                self.easier()
            # process file save / restore events
            elif event.code == olpcgames.FILE_READ_REQUEST:
                log.debug("Loading the state of the game...")
                state = json.loads(event.metadata["state"])
                log.debug("Loaded data: %s", state)
                self.maze = Maze(**state)
                self.reset()
                return True
            elif event.code == olpcgames.FILE_WRITE_REQUEST:
                log.debug("Saving the state of the game...")
                data = {"seed": self.maze.seed, "width": self.maze.width, "height": self.maze.height}
                log.debug("Saving data: %s", data)
                event.metadata["state"] = json.dumps(data)
                f = open(event.filename, "w")
                try:
                    f.write(str(time.time()))
                finally:
                    f.close()
                log.debug("Done saving.")
                return True
        else:
            log.debug("Unknown event: %r", event)
Exemplo n.º 18
0
    def processEvent(self, event):
        """Process a single pygame event.  This includes keystrokes
        as well as multiplayer events from the mesh."""
        if event.type == pygame.QUIT:
            self.running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.running = False
            elif event.key in (pygame.K_PLUS, pygame.K_EQUALS):
                self.harder()
            elif event.key == pygame.K_MINUS:
                self.easier()
            elif self.arrowkeys.has_key(event.key):
                playernum, direction = self.arrowkeys[event.key]
                player = self.localplayers[playernum]
                player.hidden = False

                if direction == pygame.K_UP:
                    player.direction = (0, -1)
                elif direction == pygame.K_DOWN:
                    player.direction = (0, 1)
                elif direction == pygame.K_LEFT:
                    player.direction = (-1, 0)
                elif direction == pygame.K_RIGHT:
                    player.direction = (1, 0)

                if len(self.remoteplayers) > 0:
                    mesh.broadcast(
                        "move:%s,%d,%d,%d,%d" %
                        (player.nick, player.position[0], player.position[1],
                         player.direction[0], player.direction[1]))
        elif event.type == pygame.KEYUP:
            pass
        elif event.type in (pygame.MOUSEMOTION, pygame.MOUSEBUTTONDOWN,
                            pygame.MOUSEBUTTONUP):
            pass
        elif event.type == mesh.CONNECT:
            print "Connected to the mesh."
        elif event.type == mesh.PARTICIPANT_ADD:
            buddy = mesh.get_buddy(event.handle)
            if event.handle == mesh.my_handle():
                print "Me:", buddy.props.nick, buddy.props.color
            else:
                print "Join:", buddy.props.nick, buddy.props.color
                player = Player(buddy)
                self.remoteplayers[event.handle] = player
                self.allplayers.append(player)
                self.allplayers.extend(player.bonusPlayers())
                self.markPointDirty(player.position)
                # send a test message to the new player
                mesh.broadcast("Welcome %s" % player.nick)
                # tell them which maze we are playing, so they can sync up
                mesh.send_to(
                    event.handle, "maze:%d,%d,%d,%d" %
                    (self.game_running_time(), self.maze.seed, self.maze.width,
                     self.maze.height))
                for player in self.localplayers:
                    if not player.hidden:
                        mesh.send_to(
                            event.handle, "move:%s,%d,%d,%d,%d" %
                            (player.nick, player.position[0],
                             player.position[1], player.direction[0],
                             player.direction[1]))
        elif event.type == mesh.PARTICIPANT_REMOVE:
            if self.remoteplayers.has_key(event.handle):
                player = self.remoteplayers[event.handle]
                print "Leave:", player.nick
                self.markPointDirty(player.position)
                self.allplayers.remove(player)
                for bonusplayer in player.bonusPlayers():
                    self.markPointDirty(bonusplayer.position)
                    self.allplayers.remove(bonusplayer)
                del self.remoteplayers[event.handle]
        elif event.type == mesh.MESSAGE_UNI or event.type == mesh.MESSAGE_MULTI:
            buddy = mesh.get_buddy(event.handle)
            #print "Message from %s / %s: %s" % (buddy.props.nick, event.handle, event.content)
            if event.handle == mesh.my_handle():
                # ignore messages from ourself
                pass
            elif self.remoteplayers.has_key(event.handle):
                player = self.remoteplayers[event.handle]
                try:
                    self.handleMessage(player, event.content)
                except:
                    print "Error handling message: %s\n%s" % (event,
                                                              sys.exc_info())
            else:
                print "Message from unknown buddy?"
        else:
            print "Unknown event:", event
Exemplo n.º 19
0
 def __get_oponent_handle(self):
     for handle in self._buddies.keys():
         if mesh.my_handle() != handle:
             return handle
Exemplo n.º 20
0
def sharing_handler(type,handle,content):
    global buddy
    global _my_handle
    global players_in_game
    global check_withBuddy
    global _is_shared
    global _is_connected
    
    if type == mesh.CONNECT:
            _is_shared=True
            print "Connected to the mesh."
            
    elif type == mesh.PARTICIPANT_ADD:
            mesh.lookup_buddy(handle,callback=withBuddy )
            while check_withBuddy==False:
                pass
            
            if handle == mesh.my_handle():
                
                _my_handle=mesh.my_handle()
                xoOwner = presenceService.get_owner()
                player=Player(handle,xoOwner)
                players_in_game[_my_handle]=player
                
                print "Me:", buddy.props.nick
                check_withBuddy=False
                
                
            else:
                _is_connected=True
                print "Join:", buddy.props.nick
                

                player = Player(handle,buddy)
                players_in_game[handle] = player
                
                #remove these in real game - just for testing
                # send a test message to the new player
                broadcast_msg(['Welcome player.nick' ,'get in the game'])
                # tell them which maze we are playing, so they can sync up
                unicast_msg(handle, ['Trying to send you personal msgs','hope you dont mind'])
                check_withBuddy=False

    elif type == mesh.PARTICIPANT_REMOVE:
            if players_in_game.has_key(handle):
                player = players_in_game[handle]
                print "Leave:", player.nick
                
                
                del players_in_game[handle]

                if handle==_my_handle:                       #XXX: not sure whether if we will leave the game, we ourselves will receive the message 
                    _is_shared=False                               #or not
                    _is_connected=False
                    players_in_game.clear()
                    
                elif len(players_in_game)==1:
                    _is_connected=False

            print 'someone is removed'


    elif type == mesh.MESSAGE_MULTI:
        if handle == mesh.my_handle():
                # ignore messages from ourselves
                print 'I have broadcasted '

        elif players_in_game.has_key(handle):
                player = players_in_game[handle]
                try:
                    
                    
                    print "got a broadcasted msg from %s" % (player.nick)
                    '''
                    if content==types.IntType:
                        pass
                    if content==types.FloatType:
                        pass
                    if content==types.LongType:
                        pass
                    #if content==types.StringType:
                    #    pass
                    if content==types.DictType:
                        pass
                    if content==types.TupleType:
                        pass
                    #if content==types.ListType:
                       # pass
                    for i,v in enumerate(content):
                        print i,v
                    
                    
                    #unicast the person who has broadcasted
                    
                    for p in players_in_game.itervalues():
                        if p==player:
                            unicast_msg(p.handle, "Succeeded in unicasting")
                    '''
                    for i,v in enumerate(content):
                        print i,v
                    messageResponderBroadcast(handle,player.nick,content)
                            
                except:
                    print "Error handling message: %s\n%s" % (type, sys.exc_info())
                    
        else:
                print "Message from unknown buddy?"

    elif type ==mesh.MESSAGE_UNI:
        if handle == mesh.my_handle():
                # ignore messages from ourselves
                print 'I have unicasted myself,might be of trouble'

        elif players_in_game.has_key(handle):
                player = players_in_game[handle]
                try:
                    
                    print "got a unicasted msg from %s" % (player.nick)

                    if content==types.IntType:
                        pass
                    if content==types.FloatType:
                        pass
                    if content==types.LongType:
                        pass
                    #if content==types.StringType:
                     #   pass
                    if content==types.DictType:
                        pass
                    if content==types.TupleType:
                        pass
                  #  if content==types.ListType:
                   #     pass
                    for i,v in enumerate(content):
                        print i,v

                    messageResponderUnicast(handle,player.nick,content)
                               
                except:
                    print "Error handling message: %s\n%s" % (type, sys.exc_info())
                    
        else:
                print "Message from unknown buddy?"
Exemplo n.º 21
0
    def run(self):
        running = True
        while running:
            milliseconds = self.clock.tick(25) # maximum number of frames per second
            
            # Procesamos los eventos pendientes
            # Estos eventos son los que se disparan mientras el oponente esta haciendo su jugada
            events = pygame.event.get() 
            if events:
                for event in events:
#                    log.debug("Event: %s", event)
                    if event.type == pygame.QUIT:
                        running = False
                    elif event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            running = False
                        elif self.jugando:
                            if event.key == pygame.K_r:                   
                                log.debug("PRESIONO Roca")            
                                self.juego.registroJugada(self.juego.Roca, self.juego.Yo)
                                mesh.send_to(self.handleAmigo, "registroJugada:" + str(self.juego.Roca))
                                self.evaluarJuego()
                            elif event.key == pygame.K_p:                   
                                log.debug("PRESIONO Papel")            
                                self.juego.registroJugada(self.juego.Papel, self.juego.Yo)
                                mesh.send_to(self.handleAmigo, "registroJugada:" + str(self.juego.Papel))
                                self.evaluarJuego()
                            elif event.key == pygame.K_t:                   
                                log.debug("PRESIONO tijera")            
                                self.juego.registroJugada(self.juego.Tijera, self.juego.Yo)
                                mesh.send_to(self.handleAmigo, "registroJugada:" + str(self.juego.Tijera))
                                self.evaluarJuego()
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        if event.button == 1:
                            # Si no estaba jugando, conecto y comienzo
                            if self.estoyConectado and self.hayAmigo and not self.jugando:
                                 # inicio juego
                                self.iniciarJuego(True)
                    elif event.type==mesh.CONNECT :
                        log.debug("CONNECT")
                        self.estoyConectado = True
                    elif event.type==mesh.PARTICIPANT_ADD:
                        log.debug("PARTICIPANT_ADD")
                        # Si no soy yo
                        if event.handle <> mesh.my_handle():
                            self.hayAmigo = True
                            self.handleAmigo = event.handle
                            
                            # Si soy el servidor comienzo el primer juego
                            if mesh.is_initiating():
                                self.iniciarJuego(True)
                    elif event.type==mesh.PARTICIPANT_REMOVE:
                        log.debug("PARTICIPANT_REMOVE")
                    elif event.type==mesh.MESSAGE_MULTI:
                        log.debug("MESSAGE_MULTI")
                    elif event.type==mesh.MESSAGE_UNI:
                        log.debug("MESSAGE_UNI: " + event.content)
                        toks = event.content.split(':')
                        if toks[0] == 'comenzarJuego':
                             # inicio juego
                            self.iniciarJuego(False)
                        elif toks[0] == 'registroJugada':
                            jugada = int(toks[1])
                            self.juego.registroJugada(jugada, self.juego.Oponente)
                            self.evaluarJuego()
                            #juego.printText("Empate")
                            #Fin chequeo de ganador
                    elif event.type==self.timereventid:
                        pygame.time.set_timer(self.timereventid, 0)
                        self.evaluarJuegoFin()
                        

                pygame.display.flip()