示例#1
0
    def new_event(self, event):
        if self.__estado in self.__estados_activos:
            if event.type == olpcgames.CONNECT:
                self.__tube_id = event.id
                self.__audio.play_voice_sound("club", "conexion exitosa")
                log.debug("Participantes: " + str(mesh.get_participants()))
                self.__set_up()
            elif event.type == olpcgames.PARTICIPANT_ADD:
                # create a new participant display value...
                current = self._buddies.get(event.handle)
                if not current:
                    if current is False:
                        self.remove_buddy(current)
                    else:

                        def on_buddy(buddy, event=event):
                            """Process update from the network telling us about a buddy
                            Note: this function runs in the wrapper's thread, *not* the Pygame thread!"""
                            log.info('''Newly joined buddy: %s (%s)''',
                                     buddy.props.nick, event.handle)
                            self.add_buddy(event.handle, buddy)

                        mesh.lookup_buddy(event.handle, on_buddy)
            elif event.type == olpcgames.PARTICIPANT_REMOVE:
                if not self.remove_buddy(event.handle):
                    # race condition, need to block new/upcoming elements...
                    self._buddies[event.handle] = False
            elif event.type == olpcgames.MESSAGE_UNI:
                self.__handle_message(event.handle, event.content)
            return False
        else:
            if event.type == olpcgames.MESSAGE_UNI and event.content == "HAY_ALGUIEN?":
                mesh.send_to(event.handle, "HAY_ALGUIEN?NO_ESTOY")
            return False
示例#2
0
 def new_event(self, event):
     if self.__estado in self.__estados_activos:
         if event.type == olpcgames.CONNECT:
             self.__tube_id = event.id
             self.__audio.play_voice_sound("club","conexion exitosa")
             log.debug("Participantes: "  + str(mesh.get_participants()))
             self.__set_up()
         elif event.type == olpcgames.PARTICIPANT_ADD:
             # create a new participant display value...
             current = self._buddies.get( event.handle )
             if not current:
                 if current is False:
                     self.remove_buddy( current )
                 else:
                     def on_buddy( buddy, event=event ):
                         """Process update from the network telling us about a buddy
                         Note: this function runs in the wrapper's thread, *not* the Pygame thread!"""
                         log.info( '''Newly joined buddy: %s (%s)''', buddy.props.nick, event.handle )
                         self.add_buddy( event.handle, buddy )
                     mesh.lookup_buddy( event.handle, on_buddy )
         elif event.type == olpcgames.PARTICIPANT_REMOVE:
             if not self.remove_buddy( event.handle ):
                 # race condition, need to block new/upcoming elements...
                 self._buddies[ event.handle ] = False
         elif event.type == olpcgames.MESSAGE_UNI:
             self.__handle_message(event.handle, event.content)
         return False
     else:
         if event.type == olpcgames.MESSAGE_UNI and event.content == "HAY_ALGUIEN?":
             mesh.send_to(event.handle,"HAY_ALGUIEN?NO_ESTOY")
         return False
示例#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)
    def process(self, event):
        """Process any relevant incoming network events"""
        if event.type == olpcgames.PARTICIPANT_ADD:
            # create a new participant display value...
            current = self._buddies.get(event.handle)
            if not current:
                if current is False:
                    self.removeBuddy(current)
                else:

                    def on_buddy(buddy, event=event):
                        """Process update from the network telling us about a buddy
                        
                        Note: this function runs in the wrapper's thread, *not* the Pygame thread!"""
                        self.addBuddy(event.handle, buddy)

                    mesh.lookup_buddy(event.handle, on_buddy)
        elif event.type == olpcgames.PARTICIPANT_REMOVE:
            if not self.removeBuddy(event.handle):
                # race condition, need to block new/upcoming elements...
                self._buddies[event.handle] = False
        return False  # we haven't consumed the event...
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?"
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?"
示例#7
0
文件: game.py 项目: rparrapy/maze
    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)