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
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
def send_end_move_message(self): destinatario = self.__get_oponent_handle() jugada = self.__engine.juego.get_last_human_move() if jugada != "": mesh.send_to(destinatario, "JUGADA:" + jugada.to_string()) else: #Si la jugada es igual a "" es porque no le quedaban jugadas posibles y tuvo que pasar el turno mesh.send_to(destinatario, "JUGADA:" + Coordinate(-1,-1).to_string()) self.__engine.off_play_mesh_game()
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
def send_end_move_message(self): destinatario = self.__get_oponent_handle() jugada = self.__engine.juego.get_last_human_move() if jugada != "": mesh.send_to(destinatario, "JUGADA:" + jugada.to_string()) else: #Si la jugada es igual a "" es porque no le quedaban jugadas posibles y tuvo que pasar el turno mesh.send_to(destinatario, "JUGADA:" + Coordinate(-1, -1).to_string()) self.__engine.off_play_mesh_game()
def iniciarJuego(self, iniciador): self.juego.printText("Iniciando nuevo juego...") log.debug("Iniciando juego") # inicio juego self.juego = PPT(self.screen) self.mostrarResultadoGlobal() self.jugando = True if iniciador: # Envio mensaje mesh.send_to(self.handleAmigo, "comenzarJuego")
def latency_checker(self): if self.sharer: self.latency_time_ID[self.latency_counter] = now() mesh.send_to(self.sharer, "LateReq|%s" % self.latency_counter) self.latency_counter += 1 if self.latency_counter < 10: Timer(3.5, self.latency_checker, ()).start() elif self.latency_counter < 50: Timer(6.75, self.latency_checker, ()).start() else: log.info('turning off latency checking')
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
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
def requestInstrument(self, name): "instrument selections should go through this first. To request an instrument, you need to give one up" if name in self.occupiedInstruments: log.info( 'failed instrument selection, as instrument currently occupied' ) else: if self.connected and (self.sharer != self.myself): releasename = self.selectedInstrument.name iparams = getInstrumentParameters(self.scene, releasename) requestname = name mesh.send_to( self.sharer, 'JammerRequest|%s|%s|%s' % (releasename, requestname, iparams)) else: self.reselectInstruments(name) if self.connected: mesh.broadcast('Occupied|%s' % self.occupiedInstruments)
def init_list_action(self, id_accion): if type(id_accion) == type(""): if id_accion == "reintentar_busqueda": self.send_game_message() self.__engine.change_context(LIST) elif id_accion == "volver_a_jugar": if self.__hay_oponente_esperando: self.__hay_oponente_esperando = False self.send_game_message() self.__engine.change_context(LIST) else: self.__audio.play_voice_sound("club", "esperando oponente") self.__estado = ESPERANDO_OPONENTE self.__send_waiting_message() self.__engine.change_context(PLAY) else: self.__engine.change_context(PLAY) mesh.send_to(id_accion, "PARTIDA") self.__oponente = id_accion
def init_list_action(self, id_accion): if type(id_accion) == type(""): if id_accion == "reintentar_busqueda": self.send_game_message() self.__engine.change_context(LIST) elif id_accion == "volver_a_jugar": if self.__hay_oponente_esperando: self.__hay_oponente_esperando = False self.send_game_message() self.__engine.change_context(LIST) else: self.__audio.play_voice_sound("club","esperando oponente") self.__estado = ESPERANDO_OPONENTE self.__send_waiting_message() self.__engine.change_context(PLAY) else: self.__engine.change_context(PLAY) mesh.send_to(id_accion, "PARTIDA") self.__oponente = id_accion
def iniciarJuego(self, iniciador, miTurno): self.juego.printResult("Iniciando nuevo juego...") log.debug("Iniciando juego") # inicio juego self.juego = Tateti(self.screen) self.jugando = True self.jugadas = 0 if iniciador: # TODO: Sorteo self.miTurno = True # El turno del otro if self.miTurno: tuTStr = 'False' else: tuTStr = 'True' # Envio mensaje mesh.send_to(self.handleAmigo, "configJugadores:" + tuTStr) else: self.miTurno = miTurno
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], ), )
def __send_waiting_message(self): for participante in mesh.get_participants(): if mesh.my_handle() != participante: mesh.send_to(participante, "ESPERANDO_JUEGO_NUEVO")
def stop(self): mesh.send_to(self.friend_handle, "stop:")
def finish_show_cards(self, insertion_order): mesh.send_to(self.friend_handle, "finishShowCards:" + insertion_order.__str__())
def attribute_selected(self, chosen_attribute): mesh.send_to(self.friend_handle, "attributeSelected:" + chosen_attribute.__str__())
def open_cards(self): mesh.send_to(self.friend_handle, "openCards:")
def start_net_game(self, mazo): mesh.send_to(self.friend_handle, "startedGame:" + mazo.__str__())
def receiveMessage(self, instruction, handle): if instruction.startswith("Welcome"): messages = instruction.split("|") self.sharer = handle jam_scene = messages[1] self.pending_instrument_assignment = [messages[2], messages[3]] self.select_activity_scene(jam_scene) if self.sharer != self.myself: olpcgames.ACTIVITY.J2JToolbar.deactivate_scene_change() elif instruction.startswith("Beat"): splitvals = instruction.split('|') receivedBeat = int(splitvals[1]) time_now = now() self.beatEstimator.addBeat(receivedBeat, time_now) if abs(receivedBeat - self.beatEstimator.beat_match(time_now)) > 0.17: pass else: latency = (sum(self.latency) / len(self.latency)) tmult = self.music_player.tempoMult latency = latency * 0.25 + 0.04 #this might be XO 1.0 specific beatadvance = int(ceil(latency * 1 / tmult)) scheduled_time = now() + ((beatadvance * tmult) - latency) self.music_player.Cease() self.music_player.playLoop(scheduled_time, (receivedBeat + beatadvance) % self.music_player.beatlimit) elif instruction.startswith("JammerRequest"): "In theory only the sharer ever gets this message" split = instruction.split('|') releasename = split[1] requestname = split[2] iparams = eval(split[3]) stealresult = self.stealInstrument(requestname, releasename, handle) if stealresult: setInstrumentParameters(self.scene, releasename, iparams) rqparams = getInstrumentParameters(self.scene, requestname) mesh.send_to( handle, "AuthorisedInstrument|%s|%s" % (requestname, rqparams)) mesh.broadcast('Occupied|%s' % self.occupiedInstruments) else: mesh.send_to(handle, "DeniedInstrument|%s") elif instruction.startswith("AuthorisedInstrument"): "In theory only a 'joiner' receives this message" msg = instruction.split('|') ai = msg[1] params = eval(msg[2]) setInstrumentParameters(self.scene, ai, params) self.reselectInstruments(ai) elif instruction.startswith("DeniedInstrument"): di = instruction.split('|')[1] log.info("Instrument request for %s was denied by sharer." % di) elif instruction.startswith("Occupied"): insdict = eval(instruction.split('|')[1]) self.occupiedInstruments = insdict for pni in self.PanelInstruments: if pni.name in insdict: pni.deactivate() else: pni.activate() elif instruction.startswith("LateReq"): id = instruction.split('|')[1] mesh.send_to(handle, "LateResp|%s" % id) elif instruction.startswith("LateResp"): id = int(instruction.split('|')[1]) try: t = self.latency_time_ID[id] del self.latency_time_ID[id] result = (now() - t) / 2 avglat = sum(self.latency) / len(self.latency) diffs = [(val - avglat)**2 for val in self.latency] stddev = sqrt(sum(diffs) / len(diffs)) if id == 0: del self.latency[0] self.latency.append(result) elif result > (avglat + stddev): pass elif result < (avglat - stddev) and len(self.latency) > 6: pass elif len(self.latency) > 12: del self.latency[0] self.latency.append(result) else: self.latency.append(result) except KeyError: log.info('Unmatched time ID %s' % id) else: log.debug("UNKNOWN INSTRUCTION RECEIVED :%s", instruction)
def unicast_msg(handle, msg_content): mesh.send_to(handle, msg_content)
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))
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()
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()
def __handle_message(self, jugador, mensaje): if mensaje == "PARTIDA": log.info("Me llego el mensaje: " + mensaje) #Iniciar una partida de Othello, luego enviar un mensaje confirmando esto y adjuntar al mismo la configuracion de la partida self.__audio.play_voice_sound("club", "comenzando partida") contrario = str(self._buddies[jugador].props.nick) #self.__festival.say(contrario) self.__engine.init_game(nombre="mesh") self.__video.init_game_elements(self.__engine.juego, self.__audio) mesh.send_to(jugador, "PARTIDA LISTA:" + self.__serialize_game_conf()) log.info("Envie el mensaje PARTIDA LISTA") self.__estado = JUGANDO self.__oponente = jugador elif mensaje.startswith("PARTIDA LISTA:"): log.info("Me llego el mensaje: " + mensaje.split(':')[0]) #Iniciar una partida de Othello y a continuacion enviar un mensaje para empezar a jugar conf_inicial = self.__unserialize_game_conf(mensaje.split(':')[1]) self.__engine.setup_game(conf_inicial, nombre="mesh") self.__video.init_game_elements(self.__engine.juego, self.__audio) mesh.send_to(jugador, "LISTO PARA JUGAR") self.__estado = JUGANDO elif mensaje == "LISTO PARA JUGAR": log.info("Me llego el mensaje: " + mensaje) #Activa la bandera para empezar a jugar, realiza una jugada y envia a continuacion un mensaje con la jugada que se hizo self.__engine.on_play_mesh_game() elif mensaje.startswith("JUGADA:"): log.info("Me llego el mensaje: " + mensaje) #Mensaje JUGADA:(x,y) #Actualizar el tablero, realizar una jugada y enviar un mensaje con la jugada que se hizo x, y = map(lambda i: int(i.strip('()')), mensaje.split(':')[1].split(',')) jugada = Coordinate(x, y) #if jugada.x != -1 and jugada.y != -1: #Si tanto x como y son iguales a -1 quiere decir que el contrario paso el turno porque no tenia jugadas posibles. self.__engine.juego.play( coord=jugada, audio=self.__engine.get_audio(), marcador=self.__engine.get_video().marcador, ventana=self.__engine.get_video().ventana) self.__engine.on_play_mesh_game() elif mensaje == "JUEGO?": log.info("Me llego el mensaje: " + mensaje) if self.__estado == ESPERANDO_OPONENTE: mesh.send_to(jugador, "JUEGO?_OK") else: mesh.send_to(jugador, "JUEGO?_NOPUEDO") log.info( "En este momento no estoy disponible para comenzar una partida" ) elif mensaje.startswith("JUEGO?"): log.info("Me llego el mensaje: " + mensaje) rta = mensaje.split('_')[1] if jugador in self.__contrarios: self.__conf_men_juego += 1 if rta == "NOPUEDO": self.__contrarios.remove(jugador) if self.__conf_men_juego == self.__can_contrarios: if not self.__contrarios == []: #Si ya llegaron las respuestas de todos los mensajes mostrar en una lista los oponentes disponibles self.__video.create_selection_list( titulo="LISTA DE OPONENTES") opciones = [] con = 1 for contrario in self.__contrarios: if con <= 3: opciones.append({ "descripcion": str(self._buddies[contrario].props.nick), "id": contrario, "visible": True }) else: opciones.append({ "descripcion": str(self._buddies[contrario].props.nick), "id": contrario, "visible": False }) con += 1 self.__audio.wait_sound_end(tiempo=600) self.__audio.play_voice_sound("club", "seleccione oponente") self.__video.selection_list.add_options(opciones) self.__video.show_selection_list() #self.__audio.wait_sound_end(tiempo=600) #self.__video.selection_list.read_option(self.__audio) else: self.__audio.play_voice_sound( "club", "no se encontraron oponentes") self.__video.create_selection_list() self.__video.selection_list.add_options([{ "descripcion": "Salir", "id": "salir", "visible": True }, { "descripcion": "Reintentar Busqueda", "id": "reintentar_busqueda", "visible": True }]) self.__video.show_selection_list() else: log.debug( "Todavia no me llegaron las respuestas de todos los oponentes. Men confirmados: %s. Can Contrarios: %s", self.__conf_men_juego, self.__can_contrarios) elif mensaje == "ESPERANDO_JUEGO_NUEVO": self.__hay_oponente_esperando = True elif mensaje == "SALGO": self.__video.dissapear_game_elements() self.__audio.play_voice_sound("club", "oponente abandono la partida") self.__video.create_selection_list() self.__video.selection_list.add_options([{ "descripcion": "Salir", "id": "salir", "visible": True }, { "descripcion": "Volver a Jugar", "id": "volver_a_jugar", "visible": True }]) self.__video.show_selection_list() self.__engine.change_context(LIST) self.__estado = ON elif mensaje == "HAY_ALGUIEN?": mesh.send_to(jugador, "HAY_ALGUIEN?ESTOY") elif mensaje.startswith("HAY_ALGUIEN?"): rta = mensaje.split('?')[1] self.__conf_men_juego += 1 if rta == "ESTOY": self.__audio.play_voice_sound("club", "buscando oponentes") self.send_game_message() else: if self.__conf_men_juego == self.__can_contrarios: self.__audio.play_voice_sound("club", "esperando oponente") self.__estado = ESPERANDO_OPONENTE self.__engine.change_context(PLAY) else: log.debug("Mensaje Desconocido... %s", mensaje)
def __handle_message(self, jugador, mensaje): if mensaje == "PARTIDA": log.info("Me llego el mensaje: " + mensaje) #Iniciar una partida de Othello, luego enviar un mensaje confirmando esto y adjuntar al mismo la configuracion de la partida self.__audio.play_voice_sound("club","comenzando partida") contrario = str(self._buddies[jugador].props.nick) #self.__festival.say(contrario) self.__engine.init_game(nombre="mesh") self.__video.init_game_elements(self.__engine.juego, self.__audio) mesh.send_to(jugador, "PARTIDA LISTA:" + self.__serialize_game_conf()) log.info("Envie el mensaje PARTIDA LISTA") self.__estado = JUGANDO self.__oponente = jugador elif mensaje.startswith("PARTIDA LISTA:"): log.info("Me llego el mensaje: " + mensaje.split(':')[0]) #Iniciar una partida de Othello y a continuacion enviar un mensaje para empezar a jugar conf_inicial = self.__unserialize_game_conf(mensaje.split(':')[1]) self.__engine.setup_game(conf_inicial,nombre="mesh") self.__video.init_game_elements(self.__engine.juego, self.__audio) mesh.send_to(jugador, "LISTO PARA JUGAR") self.__estado = JUGANDO elif mensaje == "LISTO PARA JUGAR": log.info("Me llego el mensaje: " + mensaje) #Activa la bandera para empezar a jugar, realiza una jugada y envia a continuacion un mensaje con la jugada que se hizo self.__engine.on_play_mesh_game() elif mensaje.startswith("JUGADA:"): log.info("Me llego el mensaje: " + mensaje) #Mensaje JUGADA:(x,y) #Actualizar el tablero, realizar una jugada y enviar un mensaje con la jugada que se hizo x, y = map(lambda i: int(i.strip('()')), mensaje.split(':')[1].split(',')) jugada = Coordinate(x,y) #if jugada.x != -1 and jugada.y != -1: #Si tanto x como y son iguales a -1 quiere decir que el contrario paso el turno porque no tenia jugadas posibles. self.__engine.juego.play(coord=jugada,audio=self.__engine.get_audio(),marcador=self.__engine.get_video().marcador,ventana=self.__engine.get_video().ventana) self.__engine.on_play_mesh_game() elif mensaje == "JUEGO?": log.info("Me llego el mensaje: " + mensaje) if self.__estado == ESPERANDO_OPONENTE: mesh.send_to(jugador, "JUEGO?_OK") else: mesh.send_to(jugador, "JUEGO?_NOPUEDO") log.info("En este momento no estoy disponible para comenzar una partida") elif mensaje.startswith("JUEGO?"): log.info("Me llego el mensaje: " + mensaje) rta = mensaje.split('_')[1] if jugador in self.__contrarios: self.__conf_men_juego += 1 if rta == "NOPUEDO": self.__contrarios.remove(jugador) if self.__conf_men_juego == self.__can_contrarios: if not self.__contrarios == []: #Si ya llegaron las respuestas de todos los mensajes mostrar en una lista los oponentes disponibles self.__video.create_selection_list(titulo="LISTA DE OPONENTES") opciones = [] con = 1 for contrario in self.__contrarios: if con <= 3: opciones.append({"descripcion":str(self._buddies[contrario].props.nick),"id":contrario,"visible":True}) else: opciones.append({"descripcion":str(self._buddies[contrario].props.nick),"id":contrario,"visible":False}) con += 1 self.__audio.wait_sound_end(tiempo=600) self.__audio.play_voice_sound("club","seleccione oponente") self.__video.selection_list.add_options(opciones) self.__video.show_selection_list() #self.__audio.wait_sound_end(tiempo=600) #self.__video.selection_list.read_option(self.__audio) else: self.__audio.play_voice_sound("club","no se encontraron oponentes") self.__video.create_selection_list() self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Reintentar Busqueda", "id":"reintentar_busqueda","visible":True}]) self.__video.show_selection_list() else: log.debug("Todavia no me llegaron las respuestas de todos los oponentes. Men confirmados: %s. Can Contrarios: %s", self.__conf_men_juego, self.__can_contrarios) elif mensaje == "ESPERANDO_JUEGO_NUEVO": self.__hay_oponente_esperando = True elif mensaje == "SALGO": self.__video.dissapear_game_elements() self.__audio.play_voice_sound("club","oponente abandono la partida") self.__video.create_selection_list() self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Volver a Jugar", "id":"volver_a_jugar","visible":True}]) self.__video.show_selection_list() self.__engine.change_context(LIST) self.__estado = ON elif mensaje == "HAY_ALGUIEN?": mesh.send_to(jugador, "HAY_ALGUIEN?ESTOY") elif mensaje.startswith("HAY_ALGUIEN?"): rta = mensaje.split('?')[1] self.__conf_men_juego += 1 if rta == "ESTOY": self.__audio.play_voice_sound("club","buscando oponentes") self.send_game_message() else: if self.__conf_men_juego == self.__can_contrarios: self.__audio.play_voice_sound("club","esperando oponente") self.__estado = ESPERANDO_OPONENTE self.__engine.change_context(PLAY) else: log.debug("Mensaje Desconocido... %s", mensaje)
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
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()
def unicast_msg(handle,msg_content): mesh.send_to(handle,msg_content)
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)