diff options
author | Jorge Saldivar <jorge@jorge-laptop.(none)> | 2010-03-28 03:12:31 (GMT) |
---|---|---|
committer | Jorge Saldivar <jorge@jorge-laptop.(none)> | 2010-03-28 03:12:31 (GMT) |
commit | 21b6968e6f9900dfedcb313ae9a6dea45aa231fa (patch) | |
tree | 1179a87e7f6128bd775a70156e1f3fb3805c5b01 /src |
Commit inicial
Diffstat (limited to 'src')
74 files changed, 9201 insertions, 0 deletions
diff --git a/src/_xml/__init__.py b/src/_xml/__init__.py new file mode 100755 index 0000000..e69de29 --- /dev/null +++ b/src/_xml/__init__.py diff --git a/src/_xml/__init__.pyc b/src/_xml/__init__.pyc Binary files differnew file mode 100644 index 0000000..b7cd608 --- /dev/null +++ b/src/_xml/__init__.pyc diff --git a/src/_xml/element.py b/src/_xml/element.py new file mode 100755 index 0000000..33bff97 --- /dev/null +++ b/src/_xml/element.py @@ -0,0 +1,85 @@ +""" Modulo que contiene la defincion de la Clase Element
+"""
+class Element:
+ """La Clase Element se utiliza para almacenar los datos de un
+ elemento XML.
+ """
+ def __init__(self):
+ """Constructor de la clase, inicializa las propiedas privadas:
+ nombre: almacena el nombre del elemento
+ atributos: almacena el o los atributos que contiene el elemento
+ texto: diccionario que almacena el texto contenido entre las etiquetas
+ de inicio y fin de un elemento. El diccionario contiene dos valores,
+ repr para guardar el texto con su codificacion original y str para guardar
+ el texto para guardar el texto convertido a string.
+ """
+ self.__nombre = ""
+ self.__atributos = {}
+ self.__texto = {'repr':'','str':''}
+
+ def clear(self):
+ """ Metodo que se utiliza para cerar las propiedades privadas de la
+ clase
+ """
+ self.__nombre = ""
+ self.__texto['repr'] = ''
+ self.__texto['str'] = ''
+
+ def set_name(self, nombre):
+ """Setter de la propiedad privada nombre"""
+ self.__nombre = nombre
+
+ def set_text(self, texto):
+ """Setter de la propiedad privada texto"""
+ self.__texto['repr'] = repr(texto)
+ texto = texto.encode('iso-8859-1')
+ self.__texto['str'] = str(texto)
+
+ def get_text(self, key):
+ """Getter de la propiedad privada texto"""
+ return self.__texto[key]
+
+ def get_name(self):
+ """Getter de la propiedad privada nombre"""
+ return self.__nombre
+
+ def get_attributes(self):
+ """Getter de la propiedad privada atributos, el cual devuelve todos
+ los atributos del elemento
+ """
+ return self.__atributos
+
+ def get_attribute(self, atributo):
+ """Getter de la propiedad privada atributos, el cual devuelve solo
+ el atributo requerido en el parametro
+ """
+ return self.__atributos[atributo]
+
+ def set_attributes(self, atributos):
+ """Setter de la propiedad privada atributos, recibe un diccionario
+ de atributos y los copia a la propiedad atributos de la clase
+ """
+ self.__atributos = atributos.copy()
+
+ def has_attribute(self, atributo):
+ """Metodo que se utiliza para conocer si un elemento tiene un atributo
+ determinado pasado como parametro. Retorna True o False dependiendo de
+ si contiene o no el atributo pasado como parametro.
+ """
+ return atributo in self.__atributos
+
+ def is_empty(self):
+ """Metodo que se utiliza conocer si un elemento en particular esta vacio,
+ para ello se evalua la propiedad nombre y dependiendo de esto se retorna
+ True o False.
+ """
+ if self.__nombre == "":
+ return True
+ else:
+ return False
+
+ def __str__(self):
+ """Metodo que se utiliza cuando se desea imprimir como string
+ una instancia de la clase element
+ """
+ return "Nombre: " + self.__nombre + "\nAtributos: " + str(self.__atributos) + "\nTexto: " + self.__texto['str']
diff --git a/src/_xml/element.pyc b/src/_xml/element.pyc Binary files differnew file mode 100644 index 0000000..66eaa4c --- /dev/null +++ b/src/_xml/element.pyc diff --git a/src/_xml/parser.py b/src/_xml/parser.py new file mode 100755 index 0000000..819eb0d --- /dev/null +++ b/src/_xml/parser.py @@ -0,0 +1,255 @@ +""" Modulo que contiene un wrapper de la clase expat del modulo xml de la
+ libreria de python.
+"""
+from xml.parsers import expat
+from element import Element
+
+class Parser:
+ """ Clase Parser
+
+ Esta clase se utiliza para leer los archivos xml, tiene como base
+ la clase expat del modulo xml de la libreria de python a la cual se le
+ agregaron algunas funcionalidades
+ """
+ def __init__(self):
+ """Constructor de la clase.
+
+ Inicializa las propiedades privadas:
+ -parser: la cual contiene el parser expat
+ -buscando: propiedad que se utiliza en caso de que no se quiera leer
+ todo el archivo xml y solo se necesita buscar un elemento en particular
+ -nombre_buscar: se utiliza para almacenar el nombre del elemento a buscar
+ en caso que no se quiera leer todo el archivo XML sino buscar un elemento
+ en particular.
+ -encontrado: se utiliza como bandera para indicar si ya fue o no encontrado
+ un elemento en particular.
+ -elemento: propiedad en la cual se almacena una instancia de la clase element.
+ -vec_elementos: vector en el cual se almacenan los elementos que contiene el archivo XML.
+ -attrs: dicccionario en el cual se almacenan los atributos del elemento actual que se
+ esta leyendo.
+ """
+ self.__parser = expat.ParserCreate()
+ self.__parser.StartElementHandler = self.__start_element
+ self.__parser.EndElementHandler = self.__end_element
+ self.__parser.CharacterDataHandler = self.__char_data
+ self.__buscando = False
+ self.__nombre_buscar = ""
+ self.__encontrado = False
+ self.__elemento = Element()
+ self.__vec_elementos = []
+ self.__attrs = {}
+
+ def __start_element(self, name, attrs):
+ """Wrapper del metodo del mismo nombre de la clase expat.
+
+ La diferencia con el original es que permite dejar de leer el
+ archivo una vez encontrado un elemento en particular.
+ """
+ if self.__buscando:
+ if name == self.__nombre_buscar:
+ self.__encontrado = True
+ self.__elemento.set_name(repr(name))
+ self.__elemento.set_attributes(attrs)
+ elif self.__encontrado:
+ self.__buscando = False
+
+ def __end_element(self, name):
+ """Wrapper del metodo del mismo nombre de la clase expat.
+
+ La diferencia con el original es que permite dejar de leer el
+ archivo una vez encontrado un elemento en particular.
+ """
+ if name == self.__nombre_buscar and self.__encontrado:
+ self.__buscando = False
+
+ def __char_data(self, data):
+ """Wrapper del metodo del mismo nombre de la clase expat.
+
+ La diferencia con el original es que permite dejar de leer el
+ archivo una vez encontrado un elemento en particular.
+ """
+ if self.__buscando and self.__encontrado:
+ self.__elemento.set_text(data)
+ self.__buscando = False
+
+ def __start_element_attributes(self, name, attrs):
+ """ Metodo para buscar un elemento en particular teniendo en cuenta sus atributos.
+
+ Si encuentra el elemento pedido almacena su nombre y sus atributos en
+ las propiedades respectivas, luego setea la bandera encontrado a True.
+ Si ya encontro el elemento, la siguiente vez que lea un elemento
+ nuevo del archivo XML setea la bandera buscado a False para terminar
+ con la busqueda.
+ Parametros:
+ -name: nombre del elemento a buscar.
+ -attrs: atributos por los cuales buscar el elemento.
+ """
+ if self.__buscando:
+ if name == self.__nombre_buscar and attrs == self.__attrs:
+ self.__encontrado = True
+ self.__elemento.set_name(repr(name))
+ self.__elemento.set_attributes(attrs)
+ elif self.__encontrado:
+ self.__buscando = False
+
+ def __start_element_childs(self, name, attrs):
+ """ Metodo que se utiliza cuando se desea encontrar todos los hijos de un
+ elemento en particular.
+
+ Basicamente su funcionamiento consiste en buscar el elemento padre, una
+ vez encontrado almacena todos sus elementos hijos en la propiedad vec_elementos.
+ Paramentros:
+ -name: nombre del elemento padre.
+ -attrs: atributos del elemento padre (se utiliza solo a modo de compatibilidad con el parser expat)
+ """
+ if name == self.__nombre_buscar:
+ self.__encontre_padre = True
+ elif self.__encontre_padre:
+ elem = Element()
+ elem.set_name(name)
+ elem.set_attributes(attrs)
+ self.__vec_elementos.append(elem)
+
+ def __char_data_childs(self, data):
+ """ Metodo que se utiliza cuando se desea encontrar todos los hijos de un
+ elemento en particular.
+
+ Su funcionamiento consiste en guardar el texto entre etiquetas de
+ cada uno de los hijos del elemento en particular.
+ Parametros:
+ -data: texto entre las etiquetas (el parse expat se encarga de proporcionar este parametro)
+ """
+ if not self.__vec_elementos == []:
+ elem = self.__vec_elementos.pop()
+ #Solamente si todavia no guarde el texto lo guardo
+ if elem.get_text('str') == "":
+ elem.set_text(data)
+ self.__vec_elementos.append(elem)
+
+ def __end_element_childs(self, name):
+ """ Metodo que se utiliza cuando se desea encontrar todos los hijos de un
+ elemento en particular.
+
+ Su funcionalidad consiste en setear a False la bandera encontre_padre de forma tal
+ para indicar al metodo start_element_childs que se cerro el elemento padre.
+ """
+ if name == self.__nombre_buscar:
+ self.__encontre_padre = False
+
+ def find_element(self, elemento, xml):
+ """ Metodo que se utiliza para buscar un elemento en particular sin tener en cuenta sus atributos.
+
+ Parametros:
+ -elemento: elemento en particular a buscar.
+ -xml: archivo o string xml donde debe buscarse el elemento.
+ Retorno:
+ Objeto de la clase Element
+ """
+ self.__buscando = True
+ self.__nombre_buscar = elemento
+ self.__encontrado = False
+ self.__elemento.clear()
+ self.parse(xml)
+ #if self.__encontrado:
+ # print str(self.__elemento)
+ return self.__elemento
+
+ def find_element_attribute(self, elemento, attrs, xml):
+ """ Metodo que utiliza para buscar un elemento teniendo en cuenta los atributos del mismo.
+
+ Parametros:
+ -elemento: elemento en particular a buscar.
+ -attrs: atributos que debe contener el elemento a buscar.
+ -xml: archivo o string xml donde debe buscarse el elemento.
+ Retorno:
+ Objeto de la clase Element
+ """
+ #print "AHORA VOY A BUSCAR " + str(elemento)
+ self.__buscando = True
+ self.__nombre_buscar = elemento
+ self.__attrs = attrs
+ self.__encontrado = False
+ self.__elemento.clear()
+ self.__parser.StartElementHandler = self.__start_element_attributes
+ self.parse(xml)
+ #if self.__encontrado:
+ # print str(self.__elemento)
+ return self.__elemento
+
+ def find_child_element(self, padre, xml):
+ """ Metodo que se utiliza para buscar los hijos de un elemento en particular.
+
+ Parametros:
+ -padre: nombre del elemento padre.
+ -xml: archivo o string xml donde debe realizarse la buscqueda.
+ Retorno:
+ Lista de objetos de la clase Element
+ """
+ self.__encontre_padre = False
+ self.__nombre_buscar = padre
+ #Cambio las funciones de parseo y utilizo unas especiales para buscar hijos de los elementos
+ self.__parser.StartElementHandler = self.__start_element_childs
+ self.__parser.EndElementHandler = self.__end_element_childs
+ self.__parser.CharacterDataHandler = self.__char_data_childs
+ self.parse(xml)
+ #for e in self.__vec_elementos:
+ # print str(e)
+ return self.__vec_elementos
+
+ def xml_has_element(self, elemento, xml):
+ """Metodo que se utiliza para conocer si un archivo xml determinado
+ contiene un elemento en particular.
+
+ Paramentros:
+ -elemento: elemento a buscar.
+ -xml: archivo o string xml sobre el cual se debe realizar la busqueda.
+ Retorno:
+ -True: si se encontro.
+ -False: en caso de que no se encuentre.
+ """
+ self.__buscando = True
+ self.__nombre_buscar = elemento
+ self.__encontrado = False
+ self.parse(xml)
+ return self.__encontrado
+
+ def parse(self, xml):
+ """ Metodo que se utiliza antes de comenzar a parsear el xml.
+
+ Su funcion consiste en transformar el parametro xml a string
+ si es que el que se recibe no es de ese tipo.
+ Paramentros:
+ - xml: archivo o string xml.
+ """
+ if type(xml) == file:
+ xml = xml.read()
+ xml = unicode(xml,"latin-1").encode('iso-8859-1')
+ try:
+ self.__read_xml(xml)
+ except Exception, e:
+ print e
+
+ def __read_xml(self, xml):
+ """ Metodo que se utiliza para comenzar a leer el xml.
+
+ Paramentros:
+ -xml: string con el formato xml.
+ """
+ self.__parser.Parse(xml,0)
+
+ def close(self):
+ """ Metodo que se utiliza para cerrar el parser xml """
+ self.__parser.Parse("", 1)
+ del self.__parser
+
+if __name__ == "__main__":
+ v = []
+
+ p = Parser()
+
+ f = open("../../data/games.xml")
+
+ v = p.find_child_element("games",f)
+
+ p.close()
+
diff --git a/src/_xml/parser.pyc b/src/_xml/parser.pyc Binary files differnew file mode 100644 index 0000000..da683ea --- /dev/null +++ b/src/_xml/parser.pyc diff --git a/src/club_othello.py b/src/club_othello.py new file mode 100755 index 0000000..8a121e1 --- /dev/null +++ b/src/club_othello.py @@ -0,0 +1,41 @@ +from main.engine import Engine
+from main.event_manager import EventManager
+from input_output.keyboard import Keyboard
+from input_output.video import Video
+from input_output.audio import Audio
+from input_output.mesh import Mesh
+import olpcgames +from sugar.activity.activity import get_bundle_path, get_activity_root
+import os, logging +
+log = logging.getLogger( 'ClubOthello run' )
+log.setLevel( logging.DEBUG )
+
+def init_game():
+ logging.basicConfig()
+ main_path = os.environ["SUGAR_BUNDLE_PATH"] #get_bundle_path()
+ write_path = os.environ["SUGAR_ACTIVITY_ROOT"] #get_activity_root()
+ engine = "" + try:
+ audio = Audio(main_path)
+ video = Video() + if olpcgames.ACTIVITY._shared_activity:
+ actividad_compartida = True + else:
+ actividad_compartida = False
+ malla = Mesh(write_path,audio,video)
+ manejador_eventos = EventManager()
+ engine = Engine(main_path,write_path,video,audio,malla,actividad_compartida)
+ malla.set_engine(engine)
+ teclado = Keyboard(engine)
+ manejador_eventos.subscribe(teclado)
+ manejador_eventos.subscribe(malla)
+ manejador_eventos.run()
+ except Exception, e:
+ if engine != "":
+ engine.get_navigation_manager().exit_club()
+ log.debug( "ERROR!!: " + str(olpcgames.util.get_traceback(e)) )
+ exit() + +if __name__ == "__main__": + init_game() diff --git a/src/club_othello.pyc b/src/club_othello.pyc Binary files differnew file mode 100644 index 0000000..681446b --- /dev/null +++ b/src/club_othello.pyc diff --git a/src/hyperhistory/__init__.py b/src/hyperhistory/__init__.py new file mode 100755 index 0000000..e69de29 --- /dev/null +++ b/src/hyperhistory/__init__.py diff --git a/src/hyperhistory/__init__.pyc b/src/hyperhistory/__init__.pyc Binary files differnew file mode 100644 index 0000000..e1985e0 --- /dev/null +++ b/src/hyperhistory/__init__.pyc diff --git a/src/hyperhistory/character.py b/src/hyperhistory/character.py new file mode 100755 index 0000000..ee662aa --- /dev/null +++ b/src/hyperhistory/character.py @@ -0,0 +1,1815 @@ +from main.constants import F_MEET_BLOCK_VOCALS, S_MEET_BLOCK_VOCALS, NULL, MEET, MEET_GO_TUT, MEET_GO_TUT_AGAIN, \
+ DERECHA, WELCOME, TUTORIAL1, LIST, NAVE, DIAL, PLAY, GANAR, EMPATAR, IZQUIERDA, \
+ PERDER, WON1, DRAW1, LOSE1, BRONZE, MEET_GO_CHAL1, MEET_GO_CHAL1_AGAIN, CHALLENGE1, \
+ WON2, DRAW2, LOSE2, PLATA, CHALLENGE2, DRAW3, LOSE3, WON3, ORO, TUTORIAL2, CHALLENGE3, MEET_GO_CHAL4, CHALLENGE4, \
+ CHALLENGES_COMPLETED, ALL_CLEAR, CLEAR_GAMES, CLEAR_CHALLENGES, MARFIL, MADERA
+from othello.player import PC
+from othello.ai import Ai
+import logging, pygame
+
+log = logging.getLogger( 'src.hyperhistory.character' )
+log.setLevel( logging.DEBUG )
+
+class Character:
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ self.__nombre = nombre
+ self.__disponible_partida = partida
+ self.__disponible_dialogo = dialogo
+ self.__id = id
+
+ def is_available_to_play(self):
+ return self.__disponible_partida
+
+ def is_available_to_talk(self):
+ return self.__disponible_dialogo
+
+ def __str__(self):
+ return "Nombre: " + self.__nombre + "\nPartida: " + str(self.__disponible_partida) + "\nDialogo: " + str(self.__disponible_dialogo)
+
+ def get_name(self):
+ log.debug("obteniendo el nombre del personaje")
+ return self.__nombre
+
+ def get_id(self):
+ return self.__id
+
+ def set_available_to_play(self, valor):
+ self.__disponible_partida = valor
+
+ def set_available_to_talk(self, valor):
+ self.__disponible_dialogo = valor
+
+class ChPabloGris(Character):
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ Character.__init__(self, nombre, partida, dialogo, id)
+ self.__accion = {}
+ self.__evento = {}
+ self.__leccion_retomada = ""
+
+ def set_current_action(self, accion):
+ self.__accion = accion
+
+ def set_current_event(self, evento):
+ self.__evento = evento
+
+ def do_action(self, nombre):
+ if nombre == "bienvenida":
+ pass
+ else:
+ pass
+
+ def __find_action(self, acciones, nombre_accion):
+ for a in acciones:
+ if a['nombre'] == nombre_accion:
+ return a
+
+ def init_room_action(self, engine):
+ usuario = engine.get_user()
+ estado = usuario.get_state()
+ acciones = estado.get_state_actions()
+ state_problem = False
+ character_relation_problem = False
+ if estado.get_name() == "state1":
+ if usuario.get_character_relation("pablo gris") == WELCOME:
+ self.__tutorial1(engine)
+ self.set_current_action(self.__find_action(acciones, "tutorial1"))
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state2":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__go_another_place("go_chal1",engine)
+ self.set_current_action({"nombre":"go_chal1"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state3":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__go_another_place("go_hab_pm1",engine)
+ self.set_current_action({"nombre":"go_hab_pm1"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state4":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__go_another_place("go_hab_pm2",engine)
+ self.set_current_action({"nombre":"go_hab_pm2"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state5":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__go_another_place("go_chal2",engine)
+ self.set_current_action({"nombre":"go_chal2"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state6":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__go_another_place("go_hab_pm3",engine)
+ self.set_current_action({"nombre":"go_hab_pm3"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state8":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL1:
+ self.__tutorial2(engine)
+ self.set_current_action(self.__find_action(acciones, "tutorial2"))
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state9":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ self.__go_another_place("go_chal3",engine)
+ self.set_current_action({"nombre":"go_chal3"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state10":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ self.__go_another_place("go_hab_sd",engine)
+ self.set_current_action({"nombre":"go_hab_sd"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state11":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ if usuario.get_character_relation("protasio") == NULL:
+ self.__go_another_place("go_hab_pt1",engine)
+ self.set_current_action({"nombre":"go_hab_pt1"})
+ else:
+ self.__go_another_place("go_chal4",engine)
+ self.set_current_action({"nombre":"go_chal4"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state12":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ self.__go_another_place("go_hab_pt2",engine)
+ self.set_current_action({"nombre":"go_hab_pt2"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state13":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ engine.get_dialog_manager().begin_dialogue("pg_get_medals")
+ self.set_current_action({"nombre":"get_medals"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state14":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ engine.get_dialog_manager().begin_dialogue("pg_get_medals")
+ self.set_current_action({"nombre":"get_medals"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state15":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ engine.get_dialog_manager().begin_dialogue("pg_pt_defeated")
+ self.set_current_action({"nombre":"pt_defeated"})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state17":
+ if usuario.get_character_relation("pablo gris") == TUTORIAL2:
+ engine.get_dialog_manager().begin_dialogue("pg_all_clear")
+ self.set_current_action({"nombre":"all_clear"})
+ else:
+ character_relation_problem = True
+ else:
+ state_problem = True
+ if state_problem:
+ log.error("Estado invalido! (Class: ChPabloGris, Method: init_room_action)")
+ if character_relation_problem:
+ log.debug("No hay accion asociada a la relacion con Pablo Gris en el %s (Method: init_room_action)", estado.get_name())
+
+ def __go_another_place(self,accion,engine):
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ if accion == "go_hab_pm1":
+ engine.get_dialog_manager().begin_dialogue("pg_go_pm1")
+ elif accion == "go_hab_pm2":
+ engine.get_dialog_manager().begin_dialogue("pg_go_pm2")
+ elif accion == "go_hab_pm3":
+ engine.get_dialog_manager().begin_dialogue("pg_go_pm3")
+ elif accion == "go_chal1":
+ engine.get_dialog_manager().begin_dialogue("pg_chal1")
+ elif accion == "go_chal2":
+ engine.get_dialog_manager().begin_dialogue("pg_go_chal2")
+ elif accion == "go_chal3":
+ engine.get_dialog_manager().begin_dialogue("pg_go_chal3")
+ elif accion == "go_chal4":
+ engine.get_dialog_manager().begin_dialogue("pg_go_chal4")
+ elif accion == "go_hab_sd":
+ engine.get_dialog_manager().begin_dialogue("pg_go_sd")
+ elif accion == "go_hab_pt1":
+ engine.get_dialog_manager().begin_dialogue("pg_go_pt1")
+ elif accion == "go_hab_pt2":
+ engine.get_dialog_manager().begin_dialogue("pg_go_pt2")
+
+ def __tutorial1(self, engine):
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("pg_tutorial1")
+
+ def __tutorial2(self, engine):
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("pg_tutorial2")
+
+ def init_list_action(self, id_leason, engine):
+ engine.change_context(DIAL)
+ engine.get_dialog_manager().begin_dialogue("pg_intro_retake_leason")
+ self.set_current_action({"nombre":"intro_retake_leason"})
+ if id_leason == "tutorial1":
+ self.__leccion_retomada = "tutorial1"
+ elif id_leason == "tutorial2":
+ self.__leccion_retomada = "tutorial2"
+
+ def wellcome(self, engine):
+ engine.get_audio().stop_sound()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("pg_bienvenida")
+
+ def demo_end(self, engine):
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ self.set_current_action({"nombre":"demo_end"})
+ engine.set_action(self.close_action,engine)
+ pg = engine.get_club().get_character_by_name("pablo gris")
+ video.club.show_character(pg)
+ engine.get_dialog_manager().begin_dialogue("pg_demo_end")
+
+ def close_action(self,param):
+ engine = param
+ usuario = engine.get_user()
+ contexto_pos_dialogo = ""
+ if self.__accion['nombre'] == "tutorial1":
+ usuario.set_character_relation(self.get_name(),TUTORIAL1)
+ if 'consecuencia' in self.__accion and self.__accion['consecuencia'] == "change_state":
+ engine.change_state(self.__accion['nuevo_estado'])
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ usuario.set_skill_level(TUTORIAL1)
+ elif self.__accion['nombre'] == "go_hab_pm1" or \
+ self.__accion['nombre'] == "go_chal1" or \
+ self.__accion['nombre'] == "go_hab_pm2" or \
+ self.__accion['nombre'] == "go_chal2" or \
+ self.__accion['nombre'] == "go_hab_pm3" or \
+ self.__accion['nombre'] == "go_chal3" or \
+ self.__accion['nombre'] == "go_hab_sd" or \
+ self.__accion['nombre'] == "go_hab_pt1" or \
+ self.__accion['nombre'] == "go_chal4" or \
+ self.__accion['nombre'] == "go_hab_pt2" or \
+ self.__accion['nombre'] == "get_medals" or \
+ self.__accion['nombre'] == "pt_defeated" or \
+ self.__accion['nombre'] == "all_clear":
+ engine.get_dialog_manager().begin_dialogue("pg_retake")
+ contexto_pos_dialogo = LIST
+ elif self.__accion['nombre'] == "intro_retake_leason":
+ if self.__leccion_retomada == "tutorial1":
+ engine.get_dialog_manager().begin_dialogue("pg_tutorial1",grupo_inicial=1)
+ elif self.__leccion_retomada == "tutorial2":
+ engine.get_dialog_manager().begin_dialogue("pg_tutorial2",grupo_inicial=1)
+ self.set_current_action({"nombre":"retake_leason"})
+ contexto_pos_dialogo = DIAL
+ elif self.__accion['nombre'] == "retake_leason":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "demo_end":
+ engine.get_audio().play_voice_sound("otros","salida_club")
+ engine.get_audio().wait_sound_end()
+ engine.get_navigation_manager().exit_club()
+ elif self.__accion['nombre'] == "tutorial2":
+ usuario.set_character_relation(self.get_name(),TUTORIAL2)
+ if 'consecuencia' in self.__accion and self.__accion['consecuencia'] == "change_state":
+ engine.change_state(self.__accion['nuevo_estado'])
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ usuario.set_skill_level(TUTORIAL2)
+ return contexto_pos_dialogo
+
+ def close_event(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if self.__evento['nombre'] == "bienvenida":
+ usuario.set_character_relation(self.get_name(),WELCOME)
+ if self.__evento['consecuencia'] == "change_state":
+ engine.change_state(self.__evento['nuevo_estado'])
+ video.club.show_room(usuario.get_current_room())
+ self.__evento.clear()
+ contexto_pos_dialogo = NAVE
+ return contexto_pos_dialogo
+
+
+class ChPedroMadera(Character):
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ Character.__init__(self, nombre, partida, dialogo, id)
+ self.__accion = {}
+ self.__evento = {}
+ self.__juego = {}
+ self.__medalla = ""
+
+ def set_current_action(self, accion):
+ self.__accion = accion
+
+ def set_current_event(self, evento):
+ self.__evento = evento
+
+ def set_current_game(self, juego):
+ self.__juego = juego
+
+ def do_action(self, nombre_accion, engine):
+ video = engine.get_video()
+ video.club.show_character(self)
+ video.text_box.show(video.ventana)
+ if nombre_accion == "bloqueo_acceso_piso2_1":
+ engine.get_dialog_manager().begin_dialogue("pm_bloqueo_acceso_piso2_1")
+ elif nombre_accion == "bloqueo_acceso_piso2_2":
+ engine.get_dialog_manager().begin_dialogue("pm_bloqueo_acceso_piso2_2")
+ else:
+ raise Exception("Accion desconocida, (ChPedroMadera Class, do_action method)")
+
+ def __find_action(self, acciones, nombre_accion):
+ for a in acciones:
+ if a['nombre'] == nombre_accion:
+ return a
+
+ def init_room_action(self, engine):
+ usuario = engine.get_user()
+ estado = usuario.get_state()
+ #acciones = estado.get_state_actions()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ state_problem = False
+ character_relation_problem = False
+ if estado.get_name() == "state2":
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ engine.get_dialog_manager().begin_dialogue("pm_first_meet_go_chal1")
+ self.set_current_action({"nombre":"first_meet_go_chal1","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == F_MEET_BLOCK_VOCALS or \
+ usuario.get_character_relation(self.get_name()) == S_MEET_BLOCK_VOCALS:
+ engine.get_dialog_manager().begin_dialogue("pm_intro_room_go_chal1")
+ self.set_current_action({"nombre":"intro_room_go_chal1","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == MEET_GO_CHAL1 or \
+ usuario.get_character_relation(self.get_name()) == MEET_GO_CHAL1_AGAIN:
+ engine.get_dialog_manager().begin_dialogue("pm_intro_room_go_chal1_again")
+ self.set_current_action({"nombre":"intro_room_go_chal1_again","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state3":
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ engine.get_dialog_manager().begin_dialogue("pm_first_meet_first_game")
+ self.set_current_action({"nombre":"first_meet_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == F_MEET_BLOCK_VOCALS or \
+ usuario.get_character_relation(self.get_name()) == S_MEET_BLOCK_VOCALS:
+ engine.get_dialog_manager().begin_dialogue("pm_intro_room_first_game")
+ self.set_current_action({"nombre":"intro_room_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == MEET_GO_CHAL1 or \
+ usuario.get_character_relation(self.get_name()) == MEET_GO_CHAL1_AGAIN:
+ engine.get_dialog_manager().begin_dialogue("pm_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("pm_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state4":
+ if usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("pm_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state5":
+ if usuario.get_character_relation(self.get_name()) == WON2:
+ engine.get_dialog_manager().begin_dialogue("pm_hi_go_chal2")
+ self.set_current_action({"nombre":"hi_go_chal2","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state6":
+ if usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("pm_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state8":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_go_tut2")
+ self.set_current_action({"nombre":"go_tut2","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state9":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_go_chal3")
+ self.set_current_action({"nombre":"go_chal3","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state10":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_go_sd")
+ self.set_current_action({"nombre":"go_sd","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state11":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ if usuario.get_character_relation("protasio") == NULL:
+ engine.get_dialog_manager().begin_dialogue("pm_go_pt1")
+ self.set_current_action({"nombre":"go_pt1","continua_con_dialogo":True})
+ else:
+ engine.get_dialog_manager().begin_dialogue("pm_go_chal4")
+ self.set_current_action({"nombre":"go_chal4","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state12":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_go_pt2")
+ self.set_current_action({"nombre":"go_pt2","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state13":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state14":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state15":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_pt_defeated")
+ self.set_current_action({"nombre":"pt_defeated","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state17":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pm_all_clear")
+ self.set_current_action({"nombre":"all_clear","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ else:
+ state_problem = True
+ if state_problem:
+ log.error("Estado invalido! (Class: ChPedroMadera, Method: init_room_action)")
+ if character_relation_problem:
+ log.debug("No hay accion asociada a la relacion con Pedro Madera en el %s (Method: init_room_action)", estado.get_name())
+
+ def block_third_floor_access(self, engine):
+ usuario = engine.get_user()
+ video = engine.get_video()
+ video.club.show_character(self)
+ video.text_box.show(video.ventana)
+ estado = usuario.get_state()
+ if estado.get_name() == "state1":
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ engine.get_dialog_manager().begin_dialogue("pm_bloqueo_acceso_piso2_1")
+ self.set_current_action({"nombre":"bloqueo_acceso_piso2_1","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == F_MEET_BLOCK_VOCALS:
+ engine.get_dialog_manager().begin_dialogue("pm_bloqueo_acceso_piso2_2")
+ self.set_current_action({"nombre":"bloqueo_acceso_piso2_2","continua_con_dialogo":False})
+ else:
+ log.debug("Relacion con Pedro Madera incorrecta!. Class: ChPedroMadera, Method: block_third_floor_access")
+ else:
+ log.debug("Estado de la aplicacion incorrecto!. Class: ChPedroMadera, Method: block_third_floor_access")
+
+ def init_list_action(self, id_action, engine):
+ engine.change_context(DIAL)
+ if id_action == "jugar_sin_jugadas_posibles":
+ juego_con_jp = False
+ else:
+ juego_con_jp = True
+ engine.init_game("revancha_pm",juego_con_jp)
+ self.__juego = {"nombre":"revancha","objeto":engine.juego}
+ engine.get_dialog_manager().begin_dialogue("pm_prematch_phrase")
+ self.set_current_action({"nombre":"prematch_phrase","continua_con_dialogo":False})
+
+ def close_action(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if not self.__accion['continua_con_dialogo']:
+ video.text_box.disappear(video.ventana)
+ if self.__accion['nombre'] == "bloqueo_acceso_piso2_1":
+ usuario.set_character_relation(self.get_name(),F_MEET_BLOCK_VOCALS)
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "bloqueo_acceso_piso2_2":
+ usuario.set_character_relation(self.get_name(),S_MEET_BLOCK_VOCALS)
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "first_meet_go_chal1" or \
+ self.__accion['nombre'] == "intro_room_go_chal1":
+ usuario.set_character_relation(self.get_name(),MEET_GO_CHAL1)
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ elif self.__accion['nombre'] == "intro_room_go_chal1_again":
+ usuario.set_character_relation(self.get_name(), MEET_GO_CHAL1_AGAIN)
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ elif self.__accion['nombre'] == "hi_go_chal2":
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ elif self.__accion['nombre'] == "first_meet_first_game" or \
+ self.__accion['nombre'] == "intro_room_first_game" or \
+ self.__accion['nombre'] == "init_first_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida1_pm")
+ self.__juego = {"nombre":"partida1"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_second_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida2_pm")
+ self.__juego = {"nombre":"partida2"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_third_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida3_pm")
+ self.__juego = {"nombre":"partida3"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "prematch_phrase":
+ contexto_pos_dialogo = PLAY
+ video.text_box.disappear(video.ventana)
+ video.init_game_elements(self.__juego["objeto"], engine.get_audio())
+ elif self.__accion['nombre'] == "dial_dp_juego_perdido":
+ usuario = engine.get_user()
+ contexto_pos_dialogo = DIAL
+ if usuario.get_character_relation(self.get_name()) == WON1:
+ engine.get_audio().play_fx_sound("otros","medalla_bronce")
+ video.show_medal(BRONZE)
+ usuario.save_medal("bronce")
+ self.__medalla = BRONZE
+ if usuario.get_character_relation(self.get_name()) == WON2:
+ engine.get_audio().play_fx_sound("otros","medalla_plata")
+ video.show_medal(PLATA)
+ usuario.delete_medal("bronce")
+ usuario.save_medal("plata")
+ self.__medalla = PLATA
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_audio().play_fx_sound("otros","medalla_oro")
+ video.show_medal(ORO)
+ usuario.delete_medal("plata")
+ usuario.save_medal("oro")
+ self.__medalla = ORO
+ engine.get_audio().wait_sound_end(tiempo=600)
+ engine.get_dialog_manager().begin_dialogue("pm_bye")
+ self.set_current_action({"nombre":"bye","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "bye":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "won_game")
+ if accion['nuevo_estado'] == "state7":
+ contexto_pos_dialogo = DIAL
+ nueva_hab = usuario.get_current_room().get_right_room()
+ video.club.move_to_another_room(nueva_hab,DERECHA,extra="presentacion_sofia")
+ usuario.set_current_room(nueva_hab)
+ else:
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ engine.change_state(accion['nuevo_estado'])
+ elif self.__accion['nombre'] == "go_tut2" or \
+ self.__accion['nombre'] == "go_chal3" or \
+ self.__accion['nombre'] == "go_sd" or \
+ self.__accion['nombre'] == "go_pt1" or \
+ self.__accion['nombre'] == "go_chal4" or \
+ self.__accion['nombre'] == "go_pt2" or \
+ self.__accion['nombre'] == "get_medals" or \
+ self.__accion['nombre'] == "pt_defeated" or \
+ self.__accion['nombre'] == "all_clear":
+ engine.get_dialog_manager().begin_dialogue("pm_rematch")
+ self.set_current_action({"nombre":"rematch","continua_con_dialogo":False})
+ contexto_pos_dialogo = LIST
+ elif self.__accion['nombre'] == "dp_revancha" or \
+ self.__accion['nombre'] == "dp_juego_empatado_o_ganado":
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ else:
+ raise Exception("Accion desconocida, (Class: ChPedroMadera, Method: close_action)")
+ return contexto_pos_dialogo
+
+ def close_game(self, engine):
+ ganador = engine.juego.get_final_result()
+ resultado = ""
+ video = engine.get_video()
+ video.dissapear_scores()
+ video.dissapear_board()
+ if ganador != "":
+ if ganador.get_name() == PC:
+ resultado = GANAR
+ else:
+ resultado = PERDER
+ else:
+ resultado = EMPATAR
+ if resultado == PERDER:
+ if self.__juego['nombre'] == "partida1":
+ engine.get_dialog_manager().begin_dialogue("pm_perdio_juego1")
+ engine.get_user().set_character_relation(self.get_name(),WON1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_dialog_manager().begin_dialogue("pm_perdio_juego2")
+ engine.get_user().set_character_relation(self.get_name(),WON2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_dialog_manager().begin_dialogue("pm_perdio_juego3")
+ engine.get_user().set_character_relation(self.get_name(),WON3)
+ elif self.__juego['nombre'] == "revancha":
+ engine.get_dialog_manager().begin_dialogue("pm_perdio_revancha")
+ else:
+ if resultado == EMPATAR:
+ engine.get_dialog_manager().begin_dialogue("pm_empato_juego")
+ if self.__juego['nombre'] == "partida1":
+ engine.get_user().set_character_relation(self.get_name(),DRAW1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_user().set_character_relation(self.get_name(),DRAW2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_user().set_character_relation(self.get_name(),DRAW3)
+ elif resultado == GANAR:
+ if self.__juego['nombre'] == "partida1":
+ engine.get_dialog_manager().begin_dialogue("pm_gano_juego")
+ engine.get_user().set_character_relation(self.get_name(),LOSE1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_dialog_manager().begin_dialogue("pm_gano_juego")
+ engine.get_user().set_character_relation(self.get_name(),LOSE2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_dialog_manager().begin_dialogue("pm_gano_juego")
+ engine.get_user().set_character_relation(self.get_name(),LOSE3)
+ elif self.__juego['nombre'] == "revancha":
+ engine.get_dialog_manager().begin_dialogue("pm_gano_revancha")
+ contexto_pos_juego = DIAL
+ if self.__juego['nombre'] == "revancha":
+ self.set_current_action({"nombre":"dp_revancha","continua_con_dialogo":False})
+ else:
+ if resultado == PERDER:
+ self.set_current_action({"nombre":"dial_dp_juego_perdido","continua_con_dialogo":True})
+ else:
+ self.set_current_action({"nombre":"dp_juego_empatado_o_ganado","continua_con_dialogo":False})
+ return contexto_pos_juego
+
+
+class ChDonCano(Character):
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ Character.__init__(self, nombre, partida, dialogo, id)
+ self.__accion = {}
+ self.__desafio = ""
+ self.__retomar_leccion = False
+ self.__nro_intentos = 0
+ self.__medalla = ""
+ self.__trofeo = ""
+
+ def set_current_action(self, accion):
+ self.__accion = accion
+
+ def set_current_challenge(self, desafio):
+ self.__desafio = desafio
+
+ def get_challenge_title(self, usuario, desafio):
+ if usuario.get_challenge_medal(desafio) == BRONZE:
+ return "Tomar desafio " + desafio.upper() + " (BRONCE)"
+ elif usuario.get_challenge_medal(desafio) == PLATA:
+ return "Tomar desafio " + desafio.upper() + " (PLATA)"
+ elif usuario.get_challenge_medal(desafio) == ORO:
+ return "Tomar desafio " + desafio.upper() + " (ORO)"
+ else:
+ return "Tomar desafio " + desafio.upper()
+
+ def __find_action(self, acciones, nombre_accion):
+ for a in acciones:
+ if a['nombre'] == nombre_accion:
+ return a
+
+ def __update_user_medals(self, usuario, desafio):
+ if usuario.get_challenge_medal(desafio) == PLATA:
+ usuario.delete_medal("plata")
+ elif usuario.get_challenge_medal(desafio) == BRONZE:
+ usuario.delete_medal("bronce")
+
+ def init_room_action(self, engine):
+ log.debug("Ingresando al metodo que manejo las acciones de la habitacion")
+ usuario = engine.get_user()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ estado = usuario.get_state()
+ character_relation_problem = False
+ state_problem = False
+ if estado.get_name() == "state1":
+ #Todavia no paso por el Tutorial de aprendizaje de Othello
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ #Nunca antes se encontro con Don Cano
+ engine.get_dialog_manager().begin_dialogue("dc_bienvenida_ir_tut")
+ self.set_current_action({"nombre":"bienvenida_ir_tut","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("dc_ir_tut")
+ self.set_current_action({"nombre":"ir_tut","continua_con_dialogo":False})
+ elif estado.get_name() == "state2":
+ #Ya tomo el tutorial de aprendizaje de Othello
+ log.debug("Despues de verificar el estado...")
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ #Nunca se encontro con Don Cano
+ engine.get_dialog_manager().begin_dialogue("dc_bienvenida_comenzar_chal_1")
+ self.set_current_action({"nombre":"bienvenida_comenzar_chal_1","continua_con_dialogo":False})
+ self.set_current_challenge("chal_a1")
+ self.__nro_intentos = 1
+ else:
+ #Si ya se encontro con Don Cano
+ engine.get_dialog_manager().begin_dialogue("dc_saludo_comenzar_chal_1")
+ self.set_current_action({"nombre":"saludo_comenzar_chal_1","continua_con_dialogo":False})
+ self.set_current_challenge("chal_a1")
+ self.__nro_intentos = 1
+ elif estado.get_name() == "state3":
+ #Ya paso los dos primeros desafios
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE1:
+ engine.get_dialog_manager().begin_dialogue("dc_go_pm1")
+ self.set_current_action({"nombre":"go_pm1","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state4":
+ #Ya paso los dos primeros desafios
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE1:
+ engine.get_dialog_manager().begin_dialogue("dc_go_pm2")
+ self.set_current_action({"nombre":"go_pm2","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state5":
+ #Ya paso los dos primeros desafios y las dos primeras partidas contra pedro madera
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE1:
+ engine.get_dialog_manager().begin_dialogue("dc_saludo_comenzar_chal_2")
+ self.set_current_action({"nombre":"saludo_comenzar_chal_2","continua_con_dialogo":False})
+ self.set_current_challenge("chal_a3")
+ self.__nro_intentos = 1
+ else:
+ log.error("El estado 5 y la relacion con el personaje no coinciden. (Method: init_room_action)")
+ elif estado.get_name() == "state6":
+ #Ya paso los desafios a1, a2, a3, a4 y las dos primeras partidas contra pedro madera
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE2:
+ engine.get_dialog_manager().begin_dialogue("dc_go_pm3")
+ self.set_current_action({"nombre":"go_pm3","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state8":
+ #Ya paso los desafios a1, a2, a3, a4 y las tres partidas contra pedro madera
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE2:
+ engine.get_dialog_manager().begin_dialogue("dc_go_tut2")
+ self.set_current_action({"nombre":"go_tut2","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state9":
+ #Ya paso el segundo tutorial con Pablo Gris
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE2:
+ engine.get_dialog_manager().begin_dialogue("dc_saludo_comenzar_chal_3")
+ self.set_current_action({"nombre":"saludo_comenzar_chal_3","continua_con_dialogo":False})
+ self.set_current_challenge("chal_b1")
+ self.__nro_intentos = 1
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state10":
+ #Ya paso el desafio por 5 medallas de bronce
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE3:
+ engine.get_dialog_manager().begin_dialogue("dc_go_sd1")
+ self.set_current_action({"nombre":"go_sd1","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state11":
+ if usuario.get_character_relation("protasio") == NULL:
+ engine.get_dialog_manager().begin_dialogue("dc_go_pt1")
+ self.set_current_action({"nombre":"go_pt1","continua_con_dialogo":True})
+ else:
+ engine.get_dialog_manager().begin_dialogue("dc_saludo_comenzar_chal_4")
+ self.set_current_action({"nombre":"saludo_comenzar_chal_4","continua_con_dialogo":False})
+ self.set_current_challenge("chal_c1")
+ self.__nro_intentos = 1
+ elif estado.get_name() == "state12":
+ #Ya paso el desafio sin jugadas posibles marcadas
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE4:
+ engine.get_dialog_manager().begin_dialogue("dc_go_pt2")
+ self.set_current_action({"nombre":"go_pt2","continua_con_dialogo":True})
+ elif usuario.get_character_relation(self.get_name()) == CHALLENGES_COMPLETED:
+ engine.get_dialog_manager().begin_dialogue("dc_chals_completed")
+ self.set_current_action({"nombre":"chals_completed","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state13":
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE4:
+ engine.get_dialog_manager().begin_dialogue("dc_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ elif usuario.get_character_relation(self.get_name()) == CHALLENGES_COMPLETED:
+ engine.get_dialog_manager().begin_dialogue("dc_chals_completed")
+ self.set_current_action({"nombre":"chals_completed","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state14":
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE4:
+ engine.get_dialog_manager().begin_dialogue("dc_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ elif usuario.get_character_relation(self.get_name()) == CHALLENGES_COMPLETED:
+ engine.get_dialog_manager().begin_dialogue("dc_chals_completed")
+ self.set_current_action({"nombre":"chals_completed","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state15":
+ if usuario.get_character_relation(self.get_name()) == CHALLENGE4:
+ engine.get_dialog_manager().begin_dialogue("dc_pt_defeated")
+ self.set_current_action({"nombre":"pt_defeated","continua_con_dialogo":True})
+ elif usuario.get_character_relation(self.get_name()) == CHALLENGES_COMPLETED:
+ engine.get_dialog_manager().begin_dialogue("dc_chals_completed")
+ self.set_current_action({"nombre":"chals_completed","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state17":
+ if usuario.get_character_relation(self.get_name()) == CHALLENGES_COMPLETED:
+ engine.get_dialog_manager().begin_dialogue("dc_all_clear")
+ self.set_current_action({"nombre":"all_clear","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ else:
+ state_problem = True
+ if state_problem:
+ log.error("Estado invalido! (Class: ChDonCano, Method: init_room_action)")
+ if character_relation_problem:
+ log.debug("No hay accion asociada a la relacion con Don Cano en el %s (Method: init_room_action)", estado.get_name())
+
+ def init_list_action(self, id_leason, engine):
+ engine.change_context(DIAL)
+ if not id_leason == "reintentar":
+ self.__retomar_leccion = True
+ if id_leason == "retake_chal_a1":
+ self.__desafio = "chal_a1"
+ elif id_leason == "retake_chal_a2":
+ self.__desafio = "chal_a2"
+ elif id_leason == "retake_chal_a3":
+ self.__desafio = "chal_a3"
+ elif id_leason == "retake_chal_a4":
+ self.__desafio = "chal_a4"
+ elif id_leason == "retake_chal_a5":
+ self.__desafio = "chal_a5"
+ elif id_leason == "retake_chal_b1":
+ self.__desafio = "chal_b1"
+ elif id_leason == "retake_chal_b2":
+ self.__desafio = "chal_b2"
+ elif id_leason == "retake_chal_b3":
+ self.__desafio = "chal_b3"
+ elif id_leason == "retake_chal_b4":
+ self.__desafio = "chal_b4"
+ elif id_leason == "retake_chal_b5":
+ self.__desafio = "chal_b5"
+ elif id_leason == "retake_chal_c1":
+ self.__desafio = "chal_c1"
+ elif id_leason == "retake_chal_c2":
+ self.__desafio = "chal_c2"
+ elif id_leason == "retake_chal_c3":
+ self.__desafio = "chal_c3"
+ elif id_leason == "retake_chal_c4":
+ self.__desafio = "chal_c4"
+ elif id_leason == "retake_chal_c5":
+ self.__desafio = "chal_c5"
+ self.__nro_intentos = 1
+ else:
+ self.__nro_intentos += 1
+ self.__retomar_leccion = False
+ if self.__desafio == "chal_a1":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_a1")
+ self.set_current_action({"nombre":"retake_chal_a1","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a2":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_a2")
+ self.set_current_action({"nombre":"retake_chal_a2","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a3":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_a3")
+ self.set_current_action({"nombre":"retake_chal_a3","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a4":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_a4")
+ self.set_current_action({"nombre":"retake_chal_a4","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a5":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_a5")
+ self.set_current_action({"nombre":"retake_chal_a5","continua_con_dialogo":False})
+ elif self.__desafio == "chal_b1":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_b1")
+ self.set_current_action({"nombre":"retake_chal_b1","continua_con_dialogo":False})
+ elif self.__desafio == "chal_b2":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_b2")
+ self.set_current_action({"nombre":"retake_chal_b2","continua_con_dialogo":False})
+ elif self.__desafio == "chal_b3":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_b3")
+ self.set_current_action({"nombre":"retake_chal_b3","continua_con_dialogo":False})
+ elif self.__desafio == "chal_b4":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_b4")
+ self.set_current_action({"nombre":"retake_chal_b4","continua_con_dialogo":False})
+ elif self.__desafio == "chal_b5":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_b5")
+ self.set_current_action({"nombre":"retake_chal_b5","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c1":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_c1")
+ self.set_current_action({"nombre":"retake_chal_c1","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c2":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_c2")
+ self.set_current_action({"nombre":"retake_chal_c2","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c3":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_c3")
+ self.set_current_action({"nombre":"retake_chal_c3","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c4":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_c4")
+ self.set_current_action({"nombre":"retake_chal_c4","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c5":
+ engine.get_dialog_manager().begin_dialogue("dc_retake_chal_c5")
+ self.set_current_action({"nombre":"retake_chal_c5","continua_con_dialogo":False})
+
+ def close_action(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if not self.__accion['continua_con_dialogo']:
+ video.text_box.disappear(video.ventana)
+ if self.__accion['nombre'] == "bienvenida_ir_tut":
+ usuario.set_character_relation(self.get_name(),MEET_GO_TUT)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "ir_tut":
+ usuario.set_character_relation(self.get_name(),MEET_GO_TUT_AGAIN)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "bienvenida_comenzar_chal_1" or \
+ self.__accion['nombre'] == "saludo_comenzar_chal_1" or \
+ self.__accion['nombre'] == "retake_chal_a1" or \
+ self.__accion['nombre'] == "consejo_desafio_a2" or \
+ self.__accion['nombre'] == "retake_chal_a2" or \
+ self.__accion['nombre'] == "saludo_comenzar_chal_2" or \
+ self.__accion['nombre'] == "retake_chal_a3" or \
+ self.__accion['nombre'] == "consejo_desafio_a4" or \
+ self.__accion['nombre'] == "retake_chal_a4" or \
+ self.__accion['nombre'] == "saludo_comenzar_chal_3" or \
+ self.__accion['nombre'] == "retake_chal_b1" or \
+ self.__accion['nombre'] == "retake_chal_a5"or \
+ self.__accion['nombre'] == "retake_chal_b2" or \
+ self.__accion['nombre'] == "retake_chal_b3" or \
+ self.__accion['nombre'] == "retake_chal_b4" or \
+ self.__accion['nombre'] == "retake_chal_b5" or \
+ self.__accion['nombre'] == "saludo_comenzar_chal_4" or \
+ self.__accion['nombre'] == "retake_chal_c1" or \
+ self.__accion['nombre'] == "retake_chal_c2" or \
+ self.__accion['nombre'] == "retake_chal_c3" or \
+ self.__accion['nombre'] == "retake_chal_c4" or \
+ self.__accion['nombre'] == "retake_chal_c5":
+ contexto_pos_dialogo = self.__end_challenge(engine, video)
+ elif self.__accion['nombre'] == "ok_challenge_check_answer":
+ video.dissapear_game_elements()
+ video.text_box.show(video.ventana)
+ if not self.__retomar_leccion:
+ if self.__desafio == "chal_a1":
+ engine.get_dialog_manager().begin_dialogue("dc_continue_chal1")
+ self.set_current_action({"nombre":"continue_chal1","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a2":
+ engine.get_dialog_manager().begin_dialogue("dc_finalizar_chal1")
+ self.set_current_action({"nombre":"finalizar_chal1","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a3":
+ engine.get_dialog_manager().begin_dialogue("dc_continue_chal2")
+ self.set_current_action({"nombre":"continue_chal2","continua_con_dialogo":False})
+ elif self.__desafio == "chal_a4":
+ engine.get_dialog_manager().begin_dialogue("dc_finalizar_chal2")
+ self.set_current_action({"nombre":"finalizar_chal2","continua_con_dialogo":False})
+ elif self.__desafio == "chal_c1":
+ self.__give_challenge_medal(engine, usuario)
+ else:
+ self.__give_challenge_medal(engine, usuario)
+ contexto_pos_dialogo = DIAL
+ elif self.__accion['nombre'] == "give_gold" or \
+ self.__accion['nombre'] == "give_silver" or \
+ self.__accion['nombre'] == "give_bronze":
+ medalla_a_entregar = self.__accion['nombre'].split('_')[1]
+ desafio = self.__desafio.split("_")[1]
+ if medalla_a_entregar == "gold":
+ usuario.save_challenge_medal(desafio, ORO)
+ usuario.save_medal("oro")
+ self.__medalla = ORO
+ video.show_medal(ORO)
+ engine.get_audio().play_fx_sound("otros","medalla_oro")
+ elif medalla_a_entregar == "silver":
+ usuario.save_challenge_medal(desafio, PLATA)
+ usuario.save_medal("plata")
+ self.__medalla = PLATA
+ video.show_medal(PLATA)
+ engine.get_audio().play_fx_sound("otros","medalla_plata")
+ elif medalla_a_entregar == "bronze":
+ usuario.save_challenge_medal(desafio, BRONZE)
+ usuario.save_medal("bronce")
+ self.__medalla = BRONZE
+ video.show_medal(BRONZE)
+ engine.get_audio().play_fx_sound("otros","medalla_bronce")
+ else:
+ log.warning("Medalla desconocida. (Method: close_action)")
+ if not self.__medals_clear(usuario):
+ if self.__desafio == "chal_c1":
+ engine.get_dialog_manager().begin_dialogue("dc_finalizar_chal4")
+ self.set_current_action({"nombre":"finalizar_chal4","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("dc_bye")
+ self.set_current_action({"nombre":"bye","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("dc_chals_clear")
+ self.set_current_action({"nombre":"chals_clear","continua_con_dialogo":True})
+ #TODO: Si no sirve eliminar
+ elif self.__accion['nombre'] == "ok_retake_challenge_check_answer":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "give_retro_medals":
+ for _ in xrange(1,6):
+ engine.get_audio().play_fx_sound("otros","medalla_bronce")
+ video.show_medal(BRONZE)
+ usuario.save_medal("bronce")
+ engine.get_audio().wait_sound_end(tiempo=600)
+ usuario.save_challenge_medal("a1", BRONZE)
+ usuario.save_challenge_medal("a2", BRONZE)
+ usuario.save_challenge_medal("a3", BRONZE)
+ usuario.save_challenge_medal("a4", BRONZE)
+ usuario.save_challenge_medal("b1", BRONZE)
+ video.dissapear_medal(BRONZE)
+ engine.get_dialog_manager().begin_dialogue("dc_explain_medals_finalizar_chal_3")
+ self.set_current_action({"nombre":"explain_medals_finalizar_chal_3","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "explain_medals_finalizar_chal_3":
+ usuario.set_character_relation(self.get_name(),CHALLENGE3)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "complete_chal_3")
+ engine.change_state(accion['nuevo_estado'])
+ usuario.set_skill_level(CHALLENGE3)
+ elif self.__accion['nombre'] == "continue_chal1":
+ engine.get_dialog_manager().begin_dialogue("dc_consejo_desafio_a2")
+ self.set_current_action({"nombre":"consejo_desafio_a2","continua_con_dialogo":False})
+ self.set_current_challenge("chal_a2")
+ contexto_pos_dialogo = ""
+ elif self.__accion['nombre'] == "continue_chal2":
+ engine.get_dialog_manager().begin_dialogue("dc_consejo_desafio_a4")
+ self.set_current_action({"nombre":"consejo_desafio_a4","continua_con_dialogo":False})
+ self.set_current_challenge("chal_a4")
+ contexto_pos_dialogo = ""
+ elif self.__accion['nombre'] == "finalizar_chal1":
+ usuario.set_character_relation(self.get_name(),CHALLENGE1)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "complete_chal_1")
+ engine.change_state(accion['nuevo_estado'])
+ usuario.set_skill_level(CHALLENGE1)
+ elif self.__accion['nombre'] == "finalizar_chal2":
+ usuario.set_character_relation(self.get_name(),CHALLENGE2)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "complete_chal_2")
+ engine.change_state(accion['nuevo_estado'])
+ usuario.set_skill_level(CHALLENGE2)
+ elif self.__accion['nombre'] == "finalizar_chal4":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ usuario.set_character_relation(self.get_name(),CHALLENGE4)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "complete_chal_4")
+ engine.change_state(accion['nuevo_estado'])
+ usuario.set_skill_level(CHALLENGE4)
+ elif self.__accion['nombre'] == "chals_clear":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ engine.get_audio().play_fx_sound("otros","trofeo_marfil")
+ video.show_trophy(MARFIL)
+ self.__trofeo = MARFIL
+ usuario.set_character_relation(self.get_name(),CHALLENGES_COMPLETED)
+ if usuario.get_state().get_name() == "state15":
+ usuario.set_skill_level(ALL_CLEAR)
+ else:
+ usuario.set_skill_level(CLEAR_CHALLENGES)
+ engine.get_dialog_manager().begin_dialogue("dc_bye")
+ self.set_current_action({"nombre":"bye","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "go_pm1" or \
+ self.__accion['nombre'] == "go_pm2" or \
+ self.__accion['nombre'] == "go_pm3" or \
+ self.__accion['nombre'] == "go_sd1" or \
+ self.__accion['nombre'] == "go_pt1" or \
+ self.__accion['nombre'] == "go_pt2" or \
+ self.__accion['nombre'] == "get_medals" or \
+ self.__accion['nombre'] == "pt_defeated" or \
+ self.__accion['nombre'] == "chals_completed" or \
+ self.__accion['nombre'] == "all_clear":
+ engine.get_dialog_manager().begin_dialogue("dc_chal_retake")
+ contexto_pos_dialogo = LIST
+ elif self.__accion['nombre'] == "go_tut2":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "bye":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ if self.__trofeo != "":
+ video.dissapear_trophy(self.__trofeo)
+ self.__trofeo = ""
+ if usuario.get_skill_level() == ALL_CLEAR:
+ contexto_pos_dialogo = DIAL
+ nueva_hab = usuario.get_current_room().get_right_room()
+ video.club.move_to_another_room(nueva_hab,DERECHA,extra="final_juego")
+ usuario.set_current_room(nueva_hab)
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "challenges_completed")
+ engine.change_state(accion['nuevo_estado'])
+ else:
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ return contexto_pos_dialogo
+
+ def __medals_clear(self, usuario):
+ medallas = usuario.get_challenge_medals()
+ for medalla in medallas.values():
+ if not medalla == ORO:
+ return False
+ return True
+
+ def __give_challenge_medal(self, engine, usuario):
+ desafio = self.__desafio.split("_")[1]
+ if (usuario.get_character_relation(self.get_name()) == CHALLENGE3 or usuario.get_character_relation(self.get_name()) == CHALLENGE4) and \
+ not usuario.get_challenge_medal(desafio) == ORO:
+ self.__update_user_medals(usuario, desafio)
+ if self.__nro_intentos == 1:
+ engine.get_dialog_manager().begin_dialogue("dc_give_gold")
+ self.set_current_action({"nombre":"give_gold","continua_con_dialogo":True})
+ elif self.__nro_intentos == 2:
+ engine.get_dialog_manager().begin_dialogue("dc_give_silver")
+ self.set_current_action({"nombre":"give_silver","continua_con_dialogo":True})
+ elif self.__nro_intentos > 2:
+ engine.get_dialog_manager().begin_dialogue("dc_give_bronze")
+ self.set_current_action({"nombre":"give_bronze","continua_con_dialogo":True})
+ else:
+ log.debug("Nro. de intetos desconocidos. (Method: close_action)")
+ else:
+ engine.get_dialog_manager().begin_dialogue("dc_bye")
+ self.set_current_action({"nombre":"bye","continua_con_dialogo":False})
+
+ def __end_challenge(self, engine, video):
+ if engine.get_dialog_manager().challenge_error():
+ engine.get_dialog_manager().begin_dialogue("dc_ask_select_option_list")
+ contexto = LIST
+ else:
+ self.__ok_challenge(engine, video)
+ contexto = ""
+ return contexto
+
+ def __ok_challenge(self, engine, video):
+ engine.get_audio().play_voice_sound("game","ok_"+self.__desafio)
+ engine.get_audio().wait_sound_end(tiempo=600)
+ nombre_personaje = self.get_name()
+ relacion_con_personaje = engine.get_user().get_character_relation(nombre_personaje)
+ if (relacion_con_personaje != CHALLENGE3 or relacion_con_personaje != CHALLENGE4):
+ if not self.__desafio == "chal_b1" and not self.__desafio == "chal_b2" and not self.__desafio == "chal_b3" and \
+ not self.__desafio == "chal_b4" and not self.__desafio == "chal_b5":
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("dc_ok_challenge_check_answer")
+ self.set_current_action({"nombre":"ok_challenge_check_answer","continua_con_dialogo":True})
+ engine.get_audio().play_fx_sound("otros","wait_input")
+ else:
+ video.dissapear_game_elements()
+ video.text_box.show(video.ventana)
+ if self.__desafio == "chal_b1" and not self.__accion['nombre'] == "retake_chal_b1":
+ engine.get_dialog_manager().begin_dialogue("dc_give_retro_medals")
+ self.set_current_action({"nombre":"give_retro_medals","continua_con_dialogo":True})
+ else:
+ self.__give_challenge_medal(engine, engine.get_user())
+ else:
+ self.__give_challenge_medal(engine, engine.get_user())
+
+class ChSofiaDulce(Character):
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ Character.__init__(self, nombre, partida, dialogo, id)
+ self.__accion = {}
+ self.__evento = {}
+ self.__juego = {}
+ self.__medalla = ""
+
+ def set_current_action(self, accion):
+ self.__accion = accion
+
+ def set_current_event(self, evento):
+ self.__evento = evento
+
+ def set_current_game(self, juego):
+ self.__juego = juego
+
+ def __find_action(self, acciones, nombre_accion):
+ for a in acciones:
+ if a['nombre'] == nombre_accion:
+ return a
+
+ def init_room_action(self, engine):
+ usuario = engine.get_user()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ estado = usuario.get_state()
+ state_problem = False
+ character_relation_problem = False
+ if estado.get_name() == "state8":
+ if usuario.get_character_relation(self.get_name()) == MEET:
+ engine.get_dialog_manager().begin_dialogue("sd_go_tut2")
+ self.set_current_action({"nombre":"go_tut2","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state9":
+ if usuario.get_character_relation(self.get_name()) == MEET:
+ engine.get_dialog_manager().begin_dialogue("sd_go_chal3")
+ self.set_current_action({"nombre":"go_chal3","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state10":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("sd_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state11":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("sd_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("sd_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("sd_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_go_chal4")
+ self.set_current_action({"nombre":"go_chal4","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state12":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("sd_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("sd_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("sd_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_go_pt2")
+ self.set_current_action({"nombre":"go_pt2","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state13":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("sd_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("sd_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("sd_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state14":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ engine.get_dialog_manager().begin_dialogue("sd_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("sd_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("sd_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_get_medals")
+ self.set_current_action({"nombre":"get_medals","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state15":
+ if usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ engine.get_dialog_manager().begin_dialogue("sd_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ engine.get_dialog_manager().begin_dialogue("sd_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_pt_defeated")
+ self.set_current_action({"nombre":"pt_defeated","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state17":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("sd_all_clear")
+ self.set_current_action({"nombre":"all_clear","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ else:
+ state_problem = True
+ if state_problem:
+ log.error("Estado invalido! (Class: ChSofiaDulce, Method: init_room_action)")
+ if character_relation_problem:
+ log.debug("No hay accion asociada a la relacion con Sofia Dulce en el %s (Method: init_room_action)", estado.get_name())
+
+ def init_list_action(self, id_action, engine):
+ engine.change_context(DIAL)
+ #video = engine.get_video()
+ #usuario = engine.get_user()
+ #video.text_box.disappear(video.ventana)
+ if id_action == "jugar_sin_jugadas_posibles":
+ juego_con_jp = False
+ else:
+ juego_con_jp = True
+ #if usuario.get_character_relation(self.get_name()) == WON1 or \
+ # usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ # usuario.get_character_relation(self.get_name()) == LOSE2:
+ # engine.init_game("partida2_sd",juego_con_jp)
+ # self.set_current_game({"nombre":"partida2"})
+ #elif usuario.get_character_relation(self.get_name()) == WON2 or \
+ # usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ # usuario.get_character_relation(self.get_name()) == LOSE3:
+ # engine.init_game("partida3_sd",juego_con_jp)
+ # self.set_current_game({"nombre":"partida3"})
+ #elif usuario.get_character_relation(self.get_name()) == WON3:
+ engine.init_game("revancha_sd", juego_con_jp, nivel=Ai.MEDIO)
+ self.__juego = {"nombre":"revancha","objeto":engine.juego}
+ engine.get_dialog_manager().begin_dialogue("sd_prematch_phrase")
+ self.set_current_action({"nombre":"prematch_phrase","continua_con_dialogo":False})
+ #video.init_game_elements(engine.juego, engine.get_audio())
+
+ def close_action(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if not self.__accion['continua_con_dialogo']:
+ video.text_box.disappear(video.ventana)
+ if self.__accion['nombre'] == "go_tut2":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "go_chal3":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "go_chal4" or \
+ self.__accion['nombre'] == "get_medals" or \
+ self.__accion['nombre'] == "pt_defeated" or \
+ self.__accion['nombre'] == "all_clear" or \
+ self.__accion['nombre'] == "go_pt2":
+ engine.get_dialog_manager().begin_dialogue("sd_rematch_game")
+ self.set_current_action({"nombre":"rematch_game","continua_con_dialogo":False})
+ contexto_pos_dialogo = LIST
+ elif self.__accion['nombre'] == "init_first_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida1_sd", nivel=Ai.MEDIO)
+ self.__juego = {"nombre":"partida1"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_second_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida2_sd", nivel=Ai.MEDIO)
+ self.__juego = {"nombre":"partida2"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_third_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida3_sd", nivel=Ai.MEDIO)
+ self.__juego = {"nombre":"partida3"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "prematch_phrase":
+ contexto_pos_dialogo = PLAY
+ video.text_box.disappear(video.ventana)
+ video.init_game_elements(self.__juego["objeto"], engine.get_audio())
+ elif self.__accion['nombre'] == "dp_revancha" or \
+ self.__accion['nombre'] == "dp_juego_empatado_o_ganado":
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ elif self.__accion['nombre'] == "dial_dp_juego_perdido":
+ usuario = engine.get_user()
+ contexto_pos_dialogo = DIAL
+ if usuario.get_character_relation(self.get_name()) == WON1:
+ engine.get_audio().play_fx_sound("otros","medalla_bronce")
+ video.show_medal(BRONZE)
+ usuario.save_medal("bronce")
+ self.__medalla = BRONZE
+ if usuario.get_character_relation(self.get_name()) == WON2:
+ engine.get_audio().play_fx_sound("otros","medalla_plata")
+ video.show_medal(PLATA)
+ usuario.delete_medal("bronce")
+ usuario.save_medal("plata")
+ self.__medalla = PLATA
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_audio().play_fx_sound("otros","medalla_oro")
+ video.show_medal(ORO)
+ usuario.delete_medal("plata")
+ usuario.save_medal("oro")
+ self.__medalla = ORO
+ engine.get_audio().wait_sound_end(tiempo=600)
+ if self.__juego['nombre'] == "partida1":
+ engine.get_dialog_manager().begin_dialogue("sd_give_medal1")
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_dialog_manager().begin_dialogue("sd_give_medal2")
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_dialog_manager().begin_dialogue("sd_give_medal3")
+ self.set_current_action({"nombre":"dp_entregar_medalla","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "dp_entregar_medalla":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ if usuario.get_state().get_name() == "state10":
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "won_game")
+ engine.change_state(accion['nuevo_estado'])
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ return contexto_pos_dialogo
+
+ def presentation(self, engine):
+ engine.get_audio().stop_sound()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("sd_presentation")
+
+ def close_event(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if video.text_box.is_up():
+ video.text_box.disappear(video.ventana)
+ if self.__evento['nombre'] == "presentacion":
+ usuario.set_character_relation(self.get_name(), MEET)
+ if self.__evento['consecuencia'] == "change_state":
+ engine.change_state(self.__evento['nuevo_estado'])
+ self.__evento.clear()
+ hab = engine.get_club().get_room_by_name("tercer piso")
+ video.club.show_room(hab)
+ contexto_pos_dialogo = NAVE
+ return contexto_pos_dialogo
+
+ def close_game(self, engine):
+ ganador = engine.juego.get_final_result()
+ resultado = ""
+ video = engine.get_video()
+ video.dissapear_scores()
+ video.dissapear_board()
+ if ganador != "":
+ if ganador.get_name() == PC:
+ resultado = GANAR
+ else:
+ resultado = PERDER
+ else:
+ resultado = EMPATAR
+ if resultado == PERDER:
+ if self.__juego['nombre'] == "partida1":
+ engine.get_dialog_manager().begin_dialogue("sd_perdio_juego1")
+ engine.get_user().set_character_relation(self.get_name(),WON1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_dialog_manager().begin_dialogue("sd_perdio_juego2")
+ engine.get_user().set_character_relation(self.get_name(),WON2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_dialog_manager().begin_dialogue("sd_perdio_juego3")
+ engine.get_user().set_character_relation(self.get_name(),WON3)
+ elif self.__juego['nombre'] == "revancha":
+ engine.get_dialog_manager().begin_dialogue("sd_perdio_revancha")
+ else:
+ if resultado == EMPATAR:
+ engine.get_dialog_manager().begin_dialogue("sd_empato_juego")
+ if self.__juego['nombre'] == "partida1":
+ engine.get_user().set_character_relation(self.get_name(),DRAW1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_user().set_character_relation(self.get_name(),DRAW2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_user().set_character_relation(self.get_name(),DRAW3)
+ elif resultado == GANAR:
+ engine.get_dialog_manager().begin_dialogue("sd_gano_juego")
+ if self.__juego['nombre'] == "partida1":
+ engine.get_user().set_character_relation(self.get_name(),LOSE1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_user().set_character_relation(self.get_name(),LOSE2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_user().set_character_relation(self.get_name(),LOSE3)
+ contexto_pos_juego = DIAL
+ if self.__juego['nombre'] == "revancha":
+ self.set_current_action({"nombre":"dp_revancha","continua_con_dialogo":False})
+ else:
+ if resultado == PERDER:
+ self.set_current_action({"nombre":"dial_dp_juego_perdido","continua_con_dialogo":True})
+ else:
+ self.set_current_action({"nombre":"dp_juego_empatado_o_ganado","continua_con_dialogo":False})
+ return contexto_pos_juego
+
+class ChProtasio(Character):
+ def __init__(self, nombre=-1, partida=False, dialogo=False, id=""):
+ Character.__init__(self, nombre, partida, dialogo, id)
+ self.__accion = {}
+ self.__evento = {}
+ self.__juego = {}
+ self.__medalla = ""
+
+ def set_current_action(self, accion):
+ self.__accion = accion
+
+ def set_current_event(self, evento):
+ self.__evento = evento
+
+ def __find_action(self, acciones, nombre_accion):
+ for a in acciones:
+ if a['nombre'] == nombre_accion:
+ return a
+
+ def fin_juego(self, engine):
+ engine.get_audio().stop_sound()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ engine.get_dialog_manager().begin_dialogue("end_game")
+
+ def close_event(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ video.text_box.disappear(video.ventana)
+ if self.__evento['nombre'] == "end_game":
+ self.__evento.clear()
+ hab = usuario.get_current_room()
+ video.club.show_room(hab)
+ contexto_pos_dialogo = NAVE
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "after_end")
+ engine.change_state(accion['nuevo_estado'])
+ return contexto_pos_dialogo
+
+ def init_room_action(self, engine):
+ usuario = engine.get_user()
+ video = engine.get_video()
+ video.text_box.show(video.ventana)
+ estado = usuario.get_state()
+ state_problem = False
+ character_relation_problem = False
+ if estado.get_name() == "state10":
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ engine.get_dialog_manager().begin_dialogue("pt_intro_infection_go_sd")
+ self.set_current_action({"nombre":"intro_infection_go_sd","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state11":
+ if usuario.get_character_relation(self.get_name()) == NULL:
+ engine.get_dialog_manager().begin_dialogue("pt_intro_go_chal4")
+ self.set_current_action({"nombre":"intro_go_chal4","continua_con_dialogo":False})
+ elif usuario.get_character_relation(self.get_name()) == MEET:
+ engine.get_dialog_manager().begin_dialogue("pt_go_chal4")
+ self.set_current_action({"nombre":"go_chal4","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state12":
+ if usuario.get_character_relation(self.get_name()) == MEET or \
+ usuario.get_character_relation(self.get_name()) == DRAW1 or \
+ usuario.get_character_relation(self.get_name()) == LOSE1:
+ if usuario.get_character_relation('sofia dulce') == WON1 or \
+ usuario.get_character_relation('sofia dulce') == WON2 or \
+ usuario.get_character_relation('sofia dulce') == WON3:
+ engine.get_dialog_manager().begin_dialogue("pt_init_first_game")
+ self.set_current_action({"nombre":"init_first_game","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("pt_go_sd")
+ self.set_current_action({"nombre":"go_sd","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state13":
+ if usuario.get_character_relation(self.get_name()) == WON1 or \
+ usuario.get_character_relation(self.get_name()) == DRAW2 or \
+ usuario.get_character_relation(self.get_name()) == LOSE2:
+ hash_medallas = usuario.get_medals()
+ total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
+ if total_medallas >= 12 and hash_medallas["oro"] >= 2:
+ engine.get_dialog_manager().begin_dialogue("pt_init_second_game")
+ self.set_current_action({"nombre":"init_second_game","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("pt_match2_more_medals")
+ self.set_current_action({"nombre":"match2_more_medals","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state14":
+ if usuario.get_character_relation(self.get_name()) == WON2 or \
+ usuario.get_character_relation(self.get_name()) == DRAW3 or \
+ usuario.get_character_relation(self.get_name()) == LOSE3:
+ hash_medallas = usuario.get_medals()
+ total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
+ if total_medallas >= 18 and hash_medallas["oro"] >= 4:
+ if usuario.get_character_relation('sofia dulce') == WON3:
+ engine.get_dialog_manager().begin_dialogue("pt_init_third_game")
+ self.set_current_action({"nombre":"init_third_game","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("pt_go_sd2")
+ self.set_current_action({"nombre":"go_sd2","continua_con_dialogo":False})
+ else:
+ engine.get_dialog_manager().begin_dialogue("pt_match3_more_medals")
+ self.set_current_action({"nombre":"match3_more_medals","continua_con_dialogo":False})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state15":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pt_pt_defeated")
+ self.set_current_action({"nombre":"pt_defeated","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ elif estado.get_name() == "state17":
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_dialog_manager().begin_dialogue("pt_all_clear")
+ self.set_current_action({"nombre":"all_clear","continua_con_dialogo":True})
+ else:
+ character_relation_problem = True
+ else:
+ state_problem = True
+ if state_problem:
+ log.error("Estado invalido! (Class: ChProtasio, Method: init_room_action)")
+ if character_relation_problem:
+ log.debug("No hay accion asociada a la relacion con Protasio en el %s (Method: init_room_action)", estado.get_name())
+
+ def init_list_action(self, id_action, engine):
+ engine.change_context(DIAL)
+ #video = engine.get_video()
+ #video.text_box.disappear(video.ventana)
+ engine.init_game("revancha_pt", con_jugadas_posibles=False, nivel=Ai.DIFICIL)
+ self.__juego = {"nombre":"revancha", "objeto":engine.juego}
+ engine.get_dialog_manager().begin_dialogue("pt_prematch_phrase")
+ self.set_current_action({"nombre":"prematch_phrase","continua_con_dialogo":False})
+ #video.init_game_elements(engine.juego, engine.get_audio())
+
+ def close_action(self, param):
+ engine = param
+ usuario = engine.get_user()
+ video = engine.get_video()
+ contexto_pos_dialogo = ""
+ if not self.__accion['continua_con_dialogo']:
+ video.text_box.disappear(video.ventana)
+ if self.__accion['nombre'] == "intro_infection_go_sd":
+ engine.get_user().set_character_relation(self.get_name(),MEET)
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "infection_club")
+ engine.change_state(accion['nuevo_estado'])
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "intro_go_chal4":
+ engine.get_user().set_character_relation(self.get_name(),MEET)
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "go_chal4" or \
+ self.__accion['nombre'] == "match2_more_medals" or \
+ self.__accion['nombre'] == "go_sd2" or \
+ self.__accion['nombre'] == "go_sd" or \
+ self.__accion['nombre'] == "match3_more_medals":
+ engine.get_navigation_manager().leave_room()
+ contexto_pos_dialogo = NAVE
+ elif self.__accion['nombre'] == "pt_defeated" or \
+ self.__accion['nombre'] == "all_clear":
+ engine.get_dialog_manager().begin_dialogue("pt_rematch_game")
+ self.set_current_action({"nombre":"rematch_game","continua_con_dialogo":False})
+ contexto_pos_dialogo = LIST
+ elif self.__accion['nombre'] == "init_first_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida1_pt",con_jugadas_posibles=False,nivel=Ai.DIFICIL)
+ self.__juego = {"nombre":"partida1"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_second_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida2_pt",con_jugadas_posibles=False,nivel=Ai.DIFICIL)
+ self.__juego = {"nombre":"partida2"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "init_third_game":
+ contexto_pos_dialogo = PLAY
+ engine.init_game("partida3_pt",con_jugadas_posibles=False,nivel=Ai.DIFICIL)
+ self.__juego = {"nombre":"partida3"}
+ video.init_game_elements(engine.juego, engine.get_audio())
+ elif self.__accion['nombre'] == "prematch_phrase":
+ contexto_pos_dialogo = PLAY
+ video.text_box.disappear(video.ventana)
+ video.init_game_elements(self.__juego["objeto"], engine.get_audio())
+ elif self.__accion['nombre'] == "dp_revancha" or \
+ self.__accion['nombre'] == "dp_juego_empatado_o_ganado":
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ elif self.__accion['nombre'] == "dial_dp_juego_perdido":
+ usuario = engine.get_user()
+ contexto_pos_dialogo = DIAL
+ if usuario.get_character_relation(self.get_name()) == WON1:
+ engine.get_audio().play_fx_sound("otros","medalla_bronce")
+ video.show_medal(BRONZE)
+ usuario.save_medal("bronce")
+ self.__medalla = BRONZE
+ if usuario.get_character_relation(self.get_name()) == WON2:
+ engine.get_audio().play_fx_sound("otros","medalla_plata")
+ video.show_medal(PLATA)
+ usuario.delete_medal("bronce")
+ usuario.save_medal("plata")
+ self.__medalla = PLATA
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ engine.get_audio().play_fx_sound("otros","medalla_oro")
+ video.show_medal(ORO)
+ usuario.delete_medal("plata")
+ usuario.save_medal("oro")
+ self.__medalla = ORO
+ engine.get_audio().wait_sound_end(tiempo=600)
+ if usuario.get_character_relation(self.get_name()) == WON3:
+ self.set_current_action({"nombre":"dp_entregar_medalla","continua_con_dialogo":True})
+ else:
+ self.set_current_action({"nombre":"dp_entregar_medalla","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "dp_entregar_medalla":
+ if self.__medalla != "":
+ video.dissapear_medal(self.__medalla)
+ self.__medalla = ""
+ if usuario.get_character_relation('protasio') == WON3:
+ contexto_pos_dialogo = DIAL
+ engine.get_dialog_manager().begin_dialogue("pt_give_trophy")
+ self.set_current_action({"nombre":"give_trophy","continua_con_dialogo":True})
+ else:
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "won_game")
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ engine.change_state(accion['nuevo_estado'])
+ elif self.__accion['nombre'] == "give_trophy":
+ engine.get_audio().play_fx_sound("otros","trofeo_madera")
+ video.show_trophy(MADERA)
+ pygame.time.wait(800)
+ video.dissapear_trophy(MADERA)
+ engine.get_dialog_manager().begin_dialogue("pt_match3_lose_cont")
+ self.set_current_action({"nombre":"match3_lose_cont","continua_con_dialogo":False})
+ elif self.__accion['nombre'] == "match3_lose_cont":
+ if usuario.get_character_relation('don cano') == CHALLENGES_COMPLETED:
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "won_game_and_challenges_completed")
+ usuario.set_skill_level(ALL_CLEAR)
+ contexto_pos_dialogo = DIAL
+ nueva_hab = usuario.get_current_room().get_left_room()
+ video.club.move_to_another_room(nueva_hab,IZQUIERDA,extra="final_juego")
+ usuario.set_current_room(nueva_hab)
+ else:
+ accion = self.__find_action(usuario.get_state().get_state_actions(), "won_game")
+ usuario.set_skill_level(CLEAR_GAMES)
+ contexto_pos_dialogo = NAVE
+ engine.get_navigation_manager().leave_room()
+ engine.change_state(accion['nuevo_estado'])
+ return contexto_pos_dialogo
+
+ def close_game(self, engine):
+ ganador = engine.juego.get_final_result()
+ resultado = ""
+ video = engine.get_video()
+ video.dissapear_scores()
+ video.dissapear_board()
+ if ganador != "":
+ if ganador.get_name() == PC:
+ resultado = GANAR
+ else:
+ resultado = PERDER
+ else:
+ resultado = EMPATAR
+ if resultado == PERDER:
+ if self.__juego['nombre'] == "partida1":
+ engine.get_dialog_manager().begin_dialogue("pt_perdio_juego1")
+ engine.get_user().set_character_relation(self.get_name(),WON1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_dialog_manager().begin_dialogue("pt_perdio_juego2")
+ engine.get_user().set_character_relation(self.get_name(),WON2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_dialog_manager().begin_dialogue("pt_perdio_juego3")
+ engine.get_user().set_character_relation(self.get_name(),WON3)
+ elif self.__juego['nombre'] == "revancha":
+ engine.get_dialog_manager().begin_dialogue("pt_perdio_revancha")
+ else:
+ if resultado == EMPATAR:
+ engine.get_dialog_manager().begin_dialogue("pt_empato_juego")
+ if self.__juego['nombre'] == "partida1":
+ engine.get_user().set_character_relation(self.get_name(),DRAW1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_user().set_character_relation(self.get_name(),DRAW2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_user().set_character_relation(self.get_name(),DRAW3)
+ elif resultado == GANAR:
+ engine.get_dialog_manager().begin_dialogue("pt_gano_juego")
+ if self.__juego['nombre'] == "partida1":
+ engine.get_user().set_character_relation(self.get_name(),LOSE1)
+ elif self.__juego['nombre'] == "partida2":
+ engine.get_user().set_character_relation(self.get_name(),LOSE2)
+ elif self.__juego['nombre'] == "partida3":
+ engine.get_user().set_character_relation(self.get_name(),LOSE3)
+ contexto_pos_juego = DIAL
+ if self.__juego['nombre'] == "revancha":
+ self.set_current_action({"nombre":"dp_revancha","continua_con_dialogo":False})
+ else:
+ if resultado == PERDER:
+ self.set_current_action({"nombre":"dial_dp_juego_perdido","continua_con_dialogo":True})
+ else:
+ self.set_current_action({"nombre":"dp_juego_empatado_o_ganado","continua_con_dialogo":False})
+ return contexto_pos_juego
diff --git a/src/hyperhistory/character.pyc b/src/hyperhistory/character.pyc Binary files differnew file mode 100644 index 0000000..39bcb59 --- /dev/null +++ b/src/hyperhistory/character.pyc diff --git a/src/hyperhistory/club.py b/src/hyperhistory/club.py new file mode 100755 index 0000000..9b7ce79 --- /dev/null +++ b/src/hyperhistory/club.py @@ -0,0 +1,144 @@ +from room import Room
+from character import Character, ChPedroMadera, ChDonCano, ChPabloGris, ChSofiaDulce, ChProtasio
+from _xml.parser import Parser
+import os
+
+class Club:
+ def __init__(self, main_path):
+ self.__characters = []
+ self.__rooms = []
+ self.__elevator = {"seleccionado" : False, "direccion" : ""}
+ #Al comienzo no hay ninguna habitacion seleccionada
+ self.__hab_seleccionada = {"habitacion" : "", "posicion" : ""}
+
+ xml_info = self.__get_xml_info(os.path.abspath(main_path + "/data/club.xml"),"configuration")
+ self.__init_characters(xml_info)
+ self.__init_rooms(xml_info)
+ #Recorro todas las habitaciones y cargo para cada una la habitaciones que le rodean
+ xml_info = self.__get_xml_info(os.path.abspath(main_path + "/data/club.xml"),"navigation")
+ self.__set_navegation(xml_info)
+
+ def __init_characters(self, config_info):
+ for p in config_info:
+ if p.get_name() == 'character':
+ if p.get_attribute('name') == "pedro madera":
+ self.__characters.append(ChPedroMadera(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+ elif p.get_attribute('name') == "don cano":
+ self.__characters.append(ChDonCano(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+ elif p.get_attribute('name') == "pablo gris":
+ self.__characters.append(ChPabloGris(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+ elif p.get_attribute('name') == "sofia dulce":
+ self.__characters.append(ChSofiaDulce(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+ elif p.get_attribute('name') == "protasio":
+ self.__characters.append(ChProtasio(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+ else:
+ self.__characters.append(Character(nombre=p.get_attribute('name'),id=p.get_attribute('id')))
+
+ def __init_rooms(self, config_info):
+ for e in config_info:
+ if e.get_name() == 'room':
+ piso = False
+ if e.get_attribute('floor') == 'yes':
+ piso = True
+ personaje = ""
+ if e.get_attribute('owner') != '':
+ personaje = self.__get_character(e.get_attribute('owner'))
+ self.__rooms.append(Room(nombre=e.get_attribute('name'),especial=piso,duenho=personaje,id=e.get_attribute('id')))
+ elif e.get_name() == 'alone_initial_room':
+ self.__alone_initial_room = e.get_attribute('id')
+ elif e.get_name() == 'shared_initial_room':
+ self.__shared_initial_room = e.get_attribute('id')
+
+ #Seteo las habitaciones que le rodean a cada habitacion
+ def __set_navegation(self, nav_info):
+ hab = ""
+ for e in nav_info:
+ if e.get_name() == 'room':
+ hab = self.__get_room(e.get_attribute('id'))
+ if e.get_name() == 'connection':
+ if hab != "":
+ if e.get_attribute('up') != '':
+ aux_hab = self.__get_room(e.get_attribute('up'))
+ hab.set_up_room(aux_hab)
+ if e.get_attribute('down') != '':
+ aux_hab = self.__get_room(e.get_attribute('down'))
+ hab.set_down_room(aux_hab)
+ if e.get_attribute('left') != '':
+ aux_hab = self.__get_room(e.get_attribute('left'))
+ hab.set_left_room(aux_hab)
+ if e.get_attribute('right') != '':
+ aux_hab = self.__get_room(e.get_attribute('right'))
+ hab.set_right_room(aux_hab)
+ hab = ""
+
+ def __get_character(self, id):
+ for p in self.__characters:
+ if p.get_id() == id:
+ return p
+
+ def get_character_by_name(self, nombre):
+ for p in self.__characters:
+ if p.get_name() == nombre:
+ return p
+
+ def __get_xml_info(self,archivo,etiqueta):
+ f = open(archivo)
+ p = Parser()
+ return p.find_child_element(etiqueta,f)
+
+ def __set_state(self,state_info):
+ self.__set_rooms_state(state_info)
+ self.__set_characters_state(state_info)
+
+ def __set_characters_state(self, estado):
+ for c in estado.get_characters_state().items():
+ id = c[0]
+ per = self.__get_character(id)
+ per.set_available_to_play(c[1]['juego'])
+ per.set_available_to_talk(c[1]['dialogo'])
+
+ def __set_rooms_state(self,estado):
+ for r in estado.get_rooms_state().items():
+ id = r[0]
+ hab = self.__get_room(id)
+ hab.set_available(r[1]['habilitada'])
+
+ def __get_room(self, id):
+ for r in self.__rooms:
+ if r.get_id() == id:
+ return r
+
+ def get_rooms(self):
+ return self.__rooms
+
+ def get_room_by_name(self, nombre):
+ for r in self.__rooms:
+ if r.get_name() == nombre:
+ return r
+
+ def get_alone_initial_room(self):
+ return self.__get_room(self.__alone_initial_room)
+
+ def get_shared_initial_room(self):
+ return self.__get_room(self.__shared_initial_room)
+
+ def set_current_state(self, estado_actual):
+ self.__set_state(estado_actual)
+
+ def select_room(self, hab, direccion):
+ self.__hab_seleccionada["habitacion"] = hab
+ self.__hab_seleccionada["posicion"] = direccion
+
+ def room_selected(self):
+ return self.__hab_seleccionada
+
+ def select_elevator(self, direccion):
+ self.__elevator["seleccionado"] = True
+ self.__elevator["direccion"] = direccion
+
+ def unselect_elevator(self):
+ self.__elevator["seleccionado"] = False
+ self.__elevator["direccion"] = ""
+
+ def get_elevator(self):
+ return self.__elevator
diff --git a/src/hyperhistory/club.pyc b/src/hyperhistory/club.pyc Binary files differnew file mode 100644 index 0000000..3f557c3 --- /dev/null +++ b/src/hyperhistory/club.pyc diff --git a/src/hyperhistory/dialog.py b/src/hyperhistory/dialog.py new file mode 100755 index 0000000..dd9d4aa --- /dev/null +++ b/src/hyperhistory/dialog.py @@ -0,0 +1,1163 @@ +from _xml.parser import Parser
+from main.constants import DIAL, IZQUIERDA, ARRIBA, ABAJO, DERECHA, SELECCION, TUTORIAL1, CHALLENGE1, CHALLENGE2, WON3, TUTORIAL2, CONTINUAR, \
+ BRONZE, PLATA, ORO, CHALLENGE3, CHALLENGE4, NULL, CHALLENGES_COMPLETED, ORO
+from othello.utils import Coordinate
+from othello.referee import Referee
+import thread, os, time, logging, pygame
+
+#Dialog States
+INICIO_DIALOGO = -900
+ESPERANDO_ACCION = -901
+ESPERANDO_CONTINUAR = -902
+ESPERANDO_ACCION_ESPECIAL = -904
+ACCION_DESAFIO = -905
+TERMINO_DIALOGO = -903
+
+log = logging.getLogger( 'src.hyperhistory.dialog' )
+log.setLevel( logging.DEBUG )
+
+class DialogueManager:
+ def __init__(self, main_path="", write_path="", engine="", dialogue_file_name=""):
+ if engine == "":
+ raise Exception("Error!, dialogo necesita engine para funcionar")
+ if main_path == "":
+ raise Exception("Error!, dialogo necesita el path principal para funcionar")
+ self.__textos = []
+ #self.__main_path = main_path + "/resources/sounds/club/personajes"
+ self.__hay_dialogo_abierto = False
+ self.__club = engine.get_club()
+ self.__audio = engine.get_audio()
+ self.__video = engine.get_video()
+ self.__keys = engine.get_keys()
+ self.__navegacion = engine.get_navigation_manager()
+ self.__usuario = engine.get_user()
+ self.__engine = engine
+ if dialogue_file_name == "":
+ self.__nombre_archivo = os.path.abspath(main_path + "/data/scripts/es.xml")
+ else:
+ self.__nombre_archivo = dialogue_file_name
+ self.__datos_dialogo = {}
+ self.__datos_dialogo["etiqueta"] = {}
+ self.__datos_dialogo["cantidad_grupos"] = 0
+ self.__accion_entrada = {}
+ self.__estado_dialogo = ""
+ self.__textos_dialogo_error = ""
+ self.__texto_a_mostrar = ""
+ self.__last_sounds = []
+ self.__nombre_dialogo = ""
+ self.__error_desafio = False
+ try:
+ f = open(os.path.abspath(write_path + "/data/dialog.log"),'r')
+ f.close()
+ self.__log_file = open(os.path.abspath(write_path + "/data/dialog.log"),'a')
+ print >> self.__log_file, '\nDIALOG LOG: ' + time.asctime()
+ except:
+ self.__log_file = open(os.path.abspath(write_path + "/data/dialog.log"),'w')
+ print >> self.__log_file, 'DIALOG LOG: ' + time.asctime()
+
+ def __del__(self):
+ self.__log_file.close()
+
+ def __get_label(self):
+ if self.__nombre_dialogo == "pg_bienvenida":
+ return self.__datos_dialogo["etiqueta"]["id"] + str(self.__datos_dialogo["etiqueta"]["grupo"])
+ elif self.__nombre_dialogo == "pg_tutorial1" or \
+ self.__nombre_dialogo == "pg_tutorial2":
+ if self.__datos_dialogo["etiqueta"]["grupo"] < 10:
+ return self.__datos_dialogo["etiqueta"]["id"] + "0" + str(self.__datos_dialogo["etiqueta"]["grupo"])
+ else:
+ return self.__datos_dialogo["etiqueta"]["id"] + str(self.__datos_dialogo["etiqueta"]["grupo"])
+ else:
+ return self.__datos_dialogo["etiqueta"]["id"][self.__datos_dialogo["etiqueta"]["grupo"]]
+
+ def begin_dialogue(self, nombre, grupo_inicial=0):
+ self.__datos_dialogo["cantidad_grupos"] = 0
+ self.__datos_dialogo["etiqueta"]["grupo"] = grupo_inicial
+ if nombre == "pg_bienvenida":
+ self.__datos_dialogo["etiqueta"]["id"] = "INI0"
+ self.__datos_dialogo["cantidad_grupos"] = 5
+ elif nombre == "pg_tutorial1":
+ self.__datos_dialogo["etiqueta"]["id"] = "TUT1"
+ self.__datos_dialogo["cantidad_grupos"] = 26
+ elif nombre == "pg_tutorial2":
+ self.__datos_dialogo["etiqueta"]["id"] = "PG_TUT2_"
+ self.__datos_dialogo["cantidad_grupos"] = 8
+ elif nombre == "pm_bloqueo_acceso_piso2_1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_BLOCK_VOCALS_MEET","PM_INTRO_VOCALS","PM_BLOCK_VOCALS_GO_TUT1"]
+ elif nombre == "pm_bloqueo_acceso_piso2_2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_BLOCK_VOCALS_GO_TUT1_AGAIN"]
+ elif nombre == "dc_bienvenida_ir_tut":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_MEET","DC_GO_TUT1"]
+ elif nombre == "dc_ir_tut":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_TUT1_AGAIN"]
+ elif nombre == "dc_bienvenida_comenzar_chal_1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_MEET","DC_START_CHAL1","DC_CHAL1_EXPLAIN_GOAL","DC_A1_TIP"]
+ elif nombre == "dc_saludo_comenzar_chal_1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_HI","DC_START_CHAL1","DC_A1_TIP"]
+ elif nombre == "dc_consejo_desafio_a1" or nombre == "dc_retake_chal_a1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_A1_TIP"]
+ elif nombre == "dc_ask_select_option_list":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_ASK_FOR_RETRY"]
+ elif nombre == "dc_ok_challenge_check_answer":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CHECK_ANSWER"]
+ elif nombre == "dc_consejo_desafio_a2" or nombre == "dc_retake_chal_a2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_A2_TIP"]
+ elif nombre == "dc_continue_chal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CONTINUE_CHAL1"]
+ elif nombre == "dc_finalizar_chal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_FINALIZE_CHAL1","DC_BYE"]
+ elif nombre == "dc_bye":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_BYE"]
+ elif nombre == "dc_go_pm1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_PM1"]
+ elif nombre == "dc_go_pm2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_PM2"]
+ elif nombre == "dc_go_pm3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_PM3"]
+ elif nombre == "dc_chal_retake":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CHAL_RETAKE"]
+ elif nombre == "dc_saludo_comenzar_chal_2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_HI","DC_START_CHAL2","DC_A3_TIP"]
+ elif nombre == "dc_consejo_desafio_a3" or nombre == "dc_retake_chal_a3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_A3_TIP"]
+ elif nombre == "dc_continue_chal2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CONTINUE_CHAL2"]
+ elif nombre == "dc_consejo_desafio_a4" or nombre == "dc_retake_chal_a4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_A4_TIP"]
+ elif nombre == "dc_consejo_desafio_a5" or nombre == "dc_retake_chal_a5":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_A5_TIP"]
+ elif nombre == "dc_finalizar_chal2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_FINALIZE_CHAL2","DC_BYE"]
+ elif nombre == "dc_saludo_comenzar_chal_3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_HI","DC_START_CHAL3","DC_B1_TIP"]
+ elif nombre == "dc_consejo_desafio_b1" or nombre == "dc_retake_chal_b1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_B1_TIP"]
+ elif nombre == "dc_retake_chal_b2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_B2_TIP"]
+ elif nombre == "dc_retake_chal_b3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_B3_TIP"]
+ elif nombre == "dc_retake_chal_b4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_B4_TIP"]
+ elif nombre == "dc_retake_chal_b5":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_B5_TIP"]
+ elif nombre == "dc_go_tut2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_TUT2"]
+ elif nombre == "dc_give_retro_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GIVE_RETRO_MEDALS"]
+ elif nombre == "dc_explain_medals_finalizar_chal_3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_EXPLAIN_MEDALS","DC_BYE"]
+ elif nombre == "dc_go_sd1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_SD"]
+ elif nombre == "dc_give_gold":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GIVE_GOLD"]
+ elif nombre == "dc_give_silver":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GIVE_SILVER"]
+ elif nombre == "dc_give_bronze":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GIVE_BRONZE"]
+ elif nombre == "dc_saludo_comenzar_chal_4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_HI","DC_START_CHAL4","DC_C1_TIP"]
+ elif nombre == "dc_finalizar_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_FINALIZE_CHAL4","DC_BYE"]
+ elif nombre == "dc_retake_chal_c1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_C1_TIP"]
+ elif nombre == "dc_retake_chal_c2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_C2_TIP"]
+ elif nombre == "dc_retake_chal_c3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_C3_TIP"]
+ elif nombre == "dc_retake_chal_c4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_C4_TIP"]
+ elif nombre == "dc_retake_chal_c5":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_C5_TIP"]
+ elif nombre == "dc_go_pt1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GO_PT"]
+ elif nombre == "dc_go_pt2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_HI","DC_GO_PT2"]
+ elif nombre == "dc_get_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_GET_MEDALS"]
+ elif nombre == "dc_pt_defeated":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_PT_DEFEATED"]
+ elif nombre == "dc_chals_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CHALS_CLEAR"]
+ elif nombre == "dc_chals_completed":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_CHALS_COMPLETED"]
+ elif nombre == "dc_all_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["DC_ALL_CLEAR"]
+ elif nombre == "pg_go_pm1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_PM1"]
+ elif nombre == "pg_go_pm2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_PM2"]
+ elif nombre == "pg_go_pm3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_PM3"]
+ elif nombre == "pg_go_sd":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_SD"]
+ elif nombre == "pg_go_pt1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_PT"]
+ elif nombre == "pg_go_pt2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_PT2"]
+ elif nombre == "pg_chal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_CHAL1"]
+ elif nombre == "pg_go_chal2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_CHAL2"]
+ elif nombre == "pg_go_chal3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_CHAL3"]
+ elif nombre == "pg_go_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GO_CHAL4"]
+ elif nombre == "pg_retake":
+ self.__datos_dialogo["etiqueta"]["id"] = ["TUT_RETAKE"]
+ elif nombre == "pg_intro_retake_leason":
+ self.__datos_dialogo["etiqueta"]["id"] = ["TUT_RETAKE1"]
+ elif nombre == "pg_get_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_GET_MEDALS"]
+ elif nombre == "pg_pt_defeated":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_PT_DEFEATED"]
+ elif nombre == "pg_all_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PG_ALL_CLEAR"]
+ elif nombre == "pm_first_meet_go_chal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MEET_SHOW_ROOM","PM_INTRO_VOCALS","PM_GO_CHAL1"]
+ elif nombre == "pm_intro_room_go_chal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_SHOW_ROOM","PM_GO_CHAL1"]
+ elif nombre == "pm_intro_room_go_chal1_again":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_CHAL1_AGAIN"]
+ elif nombre == "pm_first_meet_first_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MEET_SHOW_ROOM","PM_INTRO_VOCALS","PM_MATCH1_NMET","PM_MATCH1","PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_intro_room_first_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_SHOW_ROOM","PM_MATCH1_MET","PM_MATCH1","PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_init_first_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_HI","PM_MATCH1_MET","PM_MATCH1","PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_prematch_phrase":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_hi_go_chal2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_HI","PM_GO_CHAL2"]
+ elif nombre == "pm_init_second_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH2","PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_init_third_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH3","PM_PREMATCH_PHRASE"]
+ elif nombre == "pm_gano_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH_WIN"]
+ elif nombre == "pm_perdio_juego1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH1_LOSE"]
+ elif nombre == "pm_perdio_juego2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH2_LOSE"]
+ elif nombre == "pm_perdio_juego3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH3_LOSE"]
+ elif nombre == "pm_bye":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH3_GIVE_MEDAL"]
+ elif nombre == "pm_empato_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_MATCH_DRAW"]
+ elif nombre == "pm_go_tut2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_TUT2","PM_PREREMATCH"]
+ elif nombre == "pm_go_chal3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_CHAL3","PM_PREREMATCH"]
+ elif nombre == "pm_prerematch":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_PREREMATCH"]
+ elif nombre == "pm_rematch":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_REMATCH"]
+ elif nombre == "pm_perdio_revancha":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_REMATCH_LOSE"]
+ elif nombre == "pm_gano_revancha":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_REMATCH_WIN"]
+ elif nombre == "pm_go_sd":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_SD","PM_PREREMATCH"]
+ elif nombre == "pm_go_pt1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_PT","PM_PREREMATCH"]
+ elif nombre == "pm_go_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_CHAL4","PM_PREREMATCH"]
+ elif nombre == "pm_go_pt2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GO_PT2","PM_PREREMATCH"]
+ elif nombre == "pm_get_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_GET_MEDALS","PM_PREREMATCH"]
+ elif nombre == "pm_pt_defeated":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_PT_DEFEATED","PM_PREREMATCH"]
+ elif nombre == "pm_all_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PM_ALL_CLEAR","PM_PREREMATCH"]
+ elif nombre == "sd_presentation":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_INTRO"]
+ elif nombre == "sd_go_tut2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_GO_TUT2"]
+ elif nombre == "sd_go_chal3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_GO_CHAL3"]
+ elif nombre == "sd_go_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_GO_CHAL4","SD_PREREMATCH"]
+ elif nombre == "sd_go_pt2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_GO_PT2","SD_PREREMATCH"]
+ elif nombre == "sd_init_first_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH1","SD_PREMATCH_PHRASE"]
+ elif nombre == "sd_init_second_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH2","SD_PREMATCH_PHRASE"]
+ elif nombre == "sd_init_third_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH3","SD_PREMATCH_PHRASE"]
+ elif nombre == "sd_prematch_phrase":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_PREMATCH_PHRASE"]
+ elif nombre == "sd_rematch_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_REMATCH"]
+ elif nombre == "sd_perdio_juego1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH1_LOSE"]
+ elif nombre == "sd_perdio_juego2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH2_LOSE"]
+ elif nombre == "sd_perdio_juego3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH3_LOSE"]
+ elif nombre == "sd_perdio_revancha":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_REMATCH_LOSE"]
+ elif nombre == "sd_empato_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH_DRAW"]
+ elif nombre == "sd_gano_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH_WIN"]
+ elif nombre == "sd_give_medal1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH1_GIVE_MEDAL"]
+ elif nombre == "sd_give_medal2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH2_GIVE_MEDAL"]
+ elif nombre == "sd_give_medal3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_MATCH3_GIVE_MEDAL"]
+ elif nombre == "sd_get_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_GET_MEDALS","SD_PREREMATCH"]
+ elif nombre == "sd_pt_defeated":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_PT_DEFEATED","SD_PREREMATCH"]
+ elif nombre == "sd_all_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["SD_ALL_CLEAR","SD_PREREMATCH"]
+ elif nombre == "pt_intro_infection_go_sd":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_INTRO","PT_INFECTION","PT_INFECTION2","PT_GO_SD"]
+ elif nombre == "pt_intro_go_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_INTRO","PT_INFECTION","PT_INFECTION2","PT_GO_CHAL4"]
+ elif nombre == "pt_go_chal4":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_GO_CHAL4"]
+ elif nombre == "pt_go_sd":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_GO_SD"]
+ elif nombre == "pt_init_first_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH1","PT_PREMATCH_PHRASE"]
+ elif nombre == "pt_init_second_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH2","PT_PREMATCH_PHRASE"]
+ elif nombre == "pt_init_third_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3","PT_PREMATCH_PHRASE"]
+ elif nombre == "pt_rematch_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_REMATCH"]
+ elif nombre == "pt_prematch_phrase":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_PREMATCH_PHRASE"]
+ elif nombre == "pt_perdio_juego1":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH1_LOSE"]
+ elif nombre == "pt_perdio_juego2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH2_LOSE"]
+ elif nombre == "pt_perdio_juego3":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_LOSE"]
+ elif nombre == "pt_perdio_revancha":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_REMATCH_LOSE"]
+ elif nombre == "pt_empato_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH_DRAW"]
+ elif nombre == "pt_gano_juego":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH_WIN"]
+ elif nombre == "pt_pt_defeated":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_PT_DEFEATED","PT_PREREMATCH"]
+ elif nombre == "pt_all_clear":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_ALL_CLEAR","PT_PREREMATCH"]
+ elif nombre == "pt_match2_more_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH2_MORE_MEDALS"]
+ elif nombre == "pt_match3_more_medals":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_MORE_MEDALS"]
+ elif nombre == "pt_go_sd2":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_GO_SD"]
+ elif nombre == "pt_give_trophy":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_GIVE_TROPHY"]
+ elif nombre == "pt_match3_lose_cont":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_LOSE_CONT"]
+ elif nombre == "pt_best_player":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_MATCH3_LOSE_CONT"]
+ elif nombre == "end_game":
+ self.__datos_dialogo["etiqueta"]["id"] = ["PT_END1","PG_END1","DC_END1","PM_END1","SD_END1","PT_END2","PG_END2","DC_END2","PM_END2","SD_END2"]
+ else:
+ log.info("No existe un dialogo asociado al nombre " + nombre)
+ if self.__datos_dialogo["cantidad_grupos"] == 0:
+ self.__datos_dialogo["cantidad_grupos"] = len(self.__datos_dialogo["etiqueta"]["id"]) - 1
+ self.__nombre_dialogo = nombre
+ self.__hay_dialogo_abierto = True
+ self.__error_desafio = False
+ self.__get_dialogue_from_file(self.__get_label())
+ self.__estado_dialogo = INICIO_DIALOGO
+ self.__textos_dialogo_error = ""
+ self.manage_dialogue()
+
+ def get_dialogue_name(self):
+ return self.__nombre_dialogo
+
+ def __get_dialogue_from_file(self, etiqueta):
+ f = open(self.__nombre_archivo)
+ p = Parser()
+ self.__textos = p.find_child_element(etiqueta,f)
+ if self.__textos == "":
+ raise Exception("Error!, No se encontro la etiqueta de dialogo requerida (DialogueManager Class)")
+ f.close()
+ p.close()
+
+ def __are_texts_in_group(self):
+ if len(self.__textos) > 0:
+ return True
+ else:
+ return False
+
+ def __wait_special_input(self, elemento):
+ if 'input' in elemento.get_attributes():
+ self.__accion_entrada["tipo"] = "simple"
+ self.__accion_entrada["entrada_esperada"] = int(elemento.get_attribute('constant_key'))
+ return True
+ elif 'special_input' in elemento.get_attributes():
+ self.__accion_entrada["tipo"] = "especial"
+ self.__accion_entrada["entrada_esperada"] = int(elemento.get_attribute('constant_key'))
+ self.__accion_entrada["nombre_accion_especial"] = elemento.get_attribute('id')
+ self.__accion_entrada["teclas_permitidas_accion"] = [IZQUIERDA,DERECHA,ARRIBA,ABAJO,SELECCION]
+ return True
+ else:
+ return False
+
+ def __read_next_texts_group(self, etiqueta_extra="", etiqueta_error_desafio=""):
+ if etiqueta_error_desafio == "":
+ if self.__textos_dialogo_error == "":
+ self.__datos_dialogo["etiqueta"]["grupo"] += 1
+ self.__get_dialogue_from_file(self.__get_label()+etiqueta_extra)
+ else:
+ self.__get_dialogue_from_file(etiqueta_error_desafio)
+
+ def __save_last_text(self, ultimo_texto):
+ self.__last_text = ultimo_texto
+
+ def __end_dialogue(self):
+ if self.__datos_dialogo["etiqueta"]["grupo"] < self.__datos_dialogo["cantidad_grupos"]:
+ return False
+ if self.__datos_dialogo["etiqueta"]["grupo"] == self.__datos_dialogo["cantidad_grupos"]:
+ if self.__textos_dialogo_error != "":
+ #Si estaba en el dialogo de error del ultimo grupo
+ return False
+ else:
+ if not self.__are_texts_in_group():
+ #Si ya no quedan textos en el ultimo grupo de dialogo y no estoy viniendo de dialogo de error
+ return True
+ else:
+ #Si quedan todavia textos en el grupo de dialogo
+ return False
+ else:
+ return True
+
+ def __advance_dialogue(self):
+ if not self.__end_dialogue():
+ if not self.__are_texts_in_group():
+ self.__read_next_texts_group()
+ self.show_dialogue()
+ else:
+ self.__estado_dialogo = TERMINO_DIALOGO
+
+ def __go_to_error_dialogue(self):
+ if self.__textos_dialogo_error == "":
+ self.__read_next_texts_group(etiqueta_extra="_NO")
+ self.__textos_dialogo_error = list(self.__textos)
+ else:
+ self.__textos = self.__textos_dialogo_error
+ self.__show_error_dialogue()
+
+ def challenge_error(self):
+ return self.__error_desafio
+
+ def __play_in_possible_move(self):
+ coord_actual = self.__video.board.get_coord_selected_cell()
+ for coord_jp in self.__jugadas_posibles_desafio:
+ if coord_jp.equal(coord_actual):
+ return True
+ return False
+
+ #Creo esta funcion porque la manera de manejar los errores en los desafios es totalmente distinta a los tutoriales
+ def __go_to_challenge_error_dialogue(self):
+ self.__error_desafio = True
+ coord_actual = self.__video.board.get_coord_selected_cell()
+ self.__engine.juego.play(coord_actual,self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"change_score_color":False})
+ if self.__accion_entrada["nombre_accion_especial"] == "desafio_a1" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_a2" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_a3" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_a4":
+ self.__read_next_texts_group(etiqueta_error_desafio="DC_WRONG_ANSWER_MAXIMIZE")
+ self.show_dialogue()
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+ self.__keys.disable_keys(self.__accion_entrada["teclas_permitidas_accion"],DIAL)
+ self.__accion_entrada.clear()
+ self.__video.text_box.delete_text()
+
+
+ def repeat_dialogue(self):
+ self.__video.text_box.show_text(self.__video.ventana,self.__last_text)
+ for s in self.__last_sounds:
+ self.__audio.play_character_voice(s["character"],s["sonido"])
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+
+ def ended_dialogue(self):
+ if self.__estado_dialogo == TERMINO_DIALOGO:
+ return True
+ else:
+ return False
+
+ def __ok_waited_input(self, entrada):
+ if self.__accion_entrada["tipo"] == "simple":
+ if entrada == self.__accion_entrada["entrada_esperada"]:
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["tipo"] == "especial":
+ if self.__accion_entrada["nombre_accion_especial"] == "jugada_4_3":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(3,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False})
+ self.__video.text_box.refresh_text_box(self.__video.ventana)
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "jugada_2_1":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(1,2))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__video.text_box.refresh_text_box(self.__video.ventana)
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "jugada_1_6":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(6,1))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__video.text_box.refresh_text_box(self.__video.ventana)
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "movimiento_4_1":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(1,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_a1":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(4,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False,"change_score_color":False})
+ #self.__video.text_box.refresh_text_box(self.__video.ventana)
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_a2":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(2,3))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False,"change_score_color":False})
+ #self.__video.text_box.refresh_text_box(self.__video.ventana)
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_a3":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(1,6))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False,"change_score_color":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_a4":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(2,3))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False,"change_score_color":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_a5":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(3,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False,"change_score_color":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b1":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(1,6))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b2":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(3,1))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b3":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(6,6))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b4":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(3,1))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b5":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(1,1))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_c1":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(4,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_c2":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(2,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_c3":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(4,4))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_c4":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(2,2))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_c5":
+ coord = self.__video.board.graphic_coord_to_logic_coord(Coordinate(6,6))
+ if self.__video.board.get_coord_selected_cell().equal(coord):
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana, {"play_turn_sound":False})
+ self.__error_desafio = False
+ return True
+ else:
+ return False
+ elif self.__accion_entrada["nombre_accion_especial"] == "recorrer_tablero":
+ return True
+
+
+ def __print_log(self, mensaje):
+ try:
+ print >> self.__log_file, mensaje
+ except:
+ print mensaje
+
+ def manage_dialogue(self, datos_adicionales=""):
+ if self.__estado_dialogo == ESPERANDO_ACCION:
+ if self.__ok_waited_input(datos_adicionales):
+ self.__keys.disable_key(self.__accion_entrada["entrada_esperada"],DIAL)
+ self.__accion_entrada.clear()
+ self.__advance_dialogue()
+ if self.__estado_dialogo == ESPERANDO_CONTINUAR:
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+ else:
+ tecla_esperada = self.__keys.get_key_by_constant(self.__accion_entrada["entrada_esperada"]).get_name()
+ tecla_recibida = self.__keys.get_key_by_constant(datos_adicionales).get_name()
+ self.__print_log("Error se esperaba tecla: " + tecla_esperada + " se recibio: " + tecla_recibida)
+ self.__go_to_error_dialogue()
+ elif self.__estado_dialogo == ESPERANDO_ACCION_ESPECIAL:
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.marcador.refresh(self.__video.ventana)
+ if datos_adicionales == self.__accion_entrada["entrada_esperada"]:
+ if self.__ok_waited_input(datos_adicionales):
+ #Respondio correctamente
+ if self.__accion_entrada["nombre_accion_especial"] == "desafio_b1" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b2" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b3" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b4" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b5":
+ #Si es un DESAFIO B
+ self.__audio.play_init_turn_sounds(self.__video.board,self.__engine.juego,leer_turno_nro=False)
+ self.__jugada_usuario = self.__video.board.get_coord_selected_cell()
+ self.__estado_dialogo = ACCION_DESAFIO
+ else:
+ self.__keys.disable_keys(self.__accion_entrada["teclas_permitidas_accion"],DIAL)
+ self.__accion_entrada.clear()
+ self.__advance_dialogue()
+ if self.__estado_dialogo == ESPERANDO_CONTINUAR:
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+ else:
+ #No respondio correctamente
+ coord_sel = self.__video.board.get_coord_selected_cell()
+ self.__print_log("Se esperaba: " + self.__accion_entrada["nombre_accion_especial"] + " se recibio jugada en: " + str(coord_sel))
+ if self.__accion_entrada["nombre_accion_especial"].find("desafio") == 0:
+ #Si es un DESAFIO
+ if self.__play_in_possible_move():
+ #Si jugo en una jugada posible
+ if self.__accion_entrada["nombre_accion_especial"] == "desafio_b1" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b2" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b3" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b4" or \
+ self.__accion_entrada["nombre_accion_especial"] == "desafio_b5":
+ self.__engine.juego.play(coord_sel,self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False})
+ self.__audio.play_init_turn_sounds(self.__video.board,self.__engine.juego,leer_turno_nro=False)
+ self.__jugada_usuario = coord_sel
+ self.__estado_dialogo = ACCION_DESAFIO
+ self.__error_desafio = True
+ else:
+ self.__go_to_challenge_error_dialogue()
+ else:
+ #Dar error DC_WRONG_ANSWER_NOT_PLAYABLE y continua intentando
+ self.__audio.play_fx_sound("board","mal_mov")
+ if self.__accion_entrada["nombre_accion_especial"].find("c") == -1:
+ self.__read_next_texts_group(etiqueta_error_desafio="DC_WRONG_ANSWER_NOT_PLAYABLE")
+ else:
+ self.__read_next_texts_group(etiqueta_error_desafio="DC_CHALLENGE_C_NOT_PLAYABLE")
+ self.__show_challenge_error_dialogue()
+ else:
+ self.__go_to_error_dialogue()
+ else:
+ if not datos_adicionales == SELECCION:
+ self.__video.board.do_move(datos_adicionales, self.__audio)
+ else:
+ self.__do_audio_action("cell_info")
+ elif self.__estado_dialogo == ESPERANDO_CONTINUAR or self.__estado_dialogo == INICIO_DIALOGO:
+ self.__advance_dialogue()
+ if self.__estado_dialogo == ESPERANDO_CONTINUAR:
+ #Pregunto de nuevo si el estado es igual a ESPERANDO_CONTINUAR porque pudo haber cambiado despues de pasar por advance_dialog
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+ elif self.__estado_dialogo == ACCION_DESAFIO:
+ self.__video.text_box.disappear(self.__video.ventana)
+ if datos_adicionales == CONTINUAR:
+ if not self.__jugada_usuario == "":
+ if self.__accion_entrada["nombre_accion_especial"] == "desafio_b1":
+ if self.__jugada_usuario.equal_xy(5,2) or self.__jugada_usuario.equal_xy(5,3):
+ self.__engine.juego.play(Coordinate(4,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ else:
+ self.__engine.juego.play(Coordinate(2,3),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b2":
+ if self.__jugada_usuario.equal_xy(1,1) or self.__jugada_usuario.equal_xy(3,0):
+ self.__engine.juego.play(Coordinate(2,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(5,1):
+ self.__engine.juego.play(Coordinate(5,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(4,1):
+ self.__engine.juego.play(Coordinate(4,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(4,3):
+ self.__engine.juego.play(Coordinate(5,3),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(1,3):
+ self.__engine.juego.play(Coordinate(2,4),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(2,4):
+ self.__engine.juego.play(Coordinate(1,5),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b3":
+ if self.__jugada_usuario.equal_xy(0,5):
+ #Respuesta correcta
+ self.__engine.juego.play(Coordinate(3,3),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(1,5):
+ self.__engine.juego.play(Coordinate(2,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(0,3):
+ self.__engine.juego.play(Coordinate(3,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(0,1):
+ self.__engine.juego.play(Coordinate(1,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b4":
+ if self.__jugada_usuario.equal_xy(3,0) or self.__jugada_usuario.equal_xy(4,5):
+ self.__engine.juego.play(Coordinate(4,1),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(2,0) or self.__jugada_usuario.equal_xy(1,1) or self.__jugada_usuario.equal_xy(1,2) or \
+ self.__jugada_usuario.equal_xy(1,3) or self.__jugada_usuario.equal_xy(1,4) or self.__jugada_usuario.equal_xy(1,5) or \
+ self.__jugada_usuario.equal_xy(2,0):
+ self.__engine.juego.play(Coordinate(3,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__accion_entrada["nombre_accion_especial"] == "desafio_b5":
+ if self.__jugada_usuario.equal_xy(0,1) or self.__jugada_usuario.equal_xy(0,3):
+ self.__engine.juego.play(Coordinate(0,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(2,5) or self.__jugada_usuario.equal_xy(4,5):
+ self.__engine.juego.play(Coordinate(3,5),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(3,0):
+ self.__engine.juego.play(Coordinate(2,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(2,0):
+ self.__engine.juego.play(Coordinate(1,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(1,0):
+ self.__engine.juego.play(Coordinate(3,0),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(0,2):
+ self.__engine.juego.play(Coordinate(0,1),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(0,5):
+ self.__engine.juego.play(Coordinate(1,5),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(3,5):
+ self.__engine.juego.play(Coordinate(4,5),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(5,2):
+ self.__engine.juego.play(Coordinate(5,3),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(5,3):
+ self.__engine.juego.play(Coordinate(5,4),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(5,4):
+ self.__engine.juego.play(Coordinate(5,2),self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False,"update_possibles_moves":False})
+ elif self.__jugada_usuario.equal_xy(5,0):
+ #Respuesta correcta
+ self.__audio.play_voice_sound("game", "pasa_el_turno")
+ self.__audio.wait_sound_end()
+ self.__engine.juego.change_turn()
+ self.__video.marcador.render_all(self.__engine.juego.get_board(),self.__engine.juego.get_turn().get_color(),self.__video.ventana)
+ self.__jugada_usuario = ""
+ self.__get_dialogue_from_file("DC_CHECK_ANSWER")
+ self.show_dialogue()
+ self.__estado_dialogo = ACCION_DESAFIO
+ else:
+ self.__video.board.lista_jugadas = Referee.possibles_moves(self.__engine.juego.get_turn().get_color(),self.__engine.juego.get_board())
+ self.__video.board.render_list_possible_moves(self.__video.ventana)
+ self.__video.refresh_window()
+ self.__audio.play_init_turn_sounds(self.__video.board,self.__engine.juego,leer_turno_nro=False,leer_turno=False)
+ self.__audio.wait_sound_end(tiempo=600)
+ if self.__error_desafio:
+ self.__read_next_texts_group(etiqueta_error_desafio="DC_WRONG_ANSWER_BORDER")
+ self.show_dialogue()
+ self.__audio.play_fx_sound("otros","more_text",{'loop':True})
+ self.__keys.disable_keys(self.__accion_entrada["teclas_permitidas_accion"],DIAL)
+ self.__video.text_box.delete_text()
+ else:
+ self.__keys.disable_keys(self.__accion_entrada["teclas_permitidas_accion"],DIAL)
+ self.__accion_entrada.clear()
+ self.__advance_dialogue()
+ else:
+ if not datos_adicionales == SELECCION:
+ self.__video.board.do_move(datos_adicionales, self.__audio)
+ else:
+ self.__do_audio_action("cell_info")
+
+ def __show_error_dialogue(self):
+ texto_final = ""
+ aux_textos = list(self.__textos)
+ while aux_textos != []:
+ texto = aux_textos.pop(0).get_text('str')
+ self.__get_dialogue_from_file(texto)
+ e_texto = self.__textos.pop(0)
+ texto_final += e_texto.get_text('str')
+ texto_final += '\n'
+ self.__audio.play_character_voice(e_texto.get_attribute('character'),e_texto.get_attribute('sound'))
+ self.__video.text_box.show_text(self.__video.ventana,texto_final)
+ self.__save_last_text(texto_final)
+ self.__audio.play_fx_sound("otros","wait_input")
+
+ def __show_challenge_error_dialogue(self):
+ texto_final = ""
+ while self.__textos != []:
+ e_texto = self.__textos.pop(0)
+ texto_final += e_texto.get_text('str')
+ texto_final += '\n'
+ self.__audio.play_character_voice(e_texto.get_attribute('character'),e_texto.get_attribute('sound'))
+ self.__video.text_box.show_text(self.__video.ventana,texto_final)
+ self.__save_last_text(texto_final)
+ self.__audio.play_fx_sound("otros","wait_input")
+
+ def __set_state(self, elemento):
+ if self.__wait_special_input(elemento):
+ if 'input' in elemento.get_attributes():
+ self.__keys.enable_key(self.__accion_entrada["entrada_esperada"])
+ self.__estado_dialogo = ESPERANDO_ACCION
+ self.__audio.play_fx_sound("otros","wait_input")
+ elif 'special_input' in elemento.get_attributes():
+ self.__keys.enable_move_keys()
+ self.__estado_dialogo = ESPERANDO_ACCION_ESPECIAL
+ self.__audio.play_fx_sound("otros","wait_input")
+ else:
+ self.__estado_dialogo = ESPERANDO_CONTINUAR
+ self.__textos_dialogo_error = ""
+
+ def show_dialogue(self):
+ self.__texto_a_mostrar = ""
+ self.__last_sounds = []
+ self.__pre_show_dialogue()
+
+ def __pre_show_dialogue(self):
+ e_texto = self.__textos[0]
+ self.__do_show_dialogue(e_texto)
+ self.__video.text_box.show_text(self.__video.ventana,self.__texto_a_mostrar)
+ if e_texto.has_attribute('after_video_action'):
+ self.__do_video_action(e_texto.get_attribute('after_video_action'))
+ if e_texto.has_attribute('after_audio_action'):
+ self.__do_audio_action(e_texto.get_attribute('after_audio_action'))
+ self.__save_last_text(self.__texto_a_mostrar)
+
+ def __do_show_dialogue(self,e_texto):
+ if e_texto.get_name() == 'text' and e_texto.has_attribute('join'):
+ self.__show_join_dialogue(e_texto)
+ elif e_texto.get_name() == 'exec_ref':
+ self.__show_ref_dialogue(e_texto)
+ elif e_texto.get_name() == 'text':
+ self.__show_normal_dialogue(e_texto)
+ else:
+ raise Exception("Etiqueta desconocida! (Dialog Class)")
+
+ def __do_video_action(self, accion):
+ if accion == "select_class_room":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ hab_actual = self.__usuario.get_current_room().get_left_room()
+ extra = [self.__video.text_box]
+ #func = {'nombre':.is_up,'parametros':""}
+ #extra.append(func)
+ #func = {'nombre':self.__video.text_box.get_final_position,'parametros':""}
+ #extra.append(func)
+ self.__navegacion.select_room(hab_actual,IZQUIERDA)
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.club.pause_door_animation()
+ self.__video.text_box.show(self.__video.ventana)
+ self.__video.club.launch_door_animation(extra)
+ elif accion == "go_to_second_floor":
+ #self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ self.__video.club.end_door_animation()
+ self.__navegacion.go_to_floor()
+ personaje = self.__club.get_character_by_name("pablo gris")
+ self.__video.club.show_character(personaje)
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "select_elevator_up":
+ self.__video.club.end_door_animation()
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ self.__navegacion.select_elevator(ARRIBA)
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.club.pause_door_animation()
+ self.__video.text_box.show(self.__video.ventana)
+ #extra = []
+ #func = {'nombre':self.__video.text_box.refresh_text_box,'parametros':(self.__video.ventana)}
+ #extra.append(func)
+ extra = [self.__video.text_box]
+ self.__video.club.launch_door_animation(extra)
+ elif accion == "class_room_more_info":
+ self.__navegacion.selection_more_info()
+ self.__video.club.pause_door_animation()
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ #extra = []
+ #func = {'nombre':self.__video.text_box.refresh_text_box,'parametros':(self.__video.ventana)}
+ #extra.append(func)
+ extra = [self.__video.text_box]
+ self.__video.club.launch_door_animation()
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.club.pause_door_animation()
+ self.__video.text_box.show(self.__video.ventana)
+ self.__video.club.launch_door_animation(extra)
+ elif accion == "floor_more_info":
+ self.__navegacion.more_info()
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "show_board":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ self.__engine.init_game("tutorial1")
+ self.__video.show_board()
+ #self.__video.show_scores()
+ self.__video.board.set_coord_selected_cell(Coordinate(1,1))
+ thread.start_new_thread(self.__video.board.render_animation_cell,(self.__video.ventana,))
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "init_chal_a1" or accion == "init_chal_a2" or \
+ accion == "init_chal_a3" or accion == "init_chal_a4" or \
+ accion == "init_chal_b1" or accion == "init_chal_a5" or \
+ accion == "init_chal_b2" or accion == "init_chal_b3" or \
+ accion == "init_chal_b4" or accion == "init_chal_b5" or \
+ accion == "init_chal_c1" or accion == "init_chal_c2" or \
+ accion == "init_chal_c3" or accion == "init_chal_c4" or \
+ accion == "init_chal_c5":
+ self.__set_up_challenge(accion)
+ elif accion == "to_left_cell":
+ self.__video.board.do_move(IZQUIERDA, self.__audio)
+ self.__audio.wait_sound_end(tiempo=600)
+ elif accion == "to_up_cell":
+ self.__video.board.do_move(ARRIBA, self.__audio)
+ self.__audio.wait_sound_end(tiempo=600)
+ elif accion == "show_pieces":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ #Mostrar las fichas
+ self.__video.board.get_logical_board().set_up()
+ self.__video.board.render_configuration(self.__video.ventana)
+ self.__video.board.lista_jugadas = Referee.possibles_moves(self.__engine.juego.get_turn().get_color(),self.__video.board.get_logical_board())
+ self.__video.board.render_list_possible_moves(self.__video.ventana)
+ self.__engine.juego.update_possible_moves()
+ self.__video.show_scores()
+ self.__audio.play_voice_sound("game", "inicio")
+ self.__audio.play_voice_sound("board", "tablero4x4")
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "play_4_2":
+ self.__make_a_play((Coordinate(2,4)))
+ elif accion == "pg_show_selection_list":
+ self.__video.create_selection_list()
+ relacion_pg = self.__usuario.get_character_relation("pablo gris")
+ if relacion_pg == TUTORIAL1:
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"1a Clase", "id":"tutorial1","visible":True}])
+ if relacion_pg == TUTORIAL2:
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"1a Clase", "id":"tutorial1","visible":True},{"descripcion":"2a Clase", "id":"tutorial2","visible":True}])
+ else:
+ log.debug("Faltan agregar opciones para otros tipos de relacion, lista Pablo Gris")
+ self.__video.show_selection_list()
+ elif accion == "pm_show_selection_list":
+ relacion_dc = self.__usuario.get_character_relation("don cano")
+ if relacion_dc == CHALLENGE4 or relacion_dc == CHALLENGES_COMPLETED:
+ self.__video.create_selection_list(tipo="sin_jugadas_posibles")
+ self.__video.selection_list.add_options([{"descripcion":"Jugar sin marcar jugadas posibles","id":"jugar_sin_jugadas_posibles","visible":True},{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Jugar", "id":"jugar","visible":True}])
+ else:
+ self.__video.create_selection_list()
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Jugar", "id":"jugar","visible":True}])
+ self.__video.show_selection_list()
+ elif accion == "pt_show_selection_list":
+ self.__video.create_selection_list()
+ relacion_pt = self.__usuario.get_character_relation("protasio")
+ if relacion_pt == WON3:
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Jugar", "id":"jugar","visible":True}])
+ else:
+ log.debug("Faltan agregar opciones para otros tipos de relacion, lista Protasio")
+ self.__video.show_selection_list()
+ elif accion == "sd_show_selection_list":
+ relacion_sd = self.__usuario.get_character_relation("sofia dulce")
+ relacion_dc = self.__usuario.get_character_relation("don cano")
+ if relacion_sd == WON3:
+ if relacion_dc == CHALLENGE4 or relacion_dc == CHALLENGES_COMPLETED:
+ self.__video.create_selection_list(tipo="sin_jugadas_posibles")
+ self.__video.selection_list.add_options([{"descripcion":"Jugar sin marcar jugadas posibles","id":"jugar_sin_jugadas_posibles","visible":True},{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Jugar", "id":"jugar","visible":True}])
+ else:
+ self.__video.create_selection_list()
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True},{"descripcion":"Jugar", "id":"jugar_con_jp","visible":True}])
+ else:
+ log.debug("Faltan agregar opciones para otros tipos de relacion, lista Sofia Dulce")
+ self.__video.show_selection_list()
+ #Lista de seleccion que aparece si es que se responde mal a los desafios, las opciones no llevan id para diferenciar del resto
+ elif accion == "dc_show_selection_list":
+ self.__video.create_selection_list()
+ self.__video.selection_list.add_options([{"descripcion":"Reintentar","id":"reintentar","visible":True},{"descripcion":"Salir al pasillo","id":"salir_pasillo","visible":True}])
+ self.__video.show_selection_list()
+ elif accion == "dc_show_retake_list":
+ self.__video.create_selection_list()
+ relacion_dc = self.__usuario.get_character_relation("don cano")
+ don_cano = self.__engine.get_club().get_character_by_name("don cano")
+ if relacion_dc == CHALLENGE1:
+ self.__video.selection_list.add_options([{"descripcion":"Salir","id":"salir","visible":True}, \
+ {"descripcion":"Tomar desafio A1","id":"retake_chal_a1","visible":True,"medalla":""}, \
+ {"descripcion":"Tomar desafio A2","id":"retake_chal_a2","visible":True,"medalla":""}])
+ elif relacion_dc == CHALLENGE2:
+ self.__video.selection_list.add_options([{"descripcion":"Tomar desafio A4","id":"retake_chal_a4","visible":True,"medalla":""}, \
+ {"descripcion":"Salir","id":"salir","visible":True}, \
+ {"descripcion":"Tomar desafio A1","id":"retake_chal_a1","visible":True,"medalla":""}, \
+ {"descripcion":"Tomar desafio A2","id":"retake_chal_a2","visible":False,"medalla":""}, \
+ {"descripcion":"Tomar desafio A3","id":"retake_chal_a3","visible":False,"medalla":""}])
+ elif relacion_dc == CHALLENGE3:
+ self.__video.selection_list.add_options([{"descripcion":don_cano.get_challenge_title(self.__usuario,"b5"),"id":"retake_chal_b5","visible":True,"medalla":self.__usuario.get_challenge_medal("b5")}, \
+ {"descripcion":"Salir","id":"salir","visible":True}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a1"),"id":"retake_chal_a1","visible":True,"medalla":self.__usuario.get_challenge_medal("a1")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a2"),"id":"retake_chal_a2","visible":False,"medalla":self.__usuario.get_challenge_medal("a2")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a3"),"id":"retake_chal_a3","visible":False,"medalla":self.__usuario.get_challenge_medal("a3")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a4"),"id":"retake_chal_a4","visible":False,"medalla":self.__usuario.get_challenge_medal("a4")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a5"),"id":"retake_chal_a5","visible":False,"medalla":self.__usuario.get_challenge_medal("a5")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b1"),"id":"retake_chal_b1","visible":False,"medalla":self.__usuario.get_challenge_medal("b1")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b2"),"id":"retake_chal_b2","visible":False,"medalla":self.__usuario.get_challenge_medal("b2")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b3"),"id":"retake_chal_b3","visible":False,"medalla":self.__usuario.get_challenge_medal("b3")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b4"),"id":"retake_chal_b4","visible":False,"medalla":self.__usuario.get_challenge_medal("b4")}])
+ elif relacion_dc == CHALLENGE4 or relacion_dc == CHALLENGES_COMPLETED:
+ self.__video.selection_list.add_options([{"descripcion":don_cano.get_challenge_title(self.__usuario,"c5"),"id":"retake_chal_c5","visible":True,"medalla":self.__usuario.get_challenge_medal("c5")}, \
+ {"descripcion":"Salir","id":"salir","visible":True}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a1"),"id":"retake_chal_a1","visible":True,"medalla":self.__usuario.get_challenge_medal("a1")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a2"),"id":"retake_chal_a2","visible":False,"medalla":self.__usuario.get_challenge_medal("a2")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a3"),"id":"retake_chal_a3","visible":False,"medalla":self.__usuario.get_challenge_medal("a3")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a4"),"id":"retake_chal_a4","visible":False,"medalla":self.__usuario.get_challenge_medal("a4")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"a5"),"id":"retake_chal_a5","visible":False,"medalla":self.__usuario.get_challenge_medal("a5")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b1"),"id":"retake_chal_b1","visible":False,"medalla":self.__usuario.get_challenge_medal("b1")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b2"),"id":"retake_chal_b2","visible":False,"medalla":self.__usuario.get_challenge_medal("b2")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b3"),"id":"retake_chal_b3","visible":False,"medalla":self.__usuario.get_challenge_medal("b3")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b4"),"id":"retake_chal_b4","visible":False,"medalla":self.__usuario.get_challenge_medal("b4")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"b5"),"id":"retake_chal_b5","visible":False,"medalla":self.__usuario.get_challenge_medal("b5")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"c1"),"id":"retake_chal_c1","visible":False,"medalla":self.__usuario.get_challenge_medal("c1")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"c2"),"id":"retake_chal_c2","visible":False,"medalla":self.__usuario.get_challenge_medal("c2")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"c3"),"id":"retake_chal_c3","visible":False,"medalla":self.__usuario.get_challenge_medal("c3")}, \
+ {"descripcion":don_cano.get_challenge_title(self.__usuario,"c4"),"id":"retake_chal_c4","visible":False,"medalla":self.__usuario.get_challenge_medal("c4")}])
+ self.__video.show_selection_list()
+ elif accion == "init_tut2":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ self.__engine.init_game("tutorial2")
+ self.__video.init_leason_elements(self.__engine.juego, self.__engine.get_audio())
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "play_3_1":
+ self.__make_a_play(Coordinate(1,3))
+ elif accion == "play_5_4":
+ self.__make_a_play(Coordinate(4,5))
+ elif accion == "dissapear_game_elements":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.dissapear_game_elements()
+ self.__video.text_box.show(self.__video.ventana)
+ elif accion == "show_gold_trophy":
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__engine.get_audio().play_fx_sound("otros","trofeo_oro")
+ self.__video.show_trophy(ORO)
+ pygame.time.wait(800)
+ self.__video.dissapear_trophy(ORO)
+ self.__video.text_box.show(self.__video.ventana)
+ else:
+ raise Exception("Accion desconocida (Dialog Class)")
+
+ def __set_up_challenge(self, nombre_desafio):
+ subnombres = nombre_desafio.split("_")
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.text_box.delete_text()
+ if subnombres[2].find("c") == -1:
+ self.__engine.init_game("desafio_" + subnombres[2])
+ else:
+ self.__engine.init_game("desafio_" + subnombres[2],con_jugadas_posibles=False)
+ self.__video.init_challenge_elements(subnombres[1] + "_" + subnombres[2], self.__engine.juego, self.__engine.get_audio())
+ self.__jugadas_posibles_desafio = Referee.possibles_moves(self.__engine.juego.get_turn().get_color(),self.__engine.juego.get_board())
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.text_box.show(self.__video.ventana)
+
+ def __make_a_play(self, coord_juego):
+ coord = self.__video.board.graphic_coord_to_logic_coord(coord_juego)
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.marcador.refresh(self.__video.ventana)
+ self.__engine.juego.play(coord,self.__audio,self.__video.marcador, self.__video.ventana,{"play_turn_sound":False})
+ self.__video.text_box.show(self.__video.ventana)
+
+ def __do_audio_action(self, accion):
+ if accion == "cell_info":
+ self.__video.board.play_box_info_sound(self.__audio)
+ self.__audio.wait_sound_end(tiempo=600)
+ elif accion == "read_possible_moves":
+ self.__video.board.play_possible_moves_sound(self.__audio)
+ self.__audio.wait_sound_end(tiempo=600)
+ elif accion == "count_pieces":
+ self.__video.board.play_count_pieces_sound(self.__audio,self.__engine.juego)
+ self.__audio.wait_sound_end(tiempo=600)
+ self.__video.dissapear_scores()
+ self.__video.dissapear_board()
+ elif accion == "virus":
+ self.__audio.play_fx_sound("club","infeccion")
+ self.__audio.wait_sound_end(tiempo=600)
+
+ def __show_join_dialogue(self,e_texto):
+ self.__show_normal_dialogue(e_texto)
+ self.__pre_show_dialogue()
+
+ def __show_normal_dialogue(self,e_texto):
+ #Veo si tiene una accion que ejecutar
+ if e_texto.has_attribute('video_action'):
+ self.__do_video_action(e_texto.get_attribute('video_action'))
+ if e_texto.has_attribute('audio_action'):
+ self.__do_audio_action(e_texto.get_attribute('audio_action'))
+ texto = e_texto.get_text('str')
+ self.__texto_a_mostrar += texto + " "
+ #SONIDO DEL DIALOGO
+ last_sound = {}
+ last_sound["character"] = e_texto.get_attribute('character')
+ last_sound["sonido"] = e_texto.get_attribute('sound')
+ self.__audio.play_character_voice(last_sound["character"],last_sound["sonido"])
+ self.__last_sounds.append(last_sound)
+ self.__textos.pop(0)
+ self.__set_state(e_texto)
+
+ def __show_ref_dialogue(self,e_ref):
+ self.__get_dialogue_from_file(e_ref.get_text('str'))
+ self.__pre_show_dialogue()
\ No newline at end of file diff --git a/src/hyperhistory/dialog.pyc b/src/hyperhistory/dialog.pyc Binary files differnew file mode 100644 index 0000000..ee2675b --- /dev/null +++ b/src/hyperhistory/dialog.pyc diff --git a/src/hyperhistory/events.py b/src/hyperhistory/events.py new file mode 100755 index 0000000..540ee9e --- /dev/null +++ b/src/hyperhistory/events.py @@ -0,0 +1,65 @@ +import time, pygame, logging
+
+log = logging.getLogger( 'src.hyperhistory.events' )
+log.setLevel( logging.DEBUG )
+
+class Events:
+ def __init__(self):
+ self.__current_event = ""
+ self.__type_current_event = ""
+ self.__open_event = False
+
+ def run_events(self, engine, eventos):
+ #Iterar sobre los eventos y ejecutarlos
+ for e in eventos:
+ self.__run_event(engine, e)
+
+ def run_event(self, engine, evento):
+ if evento['nombre'] == "bienvenida":
+ self.__current_event = evento['nombre']
+ self.__type_current_event = evento["tipo"]
+ self.__open_event = True
+ pg = engine.get_club().get_character_by_name("pablo gris")
+ pg.wellcome(engine)
+ pg.set_current_event(evento)
+ engine.set_action(metodo=pg.close_event,parametros=(engine))
+ pygame.display.update()
+ #self.__wait_event_end()
+ #pg.close_action(("bienvenida",engine,evento))
+ elif evento['nombre'] == "presentacion":
+ self.__current_event = "presentacion"
+ self.__type_current_event = evento["tipo"]
+ self.__open_event = True
+ sd = engine.get_club().get_character_by_name("sofia dulce")
+ sd.presentation(engine)
+ sd.set_current_event(evento)
+ engine.set_action(metodo=sd.close_event,parametros=(engine))
+ pygame.display.update()
+ elif evento['nombre'] == "end_game":
+ self.__current_event = "end_game"
+ self.__type_current_event = evento["tipo"]
+ self.__open_event = True
+ pt = engine.get_club().get_character_by_name("protasio")
+ pt.fin_juego(engine)
+ pt.set_current_event(evento)
+ engine.set_action(metodo=pt.close_event,parametros=(engine))
+ pygame.display.update()
+ else:
+ log.debug("El evento no esta mapeado a ninguna funcion")
+
+ def __wait_event_end(self):
+ while self.__open_event:
+ time.sleep(1.)
+
+ def close_event(self):
+ self.__open_event = False
+
+ def is_an_open_event(self, tipo=""):
+ if tipo == "":
+ return self.__open_event
+ else:
+ if self.__type_current_event == tipo and self.__open_event:
+ return True
+ else:
+ return False
+
diff --git a/src/hyperhistory/events.pyc b/src/hyperhistory/events.pyc Binary files differnew file mode 100644 index 0000000..31fc9b9 --- /dev/null +++ b/src/hyperhistory/events.pyc diff --git a/src/hyperhistory/gui.py b/src/hyperhistory/gui.py new file mode 100755 index 0000000..45dddd6 --- /dev/null +++ b/src/hyperhistory/gui.py @@ -0,0 +1,314 @@ +import pygame
+from main.constants import ARRIBA, ABAJO, IZQUIERDA, DERECHA, RESOLUTION1, RESOLUTION2
+from resources.images import Images
+import thread
+
+class Gui:
+ def __init__(self, ventana, resolucion):
+ self.ventana = ventana
+ self.__resolucion = resolucion
+ #Creo una superficie donde almacenar la habitacion actual
+ self.__sup_hab_actual = pygame.Surface(self.__resolucion)
+ #Propiedades que utilizo para la animacion de puerta y/o ascensor
+ self.__anim_image1 = ""
+ self.__anim_image2 = ""
+ self.__mostrar_puerta_seleccionada = True
+ self.__ejecutar_animacion = True
+ self.__obj_animation_type = ""
+ self.__navegation = Navegation(self.ventana,resolucion)
+
+ def get_current_room_surface(self):
+ return self.__sup_hab_actual
+
+ def refresh_room(self):
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ #pygame.display.update()
+
+ def __show_logo(self):
+ imagen = Images.get_images_file_names(self.__resolucion, "etc")["logo"]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen['archivo']).convert_alpha(), (120,200))
+
+ def show_room(self, habitacion):
+ self.__render_room(habitacion)
+ if habitacion.get_name() == 'entrada':
+ self.__show_logo()
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ #pygame.display.update()
+
+ def show_character(self, personaje):
+ imagen = Images.get_images_file_names(self.__resolucion, "personajes")[personaje.get_name()]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen['archivo']).convert_alpha(), imagen['pos_xy_f'])
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ #pygame.display.update()
+
+ def __render_room(self, habitacion, extra=""):
+ archivo_imagen = Images.get_images_file_names(self.__resolucion, "habitaciones")[habitacion.get_name()]
+ self.__sup_hab_actual.blit(pygame.image.load(archivo_imagen).convert(), (0,0))
+ #Copio la imagen del personaje si no es piso la nueva habitacion y tiene un personaje asociado
+ if not habitacion.is_floor():
+ personaje = habitacion.get_owner()
+ if personaje != "":
+ imagen = Images.get_images_file_names(self.__resolucion, "personajes")[personaje.get_name()]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen['archivo']).convert_alpha(), imagen['pos_xy'])
+ else:
+ #Colocar las puertas y el ascensor
+ #ASCENSOR
+ imagen_as = Images.get_images_file_names(self.__resolucion, "puertas")["ascensor"]
+ imagen_as_botones = Images.get_images_file_names(self.__resolucion, "etc")["asc_botones"]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_as['archivo']).convert_alpha(), imagen_as['pos_xy'])
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_as_botones['archivo']).convert_alpha(), imagen_as_botones['pos_xy'])
+ #PUERTAS
+ if habitacion.get_left_room() != "":
+ hab_izq = habitacion.get_left_room().get_name()
+ imagen_puerta1 = Images.get_images_file_names(self.__resolucion, "puertas")[hab_izq]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_puerta1['archivo']).convert_alpha(), imagen_puerta1['pos_xy'])
+ if habitacion.get_right_room() != "":
+ hab_der = habitacion.get_right_room().get_name()
+ imagen_puerta2 = Images.get_images_file_names(self.__resolucion, "puertas")[hab_der]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_puerta2['archivo']).convert_alpha(), imagen_puerta2['pos_xy'])
+ if extra == "introduccion":
+ #Muestro a Pablo Gris en el nuevo piso (1er piso)
+ imagen = Images.get_images_file_names(self.__resolucion, "personajes")["pablo gris"]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen['archivo']).convert_alpha(), imagen['pos_xy_f'])
+ elif extra == "presentacion_sofia":
+ #Muestro a Sofia Dulce en la nueva habitacion (2do piso)
+ imagen = Images.get_images_file_names(self.__resolucion, "personajes")["sofia dulce"]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen['archivo']).convert_alpha(), imagen['pos_xy_f'])
+ elif extra == "final_juego":
+ #Muestro a todos los personajes en el pasillo para el final del juego
+ imagen_sofia = Images.get_images_file_names(self.__resolucion, "personajes")["sofia dulce"]
+ imagen_don_cano = Images.get_images_file_names(self.__resolucion, "personajes")["don cano"]
+ imagen_protasio = Images.get_images_file_names(self.__resolucion, "personajes")["protasio"]
+ imagen_pablo_gris = Images.get_images_file_names(self.__resolucion, "personajes")["pablo gris"]
+ imagen_pedro_madera = Images.get_images_file_names(self.__resolucion, "personajes")["pedro madera"]
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_don_cano['archivo']).convert_alpha(), imagen_don_cano['pos_xy_end'])
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_protasio['archivo']).convert_alpha(), imagen_protasio['pos_xy_end'])
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_pablo_gris['archivo']).convert_alpha(), imagen_pablo_gris['pos_xy_end'])
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_pedro_madera['archivo']).convert_alpha(), imagen_pedro_madera['pos_xy_end'])
+ self.__sup_hab_actual.blit(pygame.image.load(imagen_sofia['archivo']).convert_alpha(), imagen_sofia['pos_xy_end'])
+
+ def __animation_thread_running(self):
+ if self.__anim_image1 == "" and self.__anim_image2 == "":
+ return False
+ else:
+ return True
+
+ def launch_door_animation(self,extra=""):
+ try:
+ self.__ejecutar_animacion = True
+ thread.start_new_thread(self.__do_door_animation,(extra,))
+ except Exception, e:
+ print e
+ raise Exception ("Ocurrio un problema en el hilo de animacion de puertas")
+
+ def end_door_animation(self):
+ if self.__ejecutar_animacion:
+ self.__ejecutar_animacion = False
+ pygame.time.wait(100)
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ self.__anim_image1 = ""
+ self.__anim_image2 = ""
+
+ def pause_door_animation(self):
+ self.__ejecutar_animacion = False
+ pygame.time.wait(50)
+
+ def select_animation(self, obj):
+ hay_animacion = self.__animation_thread_running()
+ self.__obj_animation_type = obj['tipo']
+ if self.__obj_animation_type == 'habitacion':
+ nombre_hab = obj['habitacion'].get_name()
+ self.__anim_image1 = Images.get_images_file_names(self.__resolucion, "puertas")[nombre_hab+" sel"]
+ self.__anim_image2 = Images.get_images_file_names(self.__resolucion, "puertas")[nombre_hab]
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ if not hay_animacion:
+ self.launch_door_animation()
+ elif self.__obj_animation_type == 'ascensor':
+ self.__anim_image1 = Images.get_images_file_names(self.__resolucion, "puertas")["ascensor"]
+ self.__anim_image1_1 = Images.get_images_file_names(self.__resolucion, "etc")["asc_botones"]
+ self.__anim_image2_1 = Images.get_images_file_names(self.__resolucion, "etc")["asc_botones_sel"]
+ if obj['direccion'] == ARRIBA:
+ self.__anim_image2 = Images.get_images_file_names(self.__resolucion, "puertas")["asc_subida"]
+ elif obj['direccion'] == ABAJO:
+ self.__anim_image2 = Images.get_images_file_names(self.__resolucion, "puertas")["asc_bajada"]
+ else:
+ print "El ascensor tiene una direccion desconocida"
+ self.ventana.blit(self.__sup_hab_actual, (0,0))
+ if not hay_animacion:
+ self.launch_door_animation()
+ else:
+ raise Exception("Objeto de animacion desconocido! (Class Video)")
+
+ def __run_extra(self, extra):
+ for f in extra:
+ f["nombre"](f["parametros"])
+
+ def __do_door_animation(self, extra=""):
+ while self.__ejecutar_animacion:
+ if self.__mostrar_puerta_seleccionada:
+ self.ventana.blit(pygame.image.load(self.__anim_image1['archivo']).convert_alpha(), self.__anim_image1['pos_xy'])
+ if self.__obj_animation_type == 'ascensor':
+ self.ventana.blit(pygame.image.load(self.__anim_image1_1['archivo']).convert_alpha(), self.__anim_image1_1['pos_xy'])
+ self.__mostrar_puerta_seleccionada = False
+ else:
+ self.ventana.blit(pygame.image.load(self.__anim_image2['archivo']).convert_alpha(), self.__anim_image2['pos_xy'])
+ if self.__obj_animation_type == 'ascensor':
+ self.ventana.blit(pygame.image.load(self.__anim_image2_1['archivo']).convert_alpha(), self.__anim_image2_1['pos_xy'])
+ self.__mostrar_puerta_seleccionada = True
+ if extra != "":
+ text_box = extra[0]
+ up_text_box = text_box.is_up()
+ if up_text_box:
+ text_box.refresh_text_box(self.ventana)
+ #dim_text_box = text_box.get_final_position()
+ #update_rect = pygame.Rect((0, 0), (self.ventana.get_width(), dim_text_box[1]+10))
+ #pygame.display.update(update_rect)
+ #self.__run_extra(extra)
+ pygame.display.update()
+ pygame.time.wait(200)
+
+ def move_to_another_room(self, hab_nueva, direccion, extra=""):
+ s_hab_vieja = self.__sup_hab_actual.copy()
+ self.__render_room(hab_nueva, extra)
+ s_hab_nueva = self.__sup_hab_actual.copy()
+ self.__navegation.move_to_room(s_hab_vieja, s_hab_nueva, direccion)
+
+ def move_to_another_floor(self, piso_nuevo, direccion, extra=""):
+ s_piso_viejo = self.__sup_hab_actual.copy()
+ self.__render_room(piso_nuevo,extra)
+ s_piso_nuevo = self.__sup_hab_actual.copy()
+ self.__navegation.move_to_floor(s_piso_viejo, s_piso_nuevo, direccion)
+
+class Navegation:
+ def __init__(self, ventana="", resolucion=RESOLUTION1):
+ self.__resolucion = resolucion
+ if ventana == "":
+ raise Exception ("Error!, la navegacion del club no se puede instanciar sin una ventana (Navegation Class)")
+ self.__ventana = ventana
+ #Propiedades para la animacion al pasar de piso y habitacion
+ self.__xs = ""
+ self.__ys = ""
+
+ def __init_params_animation_move_room(self):
+ if self.__resolucion == RESOLUTION1:
+ self.__velocidad_anim = 600.
+ self.__xs = {'izquierda' : {'x1' : -900., 'x2' : 0, 'x3' : -100.},
+ 'derecha' : {'x1' : 900., 'x2' : 0, 'x3' : 800.}}
+ self.__x_black_sprite = 100
+ elif self.__resolucion == RESOLUTION2:
+ self.__velocidad_anim = 600.
+ self.__xs = {'izquierda' : {'x1' : -1350., 'x2' : 0, 'x3' : -150.},
+ 'derecha' : {'x1' : 1350., 'x2' : 0, 'x3' : 1200.}}
+ self.__x_black_sprite = 150
+
+ def move_to_room(self, hab_actual, hab_nueva, direccion):
+ if self.__xs == "":
+ self.__init_params_animation_move_room()
+ black_sprite = pygame.Surface((self.__x_black_sprite,self.__resolucion[1]))
+ main_sprite = pygame.Surface((self.__resolucion[0],self.__resolucion[1]))
+ if direccion == IZQUIERDA:
+ self.__move_to_left_room(hab_actual, hab_nueva, black_sprite, main_sprite)
+ elif direccion == DERECHA:
+ self.__move_to_right_room(hab_actual, hab_nueva, black_sprite, main_sprite)
+
+ def __move_to_left_room(self, sprite_hab_vieja, sprite_hab_nueva, sprite_black, main_sprite):
+ x1, x2, x3 = self.__xs['izquierda']['x1'], self.__xs['izquierda']['x2'], self.__xs['izquierda']['x3']
+ reloj = pygame.time.Clock()
+ while x1 <= 0:
+ x1_anterior = x1
+ main_sprite.blit(sprite_hab_nueva, (x1,0))
+ main_sprite.blit(sprite_black, (x3,0))
+ main_sprite.blit(sprite_hab_vieja, (x2,0))
+ tiempo_pasado = reloj.tick(10)
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * self.__velocidad_anim
+ x1 += distancia
+ x2 += distancia
+ x3 += distancia
+ if x1_anterior < 0 and x1 > 0:
+ x1 = 0
+ self.__ventana.blit(main_sprite, (0,0))
+ pygame.display.update()
+
+ def __move_to_right_room(self, sprite_hab_vieja, sprite_hab_nueva, sprite_black, main_sprite):
+ x1, x3, x2 = self.__xs['derecha']['x1'], self.__xs['derecha']['x3'], self.__xs['derecha']['x2']
+ reloj = pygame.time.Clock()
+ while x1 >= 0:
+ x1_anterior = x1
+ main_sprite.blit(sprite_hab_nueva, (x1,0))
+ main_sprite.blit(sprite_black, (x3,0))
+ main_sprite.blit(sprite_hab_vieja, (x2,0))
+ tiempo_pasado = reloj.tick(10)
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * self.__velocidad_anim
+ x1 = x1 - distancia
+ x2 = x2 - distancia
+ x3 = x3 - distancia
+ if x1_anterior > 0 and x1 < 0:
+ x1 = 0
+ self.__ventana.blit(main_sprite, (0,0))
+ pygame.display.update()
+
+ def __init_params_animation_move_floor(self):
+ if self.__resolucion == RESOLUTION1:
+ self.__velocidad_anim = 600.
+ self.__ys = {'arriba' : {'y1' : -700., 'y2' : 0, 'y3' : -100.},
+ 'abajo' : {'y1' : 700., 'y2' : 0, 'y3' : 600.}}
+ self.__y_black_sprite = 100
+ elif self.__resolucion == RESOLUTION2:
+ self.__velocidad_anim = 600.
+ self.__ys = {'arriba' : {'y1' : -1050., 'y2' : 0, 'y3' : -150.},
+ 'abajo' : {'y1' : 1050., 'y2' : 0, 'y3' : 900.}}
+ self.__y_black_sprite = 150
+
+ def move_to_floor(self, piso_actual, piso_nuevo, direccion):
+ if self.__ys == "":
+ self.__init_params_animation_move_floor()
+ black_sprite = pygame.Surface((self.__resolucion[0],150))
+ main_sprite = pygame.Surface((self.__resolucion[0],self.__resolucion[1]))
+ if direccion == ARRIBA:
+ self.__move_to_up_floor(piso_nuevo, piso_actual, black_sprite, main_sprite)
+ else:
+ self.__move_to_down_floor(piso_nuevo, piso_actual, black_sprite, main_sprite)
+
+ def __move_to_up_floor(self, pn_sprite, pv_sprite, b_sprite, m_sprite):
+ y1 = self.__ys['arriba']['y1']
+ y2 = self.__ys['arriba']['y2']
+ y3 = self.__ys['arriba']['y3']
+ reloj = pygame.time.Clock()
+ while y1 <= 0:
+ y1_anterior = y1
+ m_sprite.blit(pn_sprite, (0,y1))
+ m_sprite.blit(b_sprite, (0,y3))
+ m_sprite.blit(pv_sprite, (0,y2))
+ tiempo_pasado = reloj.tick(10)
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * self.__velocidad_anim
+ y1 = y1 + distancia
+ y2 = y2 + distancia
+ y3 = y3 + distancia
+ if y1_anterior < 0 and y1 > 0:
+ y1 = 0
+ self.__ventana.blit(m_sprite, (0,0))
+ pygame.display.update()
+
+ def __move_to_down_floor(self, pn_sprite, pv_sprite, b_sprite, m_sprite):
+ y1 = self.__ys['abajo']['y1']
+ y2 = self.__ys['abajo']['y2']
+ y3 = self.__ys['abajo']['y3']
+ reloj = pygame.time.Clock()
+ while y1 >= 0:
+ y1_anterior = y1
+ m_sprite.blit(pn_sprite, (0,y1))
+ m_sprite.blit(b_sprite, (0,y3))
+ m_sprite.blit(pv_sprite, (0,y2))
+ tiempo_pasado = reloj.tick(10)
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * self.__velocidad_anim
+ y1 = y1 - distancia
+ y2 = y2 - distancia
+ y3 = y3 - distancia
+ if y1_anterior > 0 and y1 < 0:
+ y1 = 0
+ self.__ventana.blit(m_sprite, (0,0))
+ pygame.display.update()
diff --git a/src/hyperhistory/gui.pyc b/src/hyperhistory/gui.pyc Binary files differnew file mode 100644 index 0000000..e1e9719 --- /dev/null +++ b/src/hyperhistory/gui.pyc diff --git a/src/hyperhistory/navigation.py b/src/hyperhistory/navigation.py new file mode 100755 index 0000000..9d579b3 --- /dev/null +++ b/src/hyperhistory/navigation.py @@ -0,0 +1,135 @@ +from main.constants import ARRIBA, ABAJO, DERECHA, IZQUIERDA, ALL_CLEAR
+import os, time, olpcgames
+
+class NavigationManager:
+ def __init__(self, engine="", write_path=""):
+ if engine == "":
+ raise Exception("Error!, navegacion necesita engine para funcionar")
+ self.__audio = engine.get_audio()
+ self.__video = engine.get_video()
+ self.__usuario = engine.get_user()
+ self.__club = engine.get_club()
+ self.__log_file = ""
+ if write_path != "":
+ try:
+ f = open(os.path.abspath(write_path + "/data/navigation.log"),'r')
+ f.close()
+ self.__log_file = open(os.path.abspath(write_path + "/data/navigation.log"),'a')
+ print >> self.__log_file, '\nNAVIGATION LOG: ' + time.asctime()
+ except:
+ self.__log_file = open(os.path.abspath(write_path + "/data/navigation.log"),'w')
+ print >> self.__log_file, 'NAVIGATION LOG: ' + time.asctime()
+
+ def __del__(self):
+ if self.__log_file != "":
+ self.__log_file.close()
+
+ def __print_log(self, mensaje):
+ try:
+ print >> self.__log_file, mensaje
+ except:
+ print mensaje
+
+ def enter_room(self, hab, pos_hab="", animacion_y_sonido=True):
+ self.__usuario.set_current_room(hab)
+ if animacion_y_sonido:
+ self.__video.club.end_door_animation()
+ self.__audio.play_fx_sound("club","puerta")
+ self.__video.club.move_to_another_room(hab,pos_hab)
+ self.__audio.stop_sound()
+ self.__print_log("Entro a " + str(self.__usuario.get_current_room().get_name()))
+ self.__audio.play_voice_sound("club",hab.get_name())
+ #if not hab.is_floor():
+ self.__audio.wait_sound_end(tiempo=500)
+
+ def leave_room(self):
+ nueva_hab = self.__usuario.get_current_room().get_right_room()
+ if nueva_hab != "":
+ self.enter_room(nueva_hab,DERECHA)
+ else:
+ nueva_hab = self.__usuario.get_current_room().get_left_room()
+ self.enter_room(nueva_hab,IZQUIERDA)
+
+ def go_to_floor(self):
+ self.__video.club.end_door_animation()
+ asc_dir = self.__club.get_elevator()["direccion"]
+ if asc_dir == ARRIBA:
+ hab = self.__usuario.get_current_room().get_up_room()
+ name = "ascensor_arriba"
+ elif asc_dir == ABAJO:
+ hab = self.__usuario.get_current_room().get_down_room()
+ name = "ascensor_abajo"
+ else:
+ raise Exception("Error!, el ascensor tiene una direccion desconocida (Class Engine)")
+ if hab.is_available():
+ self.__usuario.set_current_room(hab)
+ self.__audio.play_fx_sound("club",name)
+ self.__video.club.move_to_another_floor(hab,asc_dir)
+ self.__print_log("Fue al " + str(self.__usuario.get_current_room().get_name()))
+ #Si baje al ala entrada salgo del club
+ if hab.equal(self.__club.get_alone_initial_room()):
+ self.exit_club()
+ else:
+ self.__audio.play_voice_sound("club",hab.get_name())
+ self.__club.unselect_elevator()
+ return True
+ else:
+ self.__print_log("Intento acceder a un piso no disponible")
+ self.__club.unselect_elevator()
+ return False
+
+ def select_room(self, hab, hab_pos):
+ self.__club.unselect_elevator()
+ self.__club.select_room(hab,hab_pos)
+ self.__audio.play_voice_sound("club",hab.get_name()+" sel")
+ if not hab.is_floor():
+ obj_ani = {'tipo' : 'habitacion', 'habitacion' : hab}
+ self.__video.club.select_animation(obj_ani)
+ self.__print_log("Selecciono " + str(self.__club.room_selected()["habitacion"].get_name()))
+
+ def select_elevator(self, dir):
+ hab_actual = self.__usuario.get_current_room()
+ if dir == ARRIBA:
+ hab_nueva = self.__usuario.get_current_room().get_up_room()
+ elif dir == ABAJO:
+ hab_nueva = self.__usuario.get_current_room().get_down_room()
+ if hab_actual.is_floor():
+ if hab_nueva != "":
+ self.__club.select_room("","")
+ self.__club.select_elevator(dir)
+ self.__audio.play_voice_sound("club",hab_nueva.get_name() + " sel")
+ obj_ani = {'tipo' : 'ascensor', 'direccion' : dir}
+ self.__video.club.select_animation(obj_ani)
+ self.__print_log("Selecciono el ascensor")
+ else:
+ print "Estoy del cual ya no se puede pasar a otro"
+
+ def more_info(self):
+ self.__audio.play_voice_sound("club",self.__usuario.get_current_room().get_name() + " info")
+
+ def selection_more_info(self):
+ hab_seleccionada = self.__club.room_selected()["habitacion"]
+ if hab_seleccionada != "":
+ self.__audio.play_voice_sound("club",hab_seleccionada.get_name()+" sel")
+ self.__audio.play_voice_sound("club",hab_seleccionada.get_name() + " sel info")
+ elif self.__club.get_elevator()["seleccionado"]:
+ if self.__club.get_elevator()["direccion"] == ARRIBA:
+ self.__audio.play_voice_sound("club",self.__usuario.get_current_room().get_up_room().get_name() + " sel info")
+ else:
+ self.__audio.play_voice_sound("club",self.__usuario.get_current_room().get_down_room().get_name() + " sel info")
+ else:
+ self.__audio.play_voice_sound("club","no habitacion sel")
+
+ def exit_club(self):
+ self.__audio.off_channel()
+ self.__video.club.end_door_animation()
+ self.__usuario.save_user_data()
+ olpcgames.ACTIVITY.close(skip_save=True)
+ exit()
+
+ def exit_mettings_room(self):
+ hab_disponibles = self.__usuario.get_current_room().get_availables_rooms()
+ for pos_hab, nueva_hab in hab_disponibles.items():
+ if nueva_hab.is_floor():
+ break
+ self.enter_room(nueva_hab, pos_hab)
\ No newline at end of file diff --git a/src/hyperhistory/navigation.pyc b/src/hyperhistory/navigation.pyc Binary files differnew file mode 100644 index 0000000..64e60b5 --- /dev/null +++ b/src/hyperhistory/navigation.pyc diff --git a/src/hyperhistory/room.py b/src/hyperhistory/room.py new file mode 100755 index 0000000..d004d4f --- /dev/null +++ b/src/hyperhistory/room.py @@ -0,0 +1,87 @@ +from main.constants import ARRIBA, ABAJO, DERECHA, IZQUIERDA
+
+class Room:
+ def __init__(self, nombre=-1, disponible=False, utilizada=False, duenho="", especial=False, id=""):
+ self.__nombre = nombre
+ self.__duenho = duenho
+ self.__utilizada = utilizada
+ self.__disponible = disponible
+ self.__especial = especial
+ self.__id = id
+ self.__navegacion = {"arriba":"","abajo":"","izquierda":"","derecha":""}
+
+ def used(self,value):
+ self.__utilizada = value
+
+ def is_used(self):
+ return self.__utilizada
+
+ def set_owner(self,duenho):
+ self.__duenho = duenho
+
+ def get_owner(self):
+ return self.__duenho
+
+ def is_available(self):
+ return self.__disponible
+
+ def set_available(self, valor):
+ self.__disponible = valor
+
+ def get_name(self):
+ return self.__nombre
+
+ def get_id(self):
+ return self.__id
+
+ def is_floor(self):
+ return self.__especial
+
+ def set_up_room(self, hab):
+ self.__navegacion["arriba"] = hab
+
+ def set_left_room(self, hab):
+ self.__navegacion["izquierda"] = hab
+
+ def set_right_room(self, hab):
+ self.__navegacion["derecha"] = hab
+
+ def set_down_room(self, hab):
+ self.__navegacion["abajo"] = hab
+
+ def get_up_room(self):
+ return self.__navegacion["arriba"]
+
+ def get_down_room(self):
+ return self.__navegacion["abajo"]
+
+ def get_left_room(self):
+ return self.__navegacion["izquierda"]
+
+ def get_right_room(self):
+ return self.__navegacion["derecha"]
+
+ def get_availables_rooms(self):
+ hab_disponibles = {}
+ hab = self.get_left_room()
+ if hab != "":
+ hab_disponibles[IZQUIERDA] = hab
+ hab = self.get_right_room()
+ if hab != "":
+ hab_disponibles[DERECHA] = hab
+ hab = self.get_up_room()
+ if hab != "":
+ hab_disponibles[ARRIBA] = hab
+ hab = self.get_down_room()
+ if hab != "":
+ hab_disponibles[ABAJO] = hab
+ return hab_disponibles
+
+ def equal(self, other):
+ if self.__id == other.get_id():
+ return True
+ else:
+ return False
+
+ def __str__(self):
+ return "Pieza\nNombre: " + self.__nombre + ", disponible: " + str(self.__disponible)
\ No newline at end of file diff --git a/src/hyperhistory/room.pyc b/src/hyperhistory/room.pyc Binary files differnew file mode 100644 index 0000000..e1eb6e1 --- /dev/null +++ b/src/hyperhistory/room.pyc diff --git a/src/hyperhistory/state.py b/src/hyperhistory/state.py new file mode 100755 index 0000000..66259e2 --- /dev/null +++ b/src/hyperhistory/state.py @@ -0,0 +1,92 @@ +from _xml.parser import Parser
+from main.constants import INITIAL_STATE
+import os
+
+class State:
+ def __init__(self):
+ self.__habitaciones = {}
+ self.__personajes = {}
+ self.__precondiciones = []
+ self.__acciones = []
+ self.__eventos = []
+ self.__teclas = {}
+ self.__nombre = ""
+ self.__nro_max_estados = 17
+
+ def get_max_estados(self):
+ return self.__nro_max_estados
+
+ def get_name(self):
+ return self.__nombre
+
+ def is_initial_state(self):
+ if self.__nombre == INITIAL_STATE:
+ return True
+ else:
+ return False
+
+ def save_state(self, state, main_path):
+ f = open(os.path.abspath(main_path + "/data/hyperhistory.xml"))
+ p = Parser()
+ self.__nombre = state
+ elementos = p.find_child_element(state,f)
+ for e in elementos:
+ if e.get_name() == 'character':
+ if e.get_attribute('enable_play') == 'yes':
+ habilitado_juego = True
+ else:
+ habilitado_juego = False
+ if e.get_attribute('enable_dialogue') == 'yes':
+ habilitado_dialogo = True
+ else:
+ habilitado_dialogo = False
+ personaje = {}
+ personaje['juego'] = habilitado_juego
+ personaje['dialogo'] = habilitado_dialogo
+ self.__personajes[e.get_attribute('id')] = personaje.copy()
+ elif e.get_name() == 'room':
+ if e.get_attribute('enable') == 'yes':
+ habilitada = True
+ else:
+ habilitada = False
+ hab = {}
+ hab['habilitada'] = habilitada
+ self.__habitaciones[e.get_attribute('id')] = hab.copy()
+ elif e.get_name() == 'key':
+ if e.get_attribute('enable') == 'yes':
+ habilitada = True
+ else:
+ habilitada = False
+ hab = {}
+ hab['habilitada'] = habilitada
+ self.__teclas[e.get_attribute('id')] = hab.copy()
+ elif e.get_name() == 'precondition':
+ self.__precondiciones.append(e.get_attribute('name'))
+ elif e.get_name() == 'action':
+ accion = {}
+ accion['nombre'] = e.get_attribute('name')
+ accion['consecuencia'] = e.get_attribute('consequences')
+ accion['nuevo_estado'] = e.get_attribute('new_state')
+ self.__acciones.append(accion.copy())
+ elif e.get_name() == 'event':
+ event = {}
+ event['nombre'] = e.get_attribute('name')
+ event['tipo'] = e.get_attribute('type')
+ event['consecuencia'] = e.get_attribute('consequences')
+ event['nuevo_estado'] = e.get_attribute('new_state')
+ self.__eventos.append(event.copy())
+
+ def get_rooms_state(self):
+ return self.__habitaciones
+
+ def get_characters_state(self):
+ return self.__personajes
+
+ def get_keys_state(self):
+ return self.__teclas
+
+ def get_state_events(self):
+ return self.__eventos
+
+ def get_state_actions(self):
+ return self.__acciones
diff --git a/src/hyperhistory/state.pyc b/src/hyperhistory/state.pyc Binary files differnew file mode 100644 index 0000000..235a759 --- /dev/null +++ b/src/hyperhistory/state.pyc diff --git a/src/input_output/__init__.py b/src/input_output/__init__.py new file mode 100755 index 0000000..d30f87b --- /dev/null +++ b/src/input_output/__init__.py @@ -0,0 +1,16 @@ +#from video import Video
+#from audio import Channel
+#from input_output.keyboard import Keyboard
+#import pygame
+#from pygame.locals import KEYDOWN
+#
+#if __name__ == "__main__":
+# video = Video()
+# canal = Channel()
+# teclado = Keyboard()
+# while True:
+# for event in pygame.event.get():
+# if event.type == KEYDOWN:
+# teclado.key_pressed(event.key)
+# elif event.type == canal.SILENCE_CHANNEL:
+# pass
\ No newline at end of file diff --git a/src/input_output/__init__.pyc b/src/input_output/__init__.pyc Binary files differnew file mode 100644 index 0000000..3762f41 --- /dev/null +++ b/src/input_output/__init__.pyc diff --git a/src/input_output/audio.py b/src/input_output/audio.py new file mode 100755 index 0000000..19d2a3d --- /dev/null +++ b/src/input_output/audio.py @@ -0,0 +1,297 @@ +from pygame import mixer, time
+from pygame.locals import USEREVENT
+from main.constants import IZQUIERDA, DERECHA, ARRIBA, ABAJO, MAS_INFO, SELECCION, CONTAR_FICHAS, \
+ ATRAS
+from othello.player import HUMANO, PC, VIRTUAL
+from othello.board import BLANCO
+from resources.sounds import Sounds
+from othello.utils import get_number_word
+import thread, sys, pygame, logging
+
+log = logging.getLogger( 'AUDIO' )
+log.setLevel( logging.DEBUG )
+
+class Channel():
+ def __init__(self):
+ try:
+ #Inicilializo el modulo para ejecutar sonidos
+ if sys.platform.find('win') != -1:
+ mixer.pre_init(44100,16,1,4096)
+ else:
+ mixer.pre_init(44100)
+ mixer.init()
+ self.__canal = mixer.find_channel()
+ self.__cola = []
+ self.__ejecutando_sonidos = False
+ self.__end_sound_event = False
+ self.__new_sound_event = False
+ self.__escuchar = True
+ self.__sonido_actual = ""
+ self.SILENCE_CHANNEL = USEREVENT + 4
+ self.nombre_grupo_sonido = ""
+ except pygame.error, e:
+ raise Exception("ERROR!: " + str(e) + ", al inicilizar el video. La aplicacion se cerrara")
+
+ def new_event(self, event):
+ if event.type == self.SILENCE_CHANNEL:
+ if self.silence():
+ pass
+ else:
+ event.post(event.Event(self.SILENCE_CHANNEL))
+
+ def get_end_sound_event(self):
+ return self.__end_sound_event
+
+ def get_new_sound_event(self):
+ return self.__new_sound_event
+
+ def queue(self,sonido):
+ self.__cola.append(sonido)
+
+ def get_queue(self):
+ return self.__cola
+
+ def play(self, obj_sonido):
+ sonido = mixer.Sound(obj_sonido["path_archivo"])
+ if obj_sonido["nombre"] != "":
+ self.__sonido_actual = obj_sonido["nombre"]
+ if obj_sonido["caracteristicas"] != "":
+ if "loop" in obj_sonido["caracteristicas"]:
+ self.__canal.play(sonido,-1)
+ elif "volumen" in obj_sonido["caracteristicas"]:
+ derecha = obj_sonido["caracteristicas"]["volumen"]["derecha"]
+ izquierda = obj_sonido["caracteristicas"]["volumen"]["izquierda"]
+ self.__canal.set_volume(izquierda,derecha)
+ self.__canal.play(sonido)
+ elif "grupo_sonido" in obj_sonido["caracteristicas"]:
+ self.nombre_grupo_sonido = obj_sonido["caracteristicas"]["grupo_sonido"]
+ self.__canal.play(sonido)
+ if self.__sonido_actual == "wait_input":
+ self.nombre_grupo_sonido = ""
+ else:
+ log.warn("Faltan acciones para las demas caracteristicas")
+ else:
+ self.__canal.play(sonido)
+ while self.__canal.get_busy():
+ time.wait(100)
+ self.__end_sound_event = True
+
+ def empty_queue(self):
+ if len(self.__cola) > 0:
+ return False
+ else:
+ return True
+
+ def play_next_sound(self):
+ if not self.empty_queue():
+ sonido = self.__cola.pop(0)
+ self.play(sonido)
+ self.__ejecutando_sonidos = True
+ return True
+ else:
+ self.__ejecutando_sonidos = False
+ return False
+
+ def play_new_sound(self):
+ if self.__ejecutando_sonidos:
+ return False
+ else:
+ self.play_next_sound()
+ return True
+
+ def start(self):
+ self.__escuchar = True
+
+ def stop(self):
+ self.__canal.stop()
+ self.__cola = []
+
+ def end(self):
+ self.__escuchar = False
+
+ def send_new_sound_event(self):
+ self.__new_sound_event = True
+
+ def silence(self):
+ if self.__canal.get_busy() == 1:
+ return False
+ else:
+ if self.empty_queue():
+ return True
+ else:
+ return False
+
+ def play_sounds_queue(self):
+ while not self.empty_queue():
+ sonido = self.__cola.pop(0)
+ self.play(sonido)
+
+ def listen(self):
+ while self.__escuchar:
+ if self.__end_sound_event:
+ self.__end_sound_event = False
+ self.play_next_sound()
+ if self.__new_sound_event:
+ self.__new_sound_event = False
+ self.play_new_sound()
+
+ def get_current_sound_name(self):
+ return self.__sonido_actual
+
+class Audio():
+ def __init__(self, main_path=""):
+ self.__canal = Channel()
+ self.__sounds_files = Sounds(main_path)
+
+ def on_channel(self):
+ try:
+ self.__canal.start()
+ thread.start_new_thread(self.__canal.listen,())
+ except:
+ raise Exception ("Ocurrio un problema en el hilo del canal de Audio")
+
+ def off_channel(self):
+ self.__canal.end()
+ time.wait(200)
+
+ def stop_sound(self):
+ self.__canal.stop()
+
+ def pause_channel(self):
+ self.__canal.play_sounds_queue()
+ self.__canal.end()
+
+ def restart_channel(self):
+ self.on_channel()
+ if not self.__canal.empty_queue():
+ self.__canal.send_new_sound_event()
+
+ def silence_channel(self):
+ return self.__canal.silence()
+
+ def get_sound_name(self):
+ return self.__canal.get_current_sound_name()
+
+ def get_sound_group_name(self):
+ return self.__canal.nombre_grupo_sonido
+
+ def wait_sound_end(self, tiempo=""):
+ if tiempo == "":
+ tiempo = 150
+ while not self.__canal.silence():
+ time.wait(tiempo)
+
+ def play_sound(self, sonido, nombre_sonido="", extra=""):
+ obj_sonido = {"path_archivo":sonido,"nombre":nombre_sonido,"caracteristicas":extra}
+ self.__canal.queue(obj_sonido)
+ self.__canal.send_new_sound_event()
+
+ def play_key_sound(self, key):
+ self.__canal.stop()
+ self.play_fx_sound("otros", "select")
+ if key == IZQUIERDA:
+ self.play_voice_sound("otros", "izquierda")
+ elif key == DERECHA:
+ self.play_voice_sound("otros", "derecha")
+ elif key == ARRIBA:
+ self.play_voice_sound("otros", "arriba")
+ elif key == ABAJO:
+ self.play_voice_sound("otros", "abajo")
+ elif key == MAS_INFO:
+ self.play_voice_sound("otros", "mas_info")
+ elif key == SELECCION:
+ self.play_voice_sound("otros", "seleccion")
+ elif key == CONTAR_FICHAS:
+ self.play_voice_sound("otros", "contar_fichas")
+ elif key == ATRAS:
+ self.play_voice_sound("otros", "atras")
+ self.play_fx_sound("otros", "atras")
+ else:
+ pass
+
+ def play_disabled_key_sound(self):
+ canal_aux = mixer.find_channel()
+ #self.__canal.stop()
+ sonido = mixer.Sound(self.__sounds_files.get_sound_file_name("otros","fx","disabled_key"))
+ canal_aux.play(sonido)
+
+ def play_fx_sound(self, nombre, clave, extra=""):
+ try:
+ sonido = self.__sounds_files.get_sound_file_name(nombre,"fx",clave)
+ except:
+ raise Exception("Error!, no se encontro el sonido " + str(sonido))
+ self.play_sound(sonido,nombre_sonido=clave,extra=extra)
+
+ def play_voice_sound(self, nombre, clave, extra=""):
+ try:
+ sonido = self.__sounds_files.get_sound_file_name(nombre,"voz",clave)
+ except:
+ raise Exception("Error!, no se encontro el archivo de sonido")
+ self.play_sound(sonido,nombre_sonido=clave,extra=extra)
+
+ def play_character_voice(self, nombre_personaje, clave):
+ try:
+ sonido = self.__sounds_files.get_sound_file_name("personaje",nombre_personaje,clave)
+ except:
+ raise Exception("Error!, no se encontro el archivo de sonido")
+ self.play_sound(sonido,nombre_sonido=clave)
+
+ def play_init_turn_sounds(self, tablero_g, juego, leer_turno_nro=True, leer_configuracion=True, leer_turno=True):
+ hay_jugadas_posibles = False
+ if leer_turno_nro:
+ self.play_voice_sound("game", "turno_numero", {'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("numero",get_number_word(juego.get_turn_number(),turno=True),{'grupo_sonido':'inicio_turno'})
+ if leer_configuracion:
+ hay_jugadas_posibles = tablero_g.play_count_pieces_sound(self,juego)
+ if hay_jugadas_posibles and leer_turno:
+ jugador_de_turno = juego.get_turn()
+ if jugador_de_turno.get_name() == HUMANO:
+ if jugador_de_turno.get_color() == BLANCO:
+ self.play_voice_sound("game", "jugador_blanco",{'grupo_sonido':'inicio_turno'})
+ else:
+ self.play_voice_sound("game", "jugador_negro",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "es_su_turno",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "seleccione_jugada",{'grupo_sonido':'inicio_turno'})
+ elif jugador_de_turno.get_name() == PC:
+ if jugador_de_turno.get_color() == BLANCO:
+ self.play_voice_sound("game", "jugador_negro",{'grupo_sonido':'inicio_turno'})
+ else:
+ self.play_voice_sound("game", "jugador_blanco",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "no_es_su_turno",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "examine_tablero",{'grupo_sonido':'inicio_turno'})
+ elif jugador_de_turno.get_name() == VIRTUAL:
+ if jugador_de_turno.get_color() == BLANCO:
+ self.play_voice_sound("game", "jugador_negro",{'grupo_sonido':'inicio_turno'})
+ else:
+ self.play_voice_sound("game", "jugador_blanco",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "no_es_su_turno",{'grupo_sonido':'inicio_turno'})
+ self.play_voice_sound("game", "espere jugada oponente",{'grupo_sonido':'inicio_turno'})
+ if not jugador_de_turno.get_name() == VIRTUAL:
+ self.play_fx_sound("otros","wait_input",{'grupo_sonido':'inicio_turno'})
+
+ def play_board_configuration(self, tablero_g, juego):
+ tablero_g.play_count_pieces_sound(self,juego)
+
+ def play_end_game_sounds(self, tablero_g, juego):
+ self.play_voice_sound("game", "fin_partida")
+ tablero_g.play_count_pieces_sound(self,juego)
+ ganador = juego.get_final_result()
+ if ganador != '':
+ self.play_voice_sound("game", "el_jugador")
+ if ganador.get_color() == BLANCO:
+ self.play_voice_sound("game", "blanco")
+ else:
+ self.play_voice_sound("game", "negro")
+ self.play_voice_sound("game", "gana_la_partida")
+ else:
+ self.play_voice_sound("game", "es_un_empate")
+ self.play_fx_sound("otros","wait_input")
+ self.wait_sound_end()
+
+ def play_board_size_sound(self, dim_tablero):
+ if dim_tablero == 4:
+ self.play_voice_sound("board", "tablero4x4")
+ elif dim_tablero == 6:
+ self.play_voice_sound("board", "tablero6x6")
+ elif dim_tablero == 8:
+ self.play_voice_sound("board", "tablero8x8")
\ No newline at end of file diff --git a/src/input_output/audio.pyc b/src/input_output/audio.pyc Binary files differnew file mode 100644 index 0000000..ae45627 --- /dev/null +++ b/src/input_output/audio.pyc diff --git a/src/input_output/io_object.py b/src/input_output/io_object.py new file mode 100755 index 0000000..07792d9 --- /dev/null +++ b/src/input_output/io_object.py @@ -0,0 +1,16 @@ +class IOObject:
+ def __init__(self, engine=""):
+ self.__id = 0
+ self.engine = engine
+
+ def set_id(self, id):
+ self.__id = id
+
+ def get_id(self):
+ return self.__id
+
+ def new_event(self, event):
+ pass
+
+ def set_engine(self, engine):
+ self.engine = engine
\ No newline at end of file diff --git a/src/input_output/io_object.pyc b/src/input_output/io_object.pyc Binary files differnew file mode 100644 index 0000000..4e0b430 --- /dev/null +++ b/src/input_output/io_object.pyc diff --git a/src/input_output/keyboard.py b/src/input_output/keyboard.py new file mode 100755 index 0000000..f5f858a --- /dev/null +++ b/src/input_output/keyboard.py @@ -0,0 +1,85 @@ +from io_object import IOObject
+from pygame.locals import KEYDOWN,K_KP4,K_KP6,K_KP8,K_KP2,K_KP9,K_KP3,K_ESCAPE,K_KP1,K_KP7,K_NUMLOCK,K_g,K_p,K_e,K_t
+from pygame import key
+from main.constants import IZQUIERDA,DERECHA,ARRIBA,ABAJO,CONTINUAR,SALIR,MAS_INFO,TECLA_DESCONOCIDA, \
+ SELECCION,ATRAS,CONTAR_FICHAS,ATAJO_PERDER_JUEGO,ATAJO_EMPATAR_JUEGO,ATAJO_GANAR_JUEGO, \
+ ATAJO_PASAR_TUTORIAL
+import logging
+
+log = logging.getLogger( 'INPUT' )
+log.setLevel( logging.DEBUG )
+
+class Keyboard(IOObject):
+ def __init__(self, engine=""):
+ self.__teclas_permitidas = [K_KP4,K_KP6,K_KP8,K_KP2,K_KP9,K_KP3,K_ESCAPE,K_KP1,K_KP7,K_g,K_e,K_p,K_t]
+ if engine == "":
+ raise Exception("Engine no inicilizado")
+ else:
+ IOObject.__init__(self,engine)
+
+ def new_event(self, event):
+ if event.type == KEYDOWN:
+ teclas_presionadas = self.__get_pressed_key()
+ if not teclas_presionadas == []:
+ self.__pressed_key(teclas_presionadas)
+ #else:
+ # print "No se encuentra la tecla presionada (Class Keyboard)"
+
+ #Para conocer que tecla o telcas se presionaron, debido a que puede ser una tecla individual o
+ #una combinacion de dos teclas
+ def __get_pressed_key(self):
+ teclas_presionadas = []
+ pressed_keys = key.get_pressed()
+ for key_constant, pressed in enumerate(pressed_keys):
+ if pressed:
+ if self.__teclas_permitidas.count(key_constant) == 1:
+ teclas_presionadas.append(key_constant)
+ return teclas_presionadas
+
+ def __pressed_key(self,teclas):
+ can_teclas_presionadas = len(teclas)
+ if can_teclas_presionadas == 1:
+ self.__single_key(teclas[0])
+ elif can_teclas_presionadas == 2:
+ self.__keys_combined(teclas)
+
+ def __keys_combined(self, teclas):
+ tecla_1, tecla_2 = teclas[0], teclas[1]
+ if (tecla_1 == K_KP3 or tecla_1 == K_KP1) and (tecla_2 == K_KP3 or tecla_2 == K_KP1):
+ self.engine.arrive_input(CONTAR_FICHAS)
+
+ def __single_key(self, tecla):
+ if tecla == K_KP4:
+ #print "Se presiono la tecla izquierda con costante" + str(tecla)
+ self.engine.arrive_input(IZQUIERDA)
+ elif tecla == K_KP6:
+ #print "Se presiono la tecla derecha"
+ self.engine.arrive_input(DERECHA)
+ elif tecla == K_KP8:
+ #print "Se presiono la tecla arriba"
+ self.engine.arrive_input(ARRIBA)
+ elif tecla == K_KP2:
+ #print "Se presiono la tecla abajo"
+ self.engine.arrive_input(ABAJO)
+ elif tecla == K_KP9:
+ #print "Se presiono la tecla continuar"
+ self.engine.arrive_input(CONTINUAR)
+ elif tecla == K_KP3:
+ self.engine.arrive_input(MAS_INFO)
+ elif tecla == K_KP1:
+ self.engine.arrive_input(SELECCION)
+ elif tecla == K_KP7:
+ self.engine.arrive_input(ATRAS)
+ elif tecla == K_ESCAPE:
+ self.engine.arrive_input(SALIR)
+ elif tecla == K_p:
+ self.engine.arrive_input(ATAJO_PERDER_JUEGO)
+ elif tecla == K_e:
+ self.engine.arrive_input(ATAJO_EMPATAR_JUEGO)
+ elif tecla == K_g:
+ self.engine.arrive_input(ATAJO_GANAR_JUEGO)
+ elif tecla == K_t:
+ self.engine.arrive_input(ATAJO_PASAR_TUTORIAL)
+ else:
+ self.engine.arrive_input(TECLA_DESCONOCIDA)
+ log.warning("Se presiono un tecla sin funcion")
\ No newline at end of file diff --git a/src/input_output/keyboard.pyc b/src/input_output/keyboard.pyc Binary files differnew file mode 100644 index 0000000..70b86c9 --- /dev/null +++ b/src/input_output/keyboard.pyc diff --git a/src/input_output/mesh.py b/src/input_output/mesh.py new file mode 100755 index 0000000..383aa90 --- /dev/null +++ b/src/input_output/mesh.py @@ -0,0 +1,317 @@ +from io_object import IOObject +import olpcgames, logging, pickle, os +from olpcgames import mesh +from othello.utils import Coordinate +from main.constants import ESPERANDO_OPONENTE, JUGANDO, ON, OFF, PLAY, LIST +import pygame.event as PEvent +from pyfestival import Festival + +log = logging.getLogger( 'MESH' ) +log.setLevel( logging.DEBUG ) + + +class Mesh(IOObject): + def __init__(self, write_path="", audio="", video=""): + if write_path == "": + raise Exception("Error!, mesh necesita el path al directorio de escritura de la aplicacion para funcionar (Class Mesh)") + if audio == "": + raise Exception("Error!, mesh necesita Audio para funcionar (Class Mesh)") + if video == "": + raise Exception("Error!, mesh necesita Video para funcionar (Class Mesh)") + self.__write_path = write_path + self.__audio = audio + self.__video = video + self._buddies = {} + self.__contrarios = [] + self.__can_contrarios = 0 + self.__conf_men_juego = 0 + self.__estado = OFF + self.__hay_oponente_esperando = False + self.__festival = Festival() + self.__tube_id = 0 + self.__oponente = "" + self.__estados_activos = [ON, ESPERANDO_OPONENTE, JUGANDO] + + def set_engine(self, engine): + self.__engine = engine + + 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 __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 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_waiting_message(self): + for participante in mesh.get_participants(): + if mesh.my_handle() != participante: + mesh.send_to(participante, "ESPERANDO_JUEGO_NUEVO") + + def add_buddy( self, handle, buddy ): + """Add a new buddy to internal structures + + Note: this is called in the GObject thread! + """ + try: + current = self._buddies.get( handle ) + if current is False: + self.remove_buddy( handle ) + return + self._buddies[ handle ] = buddy + except Exception, err: + log.error( """Failure setting up buddy %s: %s""", buddy, get_traceback( err ) ) + + def remove_buddy( self,handle ): + """Remove this buddy from all internal structures""" + current = self._buddies.get( handle ) + log.info("Removing %s", current.props.nick) + try: + del self._buddies[ handle ] + except KeyError, err: + pass + return current + + 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 set_state(self, valor): + self.__estado = valor + + 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 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 remove_all(self): + #log.info( 'Antes de obtener el dbus_handle...') + #dbus_handle = mesh.instance().tube.participants[self.__get_oponent_handle()] + #log.info( 'Tengo el dbus_handle...') + #mesh.instance().ordered_bus_names.remove(mesh.my_handle()) + #log.info( 'Hice el remove...') + #PEvent.post(PEvent.Event(mesh.PARTICIPANT_REMOVE, handle=mesh.my_handle())) + #log.info( 'Envie el evento PARTICIPANT_REMOVE...') + mesh.instance().tube.close() + #log.debug("Return type _getConn: " + str(type(mesh._getConn()))) + + def __serialize_game_conf(self): + conf_partida = {"jugadores":self.__engine.juego.get_players(),"tablero":self.__engine.juego.get_board_configuration()} + f = open(os.path.abspath(self.__write_path + '/tmp/tmp.dat'),'w') + pickle.dump(conf_partida, f) + f.close() + f = open(os.path.abspath(self.__write_path + '/tmp/tmp.dat')) + str_conf = f.read() + f.close() + return str_conf + + def __unserialize_game_conf(self, str): + f = open(os.path.abspath(self.__write_path + '/tmp/tmp.dat'),'w') + f.write(str) + f.close() + f = open(os.path.abspath(self.__write_path + '/tmp/tmp.dat')) + conf = pickle.load(f) + f.close() + return conf + + def __get_oponent_handle(self): + for handle in self._buddies.keys(): + if mesh.my_handle() != handle: + return handle + + 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() + + ### + #Metodos que utilizo para que funcione el join programatico a una actividad compartida + ### + def __privacy_changed_cb(self, shared_activity, param_spec): + if shared_activity.props.private: + olpcgames.ACTIVITY._jobject.metadata['share-scope'] = "invite" + else: + olpcgames.ACTIVITY._jobject.metadata['share-scope'] = "public" + + def joined_cb(self, activity, success, err): + """Callback when join has finished""" + olpcgames.ACTIVITY.shared_activity.disconnect(olpcgames.ACTIVITY._join_id) + olpcgames.ACTIVITY._join_id = None + if not success: + logging.debug("Failed to join activity: %s" % err) + return + + olpcgames.ACTIVITY.present() + olpcgames.ACTIVITY.emit('joined') + self.__privacy_changed_cb(olpcgames.ACTIVITY.shared_activity, None) diff --git a/src/input_output/mesh.pyc b/src/input_output/mesh.pyc Binary files differnew file mode 100644 index 0000000..de5ca04 --- /dev/null +++ b/src/input_output/mesh.pyc diff --git a/src/input_output/video.py b/src/input_output/video.py new file mode 100755 index 0000000..e7d0a3b --- /dev/null +++ b/src/input_output/video.py @@ -0,0 +1,850 @@ +# -*- coding: utf-8 -*-
+import pygame
+from pygame.locals import SRCALPHA
+from main.constants import RESOLUTION1, RESOLUTION2, ARRIBA, ABAJO, BRONZE, PLATA, ORO, MARFIL, MADERA
+from hyperhistory.gui import Gui
+from resources.images import Images
+from resources.fonts import Fonts
+from othello.gui import GraphicBoard, Score
+from othello.board import BLANCO
+from othello.utils import Coordinate, get_number_word
+from othello.referee import Referee
+from othello.player import HUMANO
+import thread, string, logging, pyfestival
+
+log = logging.getLogger( 'src.input_output.video' )
+log.setLevel( logging.DEBUG )
+
+
+class Video():
+ def __init__(self, engine="", titulo_ventana="Club de Othello"):
+ try:
+ pygame.init()
+ #Averiguo la resolucion necesario para crear la ventana
+ self.__resolucion = self.__get_initial_resolution()
+ #Creo la ventana
+ self.ventana = pygame.display.set_mode(self.__resolucion, 0, 32)
+ #Coloco el titulo a la ventana
+ pygame.display.set_caption(titulo_ventana)
+ pygame.mouse.set_visible(False)
+ self.club = Gui(self.ventana,self.__resolucion)
+ self.board = ""
+ self.text_box = TextBox(self.__resolucion)
+ self.__init_animation_values()
+ self.marcador = Score(self.__resolucion)
+ self.__tablero_arriba = False
+ self.__marcador_visible = False
+ except pygame.error, e:
+ raise Exception("ERROR! al inicilizar el video. La aplicacion se cerrara\n"+str(e))
+
+ def __get_initial_resolution(self):
+ maxima_resolucion = pygame.display.list_modes()[0]
+ if maxima_resolucion[0] >= RESOLUTION2[0] and maxima_resolucion[1] >= RESOLUTION2[1]:
+ return RESOLUTION2
+ else:
+ return RESOLUTION1
+
+ def get_resolution(self):
+ return self.__resolucion
+
+ def set_window_background(self, imagen):
+ self.__window_background.blit(imagen,(0,0))
+
+ def refresh_window(self, area=""):
+ if area == "":
+ pygame.display.update()
+ else:
+ pygame.display.update(area)
+
+ def __init_animation_values(self):
+ if self.__resolucion == RESOLUTION1:
+ self.__vel_anim_tablero = 600.
+ self.__vel_anim_score = 500.
+ self.__vel_anim_medals = 500.
+ elif self.__resolucion == RESOLUTION2:
+ self.__vel_anim_tablero = 800.
+ self.__vel_anim_score = 700.
+ self.__vel_anim_medals = 1000.
+ else:
+ raise Exception("Error!, resolucion desconocida (Video Class)")
+
+ def __do_set_up_game_elements(self, juego):
+ self.board.render_configuration(self.ventana)
+ if juego.with_possibles_moves():
+ self.board.lista_jugadas = Referee.possibles_moves(juego.get_turn().get_color(),self.board.get_logical_board())
+ self.board.render_list_possible_moves(self.ventana)
+ self.show_board(con_configuracion=True)
+ self.show_scores(juego.get_turn().get_color())
+ self.board.set_coord_selected_cell(Coordinate(1,1))
+ if self.board.animation_cell_running():
+ self.board.end_animation_cell()
+ thread.start_new_thread(self.board.render_animation_cell,(self.ventana,))
+
+ def init_game_elements(self, juego, audio):
+ self.__do_set_up_game_elements(juego)
+ audio.play_voice_sound("game", "inicio", {'grupo_sonido':'inicio_turno'})
+ dim_tablero = self.board.get_logical_board().get_dimension()
+ audio.play_board_size_sound(dim_tablero)
+ audio.play_init_turn_sounds(self.board,juego)
+
+ def init_leason_elements(self, juego, audio):
+ self.__do_set_up_game_elements(juego)
+ audio.play_voice_sound("game", "inicio_leccion", {'grupo_sonido':'inicio_turno'})
+ dim_tablero = self.board.get_logical_board().get_dimension()
+ audio.play_board_size_sound(dim_tablero)
+
+ def init_challenge_elements(self, nombre_desafio, juego, audio):
+ self.__do_set_up_game_elements(juego)
+ audio.play_voice_sound("game", "exp_"+str(nombre_desafio), {'grupo_sonido':'inicio_turno'})
+ audio.play_voice_sound("game", "inicio_desafio", {'grupo_sonido':'inicio_turno'})
+ dim_tablero = self.board.get_logical_board().get_dimension()
+ audio.play_board_size_sound(dim_tablero)
+
+ def create_graphic_board(self, logical_board=""):
+ try:
+ self.board.end_animation_cell()
+ self.board = GraphicBoard(tablero_logico=logical_board,resolucion=self.__resolucion)
+ self.text_box.set_up_graphic_board(self.board)
+ except:
+ self.board = GraphicBoard(tablero_logico=logical_board,resolucion=self.__resolucion)
+ self.text_box.set_up_graphic_board(self.board)
+
+ def create_selection_list(self, titulo="", tipo=""):
+ self.selection_list = SelectionList(self.__resolucion, self.ventana, titulo, tipo)
+
+ def show_selection_list(self):
+ self.selection_list.draw()
+ list_sup = self.selection_list.render_options()
+ self.ventana.blit(list_sup,self.selection_list.get_screen_position())
+ if not self.board == "":
+ self.board.set_up_image({'imagen':list_sup, 'posicion':self.selection_list.get_screen_position()})
+ pygame.display.update()
+
+ def remove_selection_list(self):
+ self.selection_list.remove()
+ if not self.board == "":
+ self.board.remove_up_images()
+
+ def show_medal(self, medalla):
+ na_imagenes_medallas = Images.get_images_file_names(self.__resolucion, "medallas")
+ if medalla == ORO:
+ imagen_medalla = pygame.image.load(na_imagenes_medallas["oro"]["archivo"]).convert_alpha()
+ pos_final_medalla = na_imagenes_medallas["oro"]["pos_xy"]
+ elif medalla == PLATA:
+ imagen_medalla= pygame.image.load(na_imagenes_medallas["plata"]["archivo"]).convert_alpha()
+ pos_final_medalla = na_imagenes_medallas["plata"]["pos_xy"]
+ elif medalla == BRONZE:
+ imagen_medalla= pygame.image.load(na_imagenes_medallas["bronze"]["archivo"]).convert_alpha()
+ pos_final_medalla = na_imagenes_medallas["bronze"]["pos_xy"]
+ update_rect = pygame.Rect((pos_final_medalla[0], 0), (imagen_medalla.get_width(), pos_final_medalla[1]+imagen_medalla.get_height()))
+ velocidad = self.__vel_anim_medals
+ reloj = pygame.time.Clock()
+ y_max = pos_final_medalla[1]
+ y = -imagen_medalla.get_height()
+ while y < y_max:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y = y + distancia #distancia
+ if y_anterior < y_max and y > y_max:
+ y = y_max
+ self.ventana.blit(self.club.get_current_room_surface(), update_rect, update_rect)
+ self.ventana.blit(imagen_medalla, (pos_final_medalla[0], y))
+ pygame.display.update(update_rect)
+
+ def dissapear_medal(self, medalla):
+ na_imagenes_medallas = Images.get_images_file_names(self.__resolucion, "medallas")
+ if medalla == ORO:
+ imagen_medalla = pygame.image.load(na_imagenes_medallas["oro"]["archivo"]).convert_alpha()
+ pos_inicial_medalla = na_imagenes_medallas["oro"]["pos_xy"]
+ elif medalla == PLATA:
+ imagen_medalla= pygame.image.load(na_imagenes_medallas["plata"]["archivo"]).convert_alpha()
+ pos_inicial_medalla = na_imagenes_medallas["plata"]["pos_xy"]
+ elif medalla == BRONZE:
+ imagen_medalla= pygame.image.load(na_imagenes_medallas["bronze"]["archivo"]).convert_alpha()
+ pos_inicial_medalla = na_imagenes_medallas["bronze"]["pos_xy"]
+ update_rect = pygame.Rect((pos_inicial_medalla[0], 0), (imagen_medalla.get_width(), pos_inicial_medalla[1]+imagen_medalla.get_height()))
+ velocidad = self.__vel_anim_medals
+ reloj = pygame.time.Clock()
+ y_max = -imagen_medalla.get_height()
+ y = pos_inicial_medalla[1]
+ while y > y_max:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y = y - distancia #distancia
+ if y_anterior < y_max and y > y_max:
+ y = y_max
+ self.ventana.blit(self.club.get_current_room_surface(), update_rect, update_rect)
+ self.ventana.blit(imagen_medalla, (pos_inicial_medalla[0], y))
+ pygame.display.update(update_rect)
+
+ def show_trophy(self, trofeo):
+ na_imagenes_trofeos = Images.get_images_file_names(self.__resolucion, "trofeos")
+ if trofeo == ORO:
+ imagen_trofeo = pygame.image.load(na_imagenes_trofeos["oro"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["oro"]["pos_xy"]
+ elif trofeo == MARFIL:
+ imagen_trofeo= pygame.image.load(na_imagenes_trofeos["marfil"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["marfil"]["pos_xy"]
+ elif trofeo == MADERA:
+ imagen_trofeo= pygame.image.load(na_imagenes_trofeos["madera"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["madera"]["pos_xy"]
+ update_rect = pygame.Rect((pos_final_trofeo[0], 0), (imagen_trofeo.get_width(), pos_final_trofeo[1]+imagen_trofeo.get_height()))
+ velocidad = self.__vel_anim_medals
+ reloj = pygame.time.Clock()
+ y_max = pos_final_trofeo[1]
+ y = -imagen_trofeo.get_height()
+ while y < y_max:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y = y + distancia #distancia
+ if y_anterior < y_max and y > y_max:
+ y = y_max
+ self.ventana.blit(self.club.get_current_room_surface(), update_rect, update_rect)
+ self.ventana.blit(imagen_trofeo, (pos_final_trofeo[0], y))
+ pygame.display.update(update_rect)
+
+ def dissapear_trophy(self, trofeo):
+ na_imagenes_trofeos = Images.get_images_file_names(self.__resolucion, "trofeos")
+ if trofeo == ORO:
+ imagen_trofeo = pygame.image.load(na_imagenes_trofeos["oro"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["oro"]["pos_xy"]
+ elif trofeo == MARFIL:
+ imagen_trofeo= pygame.image.load(na_imagenes_trofeos["marfil"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["marfil"]["pos_xy"]
+ elif trofeo == MADERA:
+ imagen_trofeo= pygame.image.load(na_imagenes_trofeos["madera"]["archivo"]).convert_alpha()
+ pos_final_trofeo = na_imagenes_trofeos["madera"]["pos_xy"]
+ update_rect = pygame.Rect((pos_final_trofeo[0], 0), (imagen_trofeo.get_width(), pos_final_trofeo[1]+imagen_trofeo.get_height()))
+ velocidad = self.__vel_anim_medals
+ reloj = pygame.time.Clock()
+ y_max = -imagen_trofeo.get_height()
+ y = pos_final_trofeo[1]
+ while y > y_max:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y = y - distancia #distancia
+ if y_anterior < y_max and y > y_max:
+ y = y_max
+ self.ventana.blit(self.club.get_current_room_surface(), update_rect, update_rect)
+ self.ventana.blit(imagen_trofeo, (pos_final_trofeo[0], y))
+ pygame.display.update(update_rect)
+
+ def show_board(self, con_configuracion=False):
+ self.__x_board = self.board.get_board_pos().x
+ if not self.__tablero_arriba:
+ self.__do_board_animation_show(configuracion=con_configuracion)
+ self.__tablero_arriba = True
+ else:
+ tablero_sup = self.board.render()
+ if con_configuracion:
+ conf_sup = self.board.get_configuration_surface()
+ update_rect = pygame.Rect((self.__x_board, 0), (tablero_sup.get_width(), tablero_sup.get_height()))
+ self.ventana.blit(tablero_sup, (self.__x_board, 0))
+ self.ventana.blit(conf_sup, (self.__x_board, 0))
+ pygame.display.update(update_rect)
+
+ def dissapear_board(self):
+ if self.__tablero_arriba:
+ self.__tablero_arriba = False
+ self.board.end_animation_cell()
+ self.__do_board_animation_show(factor=-1, configuracion=True)
+
+ def show_scores(self, turno=BLANCO):
+ if not self.__marcador_visible:
+ self.__fondo = self.ventana.copy()
+ self.__do_score_animation_show(turno=turno)
+ self.__marcador_visible = True
+ else:
+ marcador_der = self.marcador.render_right_score(self.board.get_logical_board(), turno)
+ marcador_izq = self.marcador.render_left_score(self.board.get_logical_board(), turno)
+ x1 = self.__resolucion[0] - marcador_der.get_width()
+ x2 = marcador_izq.get_width()
+ y2 = marcador_izq.get_height()
+ update_rect_izq = pygame.Rect((0, 0), (x2, y2))
+ update_rect_der = pygame.Rect((x1, 0), (x2, y2))
+ xi = 0
+ xd = self.__resolucion[0] - marcador_der.get_width()
+ self.ventana.blit(marcador_izq, (xi, 0))
+ self.ventana.blit(marcador_der, (xd, 0))
+ if self.text_box.up:
+ self.text_box.refresh_text_box(self.ventana)
+ pygame.display.update([update_rect_izq,update_rect_der])
+
+ def dissapear_scores(self):
+ if self.__marcador_visible:
+ self.__marcador_visible = False
+ self.__do_score_animation_show(factor=-1)
+
+ def dissapear_game_elements(self):
+ self.dissapear_board()
+ self.dissapear_scores()
+
+ def __do_score_animation_show(self, turno=BLANCO, factor=1):
+ marcador_der = self.marcador.render_right_score(self.board.get_logical_board(), turno)
+ marcador_izq = self.marcador.render_left_score(self.board.get_logical_board(), turno)
+ x1 = self.__resolucion[0] - marcador_der.get_width()
+ x2 = marcador_izq.get_width()
+ y2 = marcador_izq.get_height()
+ update_rect_izq = pygame.Rect((0, 0), (x2, y2))
+ update_rect_der = pygame.Rect((x1, 0), (x2, y2))
+ velocidad = self.__vel_anim_score
+ reloj = pygame.time.Clock()
+ if factor > 0:
+ xi = -marcador_izq.get_width()
+ xd = self.__resolucion[0]
+ xi_max = 0
+ xd_max = self.__resolucion[0] - marcador_der.get_width()
+ else:
+ xi = 0
+ xd = self.__resolucion[0] - marcador_der.get_width()
+ xi_max = -marcador_izq.get_width()
+ xd_max = self.__resolucion[0]
+ condicion = True
+ while condicion:
+ x_anterior = xi
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ xi = xi + (distancia * factor)
+ xd = xd - (distancia * factor)
+ if x_anterior < xi_max and xi > xi_max:
+ xi, xd = xi_max, xd_max
+ self.ventana.blit(self.__fondo,update_rect_izq,update_rect_izq)
+ self.ventana.blit(self.__fondo,update_rect_der,update_rect_der)
+ self.ventana.blit(marcador_izq, (xi, 0))
+ self.ventana.blit(marcador_der, (xd, 0))
+ if self.text_box.up:
+ self.text_box.refresh_text_box(self.ventana)
+ pygame.display.update([update_rect_izq,update_rect_der])
+ if factor > 0:
+ condicion = xi < xi_max
+ else:
+ condicion = xi > xi_max
+ #self.ventana.blit(self.club.get_current_room_surface(),(0,0))
+ #self.ventana.blit(marcador_izq, (xi, 0))
+ #self.ventana.blit(marcador_der, (xd, 0))
+ #pygame.display.update([update_rect_izq,update_rect_der])
+
+ def __do_board_animation_show(self, factor=1, configuracion=False):
+ tablero_sup = self.board.render()
+ if configuracion:
+ conf_sup = self.board.get_configuration_surface()
+ update_rect = pygame.Rect((self.__x_board, 0), (tablero_sup.get_width(), tablero_sup.get_height()))
+ velocidad = self.__vel_anim_tablero
+ reloj = pygame.time.Clock()
+ if factor > 0:
+ y_max = 0
+ y = -tablero_sup.get_height()
+ else:
+ y = 0
+ y_max = -tablero_sup.get_height()
+ condicion = True
+ while condicion:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y = y + (distancia * factor) #distancia
+ if y_anterior < y_max and y > y_max:
+ y = y_max
+ self.ventana.blit(self.club.get_current_room_surface(), update_rect, update_rect)
+ self.ventana.blit(tablero_sup, (self.__x_board, y))
+ if configuracion:
+ self.ventana.blit(conf_sup, (self.__x_board, y))
+ if factor > 0:
+ condicion = y < y_max
+ else:
+ condicion = y > y_max
+ pygame.display.update(update_rect)
+ #self.ventana.blit(self.club.get_current_room_surface(), (0, 0))
+ #self.ventana.blit(tablero_sup, (self.__x_board, y))
+ #pygame.display.update(update_rect)
+
+
+
+
+class TextBox:
+ def __init__(self, resolucion=RESOLUTION1):
+ na_otras_imagenes = Images.get_images_file_names(resolucion, "etc")
+ self.__image = pygame.image.load(na_otras_imagenes["caja_texto"]).convert_alpha()
+ self.__resolucion = resolucion
+ self.__init_constants(resolucion)
+ self.__init_fonts()
+ self.__contenido = ""
+ self.__encoding = 'iso-8859-15'
+ self.__sup_fondo = pygame.Surface(resolucion)
+ self.up = False
+ self.__tablero_g = ""
+
+ def __init_constants(self,resolucion):
+ #Si la resolucion es de 800x600
+ if resolucion == RESOLUTION1:
+ self.__y_max = 350
+ self.__y_inicial = 600.
+ self.__velocidad = 650.
+ self.__pos_ini_text = (30,380)
+ self.__tam_fuente = 30
+ self.__text_area = (700,250)
+ elif resolucion == RESOLUTION2:
+ self.__tam_fuente = 40
+ self.__y_max = 530
+ self.__y_inicial = 900.
+ self.__velocidad = 1500.
+ self.__text_area = (1100,300)
+ self.__pos_ini_text = (40,580)
+ else:
+ raise Exception("Resolucion desconocida (Text Box Class)")
+ self.__text_color = (0,0,0)
+ self.__update_rect = pygame.Rect((0, self.__y_max), (self.__image.get_width(), self.__image.get_height()))
+
+ def __init_fonts(self):
+ self.__fuente = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"] ,self.__tam_fuente)
+
+ def get_image(self):
+ return self.__image
+
+ def get_sprite(self):
+ return self.__sprite
+
+ def get_final_position(self):
+ return (0,self.__y_max)
+
+ def is_up(self):
+ return self.up
+
+ def set_up_graphic_board(self, tablero_g):
+ self.__tablero_g = tablero_g
+
+ def __render_textrect(self, string, font, rect, text_color, justification=0):
+ """Returns a surface containing the passed text string, reformatted
+ to fit within the given rect, word-wrapping as necessary. The text
+ will be anti-aliased.
+
+ Takes the following arguments:
+
+ string - the text you wish to render. \n begins a new line.
+ font - a Font object
+ rect - a rectstyle giving the size of the surface requested.
+ text_color - a three-byte tuple of the rgb value of the
+ background_color - a three-byte tuple of the rgb value of the surface.
+ justification - 0 (default) left-justified
+ 1 horizontally centered
+ 2 right-justified
+
+ Returns the following values:
+
+ Success - a surface object with the text rendered onto it.
+ Failure - raises a Exception if the text won't fit onto the surface.
+ """
+
+
+ final_lines = []
+
+ requested_lines = string.splitlines()
+
+ # Create a series of lines that will fit on the provided
+ # rectangle.
+
+ for requested_line in requested_lines:
+ if font.size(requested_line)[0] > rect[0]:
+ words = requested_line.split(' ')
+ # if any of our words are too long to fit, return.
+ for word in words:
+ if font.size(word)[0] >= rect[0]:
+ raise Exception("The word " + word + " is too long to fit in the rect passed.")
+ # Start a new line
+ accumulated_line = ""
+ for word in words:
+ test_line = accumulated_line + word + " "
+ # Build the line while the words fit.
+ if font.size(test_line)[0] < rect[0]:
+ accumulated_line = test_line
+ else:
+ final_lines.append(accumulated_line)
+ accumulated_line = word + " "
+ final_lines.append(accumulated_line)
+ else:
+ final_lines.append(requested_line)
+
+ # Let's try to write the text out on the surface.
+
+ surface = pygame.Surface(rect,SRCALPHA,32)
+
+ accumulated_height = 0
+ for line in final_lines:
+ if accumulated_height + font.size(line)[1] >= rect[1]:
+ raise Exception("Once word-wrapped, the text string was too tall to fit in the rect.")
+ if line != "":
+ tempsurface = font.render(line, True, text_color)
+ if justification == 0:
+ surface.blit(tempsurface, (0, accumulated_height))
+ #self.__sup_texto.blit(tempsurface, (0, accumulated_height))
+ elif justification == 1:
+ surface.blit(tempsurface, ((rect[0] - tempsurface.get_width()) / 2, accumulated_height))
+ #self.__sup_texto.blit(tempsurface, ((rect[0] - tempsurface.get_width()) / 2, accumulated_height))
+ elif justification == 2:
+ surface.blit(tempsurface, (rect[0] - tempsurface.get_width(), accumulated_height))
+ #self.__sup_texto.blit(tempsurface, (rect[0] - tempsurface.get_width(), accumulated_height))
+ else:
+ raise Exception("Invalid justification argument: " + str(justification))
+ accumulated_height += font.size(line)[1]
+
+ return surface
+
+ def write(self,texto):
+ texto = unicode(texto,'latin-1')
+ texto = texto.encode(self.__encoding)
+ self.__contenido = self.__render_textrect(texto, self.__fuente, self.__text_area, self.__text_color, 0)
+
+ def show_text(self, superficie, texto):
+ self.write(texto)
+ if self.__contenido != "":
+ if self.up:
+ self.refresh_text_box(superficie)
+ else:
+ self.show(superficie)
+ self.refresh_text_box(superficie)
+ if not self.__tablero_g == "":
+ dim = self.__tablero_g.get_logical_board().get_dimension()
+ if dim == 6:
+ sup_text_box_and_text = pygame.Surface(self.__contenido.get_size(),SRCALPHA,32)
+ sup_text_box_and_text.blit(self.__image, (0,0))
+ sup_text_box_and_text.blit(self.__contenido, (self.__pos_ini_text[0],self.__pos_ini_text[1]-self.__y_max))
+ self.__tablero_g.set_up_image({'imagen':sup_text_box_and_text, 'posicion':(0,self.__y_max)})
+ #self.__tablero_g.set_up_image({'imagen':self.__image, 'posicion':(0,self.__y_max)})
+ #self.__tablero_g.set_up_image({'imagen':self.__contenido, 'posicion':self.__pos_ini_text})
+
+ def refresh_text_box(self, superficie):
+ superficie.blit(self.__image, (0, self.__y_max))
+ superficie.blit(self.__contenido, self.__pos_ini_text)
+ self.up = True
+ pygame.display.update(self.__update_rect)
+
+ def delete_text(self):
+ self.__contenido = pygame.Surface(self.__text_area,SRCALPHA,32)
+
+ def show(self, superficie):
+ self.__sup_fondo = superficie.copy()
+ y = self.__y_inicial
+ velocidad = self.__velocidad
+ reloj = pygame.time.Clock()
+ while y > self.__y_max:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y -= distancia #30
+ if y_anterior > self.__y_max and y < self.__y_max:
+ y = self.__y_max
+ superficie.blit(self.__image, (0, y))
+ pygame.display.update(self.__update_rect)
+ self.up = True
+ #if not self.__tablero_g == "":
+ # dim = self.__tablero_g.get_logical_board().get_dimension()
+ # if dim == 6:
+ # self.__tablero_g.set_up_image({'imagen':self.__image, 'posicion':(0,self.__y_max)})
+
+
+ def disappear(self, superficie):
+ if self.up:
+ if not self.__tablero_g == "":
+ dim = self.__tablero_g.get_logical_board().get_dimension()
+ if dim == 6:
+ self.__tablero_g.remove_up_images()
+ y = self.__y_max
+ velocidad = self.__velocidad
+ reloj = pygame.time.Clock()
+ while y < self.__y_inicial:
+ y_anterior = y
+ tiempo_pasado = reloj.tick()
+ tiempo_pasado_segundos = tiempo_pasado / 1000.0
+ distancia = tiempo_pasado_segundos * velocidad
+ y += distancia #30
+ if y_anterior < self.__y_max and y > self.__y_max:
+ y = self.__y_inicial
+ superficie.blit(self.__sup_fondo, self.__update_rect, self.__update_rect)
+ superficie.blit(self.__image, (0, y))
+ pygame.display.update(self.__update_rect)
+ self.up = False
+
+class SelectionList:
+ NEGRO = -500
+ AMARILLO = -501
+
+ def __init__(self, resolucion=RESOLUTION2, ventana="", titulo="", tipo=""):
+ self.__resolucion = resolucion
+ self.__ventana = ventana
+ self.__init_constants(tipo)
+ self.__init_fonts()
+ self.__opciones = []
+ self.__opciones_visibles = []
+ if titulo == "":
+ self.__titulo = "OPCIONES"
+ else:
+ self.__titulo = titulo
+ self.__color_destello = self.AMARILLO
+
+ def __init_constants(self, tipo):
+ if self.__resolucion == RESOLUTION1:
+ if tipo == "secretaria":
+ self.__tam = (650,262)
+ self.__tam_frente = (640,192)
+ self.__tam_seleccion = (630,50)
+ self.__pos_pantalla =(80,200)
+ elif tipo == "sin_jugadas_posibles":
+ self.__tam = (480,262)
+ self.__tam_frente = (470,192)
+ self.__tam_seleccion = (460,50)
+ self.__pos_pantalla =(300,90)
+ else:
+ self.__tam = (400,262)
+ self.__tam_frente = (390,192)
+ self.__tam_seleccion = (380,50)
+ self.__pos_pantalla =(380,90)
+ self.__formato_titulo = {"tamano" : 25, "color": (216,216,0)}
+ self.__formato_opciones = {"tamano" : 25, "color" : (0,0,0)}
+ self.__formato_opcion = {"tamano" : 25, "color" : (216,216,0)}
+ elif self.__resolucion == RESOLUTION2:
+ if tipo == "secretaria":
+ self.__tam = (850,394)
+ self.__tam_frente = (840,324)
+ self.__tam_seleccion = (830,55)
+ self.__pos_pantalla = (120,300)
+ elif tipo == "sin_jugadas_posibles":
+ self.__tam = (720,324)
+ self.__tam_frente = (705,254)
+ self.__tam_seleccion = (690,55)
+ self.__pos_pantalla =(450,200)
+ else:
+ self.__tam = (600,324)
+ self.__tam_frente = (590,254)
+ self.__tam_seleccion = (580,55)
+ self.__pos_pantalla = (550,200)
+ self.__formato_titulo = {"tamano" : 35, "color": (216,216,0)}
+ self.__formato_opciones = {"tamano" : 35, "color" : (0,0,0)}
+ self.__formato_opcion = {"tamano" : 35, "color" : (216,216,0)}
+ self.__tam_max = 3
+
+ def __init_fonts(self):
+ self.__fuente_titulo = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"] ,self.__formato_titulo["tamano"])
+ self.__fuente_opciones = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"] ,self.__formato_opciones["tamano"])
+ self.__fuente_opcion = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"] ,self.__formato_opcion["tamano"])
+
+ def get_screen_position(self):
+ return self.__pos_pantalla
+
+ def draw(self):
+ self.__fondo = self.__ventana.copy()
+ self.__main_surface = pygame.Surface(self.__tam)
+ frente = pygame.Surface(self.__tam_frente)
+ frente.fill(((216, 216, 0)))
+ self.__main_surface.blit(frente, (5,65))
+ titulo = self.__fuente_titulo.render(self.__titulo, True, self.__formato_titulo["color"])
+ pos_x = (self.__tam[0] - titulo.get_width()) / 2
+ self.__main_surface.blit(titulo,(pos_x,5))
+ return self.__main_surface
+
+ def add_options(self, opciones):
+ c_opciones = 1
+ for o in opciones:
+ opcion = {}
+ opcion["descripcion"] = o["descripcion"]
+ opcion["id"] = o["id"]
+ opcion["visible"] = o["visible"]
+ if "medalla" in o:
+ opcion["medalla"] = o["medalla"]
+ if c_opciones == 1:
+ opcion["seleccionada"] = True
+ else:
+ opcion["seleccionada"] = False
+ if opcion["visible"]:
+ self.__opciones_visibles.append(opcion)
+ self.__opciones.append(opcion)
+ c_opciones += 1
+ #self.__render_options()
+
+ def render_options(self):
+ y = 100
+ for o in self.__opciones_visibles:
+ if o["seleccionada"]:
+ opcion = self.__fuente_opcion.render(o["descripcion"], True, self.__formato_opcion["color"])
+ rect_sup = pygame.Surface((self.__tam_seleccion))
+ rect_sup.fill((0,0,0))
+ self.__main_surface.blit(rect_sup, (10,y-5))
+ pos_x = (self.__tam_frente[0] - opcion.get_width()) / 2
+ self.__main_surface.blit(opcion, (pos_x,y))
+ else:
+ opcion = self.__fuente_opciones.render(o["descripcion"], True, self.__formato_opciones["color"])
+ pos_x = (self.__tam_frente[0] - opcion.get_width()) / 2
+ self.__main_surface.blit(opcion, (pos_x,y))
+ o["posicion_pantalla"] = (pos_x,y)
+ y += 60
+ return self.__main_surface
+
+ def change_selection_options(self, direccion, audio):
+ indice_sel_anterior = self.__index_option_selected_visible_list()
+ can_opciones = len(self.__opciones)
+ if direccion == ARRIBA:
+ for i in xrange(0,can_opciones):
+ if self.__opciones[i]["seleccionada"]:
+ if not i == 0:
+ self.__opciones[i]["seleccionada"] = False
+ self.__opciones[i-1]["seleccionada"] = True
+ self.__opciones[i-1]["visible"] = True
+ nueva_opcion_visible = self.__opciones[i-1]
+ break
+ else:
+ self.__opciones[i]["seleccionada"] = False
+ self.__opciones[can_opciones-1]["seleccionada"] = True
+ self.__opciones[can_opciones-1]["visible"] = True
+ nueva_opcion_visible = self.__opciones[can_opciones-1]
+ break
+ elif direccion == ABAJO:
+ cambio_seleccion = False
+ for i in xrange(0,can_opciones):
+ if self.__opciones[i]["seleccionada"]:
+ if not i == can_opciones-1 and not cambio_seleccion:
+ self.__opciones[i]["seleccionada"] = False
+ self.__opciones[i+1]["seleccionada"] = True
+ self.__opciones[i+1]["visible"] = True
+ nueva_opcion_visible = self.__opciones[i+1]
+ cambio_seleccion = True
+ elif i == can_opciones-1 and not cambio_seleccion:
+ self.__opciones[i]["seleccionada"] = False
+ self.__opciones[0]["seleccionada"] = True
+ cambio_seleccion = True
+ self.__opciones[0]["visible"] = True
+ nueva_opcion_visible = self.__opciones[0]
+ else:
+ raise Exception("Error!, direccion desconocida (SelectionList Class)")
+ if len(self.__opciones_visibles) == self.__tam_max:
+ if indice_sel_anterior == 0 and direccion == ARRIBA or \
+ indice_sel_anterior == (self.__tam_max-1) and direccion == ABAJO:
+ self.__update_visibles_options_list(nueva_opcion_visible, direccion)
+ frente = pygame.Surface(self.__tam_frente)
+ frente.fill((216, 216, 0))
+ self.__main_surface.blit(frente, (5,65))
+ list_sup = self.render_options()
+ self.__ventana.blit(list_sup,self.__pos_pantalla)
+ self.read_option(audio)
+
+ def __index_option_selected_visible_list(self):
+ for o in self.__opciones_visibles:
+ if o["seleccionada"]:
+ indice = self.__opciones_visibles.index(o)
+ return indice
+
+ def __update_visibles_options_list(self, nueva_op_visible, direccion):
+ if direccion == ABAJO:
+ self.__opciones_visibles.pop(0)
+ self.__opciones_visibles.append(nueva_op_visible)
+ else:
+ self.__opciones_visibles.pop()
+ self.__opciones_visibles.insert(0,nueva_op_visible)
+
+ def read_option(self, audio):
+ for o in self.__opciones:
+ if o["seleccionada"]:
+ nombre_audio = o["id"]
+ if type(nombre_audio) == type(""):
+ if not nombre_audio.find("chal") == -1:
+ audio.play_voice_sound("selector","tomar")
+ audio.play_voice_sound("selector","desafio")
+ audio.play_voice_sound("selector",nombre_audio.split("_chal_")[1])
+ if not o["medalla"] == "":
+ audio.play_voice_sound("selector","actualmente_tiene_la")
+ if o["medalla"] == BRONZE:
+ audio.play_voice_sound("selector","medalla_bronze")
+ elif o["medalla"] == PLATA:
+ audio.play_voice_sound("selector","medalla_plata")
+ elif o["medalla"] == ORO:
+ audio.play_voice_sound("selector","medalla_oro")
+ elif not nombre_audio.find("progreso") == -1:
+ progreso = nombre_audio.split("-")
+ audio.play_voice_sound("selector",progreso[0])
+ numero = get_number_word(int(progreso[1]))
+ audio.play_voice_sound("numero",numero)
+ audio.play_voice_sound("selector","porciento")
+ elif not nombre_audio.find("medallas") == -1:
+ str_medallas = nombre_audio.split("-")
+ audio.play_voice_sound("selector",str_medallas[0])
+ vec_medallas = str_medallas[1].split(".")
+ medallas_bronze = int(vec_medallas[0])
+ medallas_plata = int(vec_medallas[1])
+ medallas_oro = int(vec_medallas[2])
+ medallas_total = medallas_bronze + medallas_plata + medallas_oro
+ audio.play_voice_sound("numero", get_number_word(medallas_bronze,medallas=True))
+ if medallas_bronze == 1:
+ audio.play_voice_sound("selector","medalla_bronze")
+ else:
+ audio.play_voice_sound("selector","medallas_bronze")
+ audio.play_voice_sound("numero", get_number_word(medallas_plata,medallas=True))
+ if medallas_plata == 1:
+ audio.play_voice_sound("selector","medalla_plata")
+ else:
+ audio.play_voice_sound("selector","medallas_plata")
+ audio.play_voice_sound("numero", get_number_word(medallas_oro,medallas=True))
+ if medallas_oro == 1:
+ audio.play_voice_sound("selector","medalla_oro")
+ else:
+ audio.play_voice_sound("selector","medallas_oro")
+ audio.play_voice_sound("numero", get_number_word(medallas_total,medallas=True))
+ if medallas_total == 1:
+ audio.play_voice_sound("selector","medalla_total")
+ else:
+ audio.play_voice_sound("selector","medallas_total")
+
+ else:
+ audio.play_voice_sound("selector",nombre_audio)
+ else:
+ #Estamos en el salon de encuentros leyendo las opciones de oponentes, para ello usamos festival
+ pass
+ #pyfestival.Festival().say(o["descripcion"])
+
+ def option_more_info(self, audio):
+ for o in self.__opciones:
+ if o["seleccionada"]:
+ nombre_audio = o["id"]
+ try:
+ if type(nombre_audio) == type(""):
+ if not nombre_audio.find("progreso") == -1:
+ nombre_audio = nombre_audio.split("-")[0]
+ elif not nombre_audio.find("medallas") == -1:
+ nombre_audio = nombre_audio.split("-")[0]
+ audio.play_voice_sound("selector",nombre_audio+"_desc")
+ else:
+ pyfestival.Festival().say(o["descripcion"])
+ except:
+ log.warning("No hay descripcion para la opcion seleccionada")
+
+ def get_selected_option(self):
+ for o in self.__opciones:
+ if o["seleccionada"]:
+ return o
+
+ def blink_option(self):
+ opcion_seleccionada = self.get_selected_option()
+ if self.__color_destello == self.AMARILLO:
+ b_opcion = self.__fuente_opciones.render(opcion_seleccionada["descripcion"], True, self.__formato_opciones["color"])
+ self.__color_destello = self.NEGRO
+ else:
+ b_opcion = self.__fuente_opcion.render(opcion_seleccionada["descripcion"], True, self.__formato_opcion["color"])
+ self.__color_destello = self.AMARILLO
+ self.__main_surface.blit(b_opcion, opcion_seleccionada["posicion_pantalla"])
+ self.__ventana.blit(self.__main_surface,self.get_screen_position())
+ update_rect = pygame.Rect(self.__pos_pantalla, self.__tam)
+ pygame.time.wait(100)
+ pygame.display.update(update_rect)
+
+ def remove(self):
+ update_rect = pygame.Rect(self.__pos_pantalla, self.__tam)
+ self.__ventana.blit(self.__fondo,update_rect,update_rect)
+ pygame.display.update(update_rect) diff --git a/src/input_output/video.pyc b/src/input_output/video.pyc Binary files differnew file mode 100644 index 0000000..3d06292 --- /dev/null +++ b/src/input_output/video.pyc diff --git a/src/main/__init__.py b/src/main/__init__.py new file mode 100755 index 0000000..e69de29 --- /dev/null +++ b/src/main/__init__.py diff --git a/src/main/__init__.pyc b/src/main/__init__.pyc Binary files differnew file mode 100644 index 0000000..8978078 --- /dev/null +++ b/src/main/__init__.pyc diff --git a/src/main/constants.py b/src/main/constants.py new file mode 100755 index 0000000..02c1da8 --- /dev/null +++ b/src/main/constants.py @@ -0,0 +1,114 @@ +#Resolutions
+RESOLUTION1 = (800,600)
+RESOLUTION2 = (1200,900)
+
+###
+#Room Constants
+###
+PLANTABAJA = 300
+PRIMERPISO = 301
+SEGUNDOPISO = 302
+TERCERPISO = 303
+CUARTOPISO = 304
+SECRETARIA = 305
+SALONDECLASES = 306
+SALONDEDESAFIOS = 307
+SALONDEENCUENTROS = 308
+HABITACIONPM = 309
+HABITACIONSD = 310
+HABITACIONPTE = 311
+ENTRADA = 312
+PASILLO = 313
+
+###
+#Characters Constants
+###
+PABLOGRIS = 401
+DONCANO = 402
+PEDROMADERA = 403
+SOFIADULCE = 404
+PROTASIO = 405
+
+#Skill Levels
+NULL = 500
+TUTORIAL1 = 501
+CHALLENGE1 = 502
+CHALLENGE2 = 504
+CHALLENGE3 = 506
+CHALLENGE4 = 507
+CHALLENGES_COMPLETED = 508
+WON_VOCAL = 503
+TUTORIAL2 = 505
+CLEAR_GAMES = 509
+CLEAR_CHALLENGES = 510
+ALL_CLEAR = 511
+
+#Characters Relations
+MEET = 600
+WON1 = 601
+WON2 = 611
+DRAW1 = 607
+LOSE1 = 608
+DRAW2 = 612
+LOSE2 = 613
+DRAW3 = 614
+LOSE3 = 615
+WON3 = 616
+WELCOME = 604
+F_MEET_BLOCK_VOCALS = 602
+S_MEET_BLOCK_VOCALS = 603
+MEET_GO_TUT = 605
+MEET_GO_TUT_AGAIN = 606
+MEET_GO_CHAL1 = 609
+MEET_GO_CHAL1_AGAIN = 610
+MEET_GO_CHAL4 = 617
+
+#Contexts
+NAVE = 700
+DIAL = 701
+PLAY = 702
+LIST = 703
+ENTR = 704
+
+#Initial State
+INITIAL_STATE = "state0"
+
+#Keys
+IZQUIERDA = 800
+DERECHA = 801
+ARRIBA = 802
+ABAJO = 803
+CONTINUAR = 804
+MAS_INFO = 805
+SALIR = 806
+SELECCION = 807
+ATRAS = 808
+CONTAR_FICHAS = 809
+TECLA_DESCONOCIDA = 810
+ATAJO_GANAR_JUEGO = 811
+ATAJO_PERDER_JUEGO = 812
+ATAJO_EMPATAR_JUEGO = 813
+ATAJO_PASAR_TUTORIAL = 814
+
+#Results
+GANAR = 900
+EMPATAR = 901
+PERDER = 902
+
+#Others
+STANDART_BOARD_DIMENSION = 4
+
+#MEDALS
+BRONZE = 1000
+PLATA = 1001
+ORO = 1002
+
+#Trophies
+MARFIL = 3001
+MADERA = 3002
+
+#Estados de la mesh
+ESPERANDO_OPONENTE = 2000
+JUGANDO = 2001
+ON = 2002
+OFF = 2003
\ No newline at end of file diff --git a/src/main/constants.pyc b/src/main/constants.pyc Binary files differnew file mode 100644 index 0000000..2eebcc7 --- /dev/null +++ b/src/main/constants.pyc diff --git a/src/main/engine.py b/src/main/engine.py new file mode 100755 index 0000000..d38c271 --- /dev/null +++ b/src/main/engine.py @@ -0,0 +1,509 @@ +from hyperhistory.club import Club
+from user import User
+from constants import IZQUIERDA,DERECHA,ARRIBA,ABAJO,CONTINUAR,SALIR,NAVE,DIAL,PLAY,LIST,MAS_INFO, \
+ ATRAS,SELECCION,CONTAR_FICHAS,ON,OFF,ATAJO_GANAR_JUEGO,ATAJO_PERDER_JUEGO,ATAJO_EMPATAR_JUEGO, ATAJO_PASAR_TUTORIAL
+from keys import Keys
+from hyperhistory.events import Events
+from hyperhistory.dialog import DialogueManager
+from hyperhistory.navigation import NavigationManager
+from othello.game import Game
+from othello.player import *
+from othello.board import Board, BLANCO, NEGRO
+from othello.gui import GraphicBoard
+from othello.ai import Ai
+from _xml.parser import Parser
+import os, thread, logging
+import olpcgames
+
+log = logging.getLogger( 'src.main.engine' )
+log.setLevel( logging.DEBUG )
+
+class Engine():
+ def __init__(self, main_path="", write_path="", video="", audio="", malla="", actividad_compartida=False):
+ if main_path == "":
+ raise Exception("Error!, engine necesita el path al directorio principal de la aplicacion para funcionar (Class Engine)")
+ if video == "" or audio == "" or malla == "":
+ raise Exception("Error!, engine necesita Audio, Video y Malla para funcionar (Class Engine)")
+ self.__main_path = main_path
+ self.__write_path = write_path
+ #Iniciliazo el Audio y Video
+ self.__video = video
+ self.__audio = audio
+ self.__malla = malla
+ self.__actividad_compartida = actividad_compartida
+ self.__audio.on_channel()
+ #Inicializo las teclas
+ self.__keys = Keys(main_path)
+ #Iniciliazo el club (habitaciones)
+ self.__club = Club(main_path)
+ #Inicializo el usuario
+ if self.__actividad_compartida:
+ self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_shared_initial_room())
+ self.__paso_introduccion = True
+ self.change_context(PLAY)
+ else:
+ self.__usuario = User(main_path,write_path,lugar_inicial=self.__club.get_alone_initial_room())
+ self.__paso_introduccion = False
+ #Seteo la configuracion del club a los valores del estado actual del usuario
+ self.__estado_actual = self.__usuario.get_state()
+ self.__club.set_current_state(self.__estado_actual)
+ self.__keys.enable_keys(self.__usuario.get_context())
+ #Iniciliazo el administrador de navegacion
+ self.__navegacion_manager = NavigationManager(self, write_path)
+ #Iniciliazo el administrador de dialogos
+ self.__dialogo_manager = DialogueManager(engine=self,main_path=main_path,write_path=write_path)
+ self.__events = Events()
+ self.__accion = {}
+ self.__path_archivo_juegos = main_path+"/data/games.xml"
+ self.__show_club_introduction()
+ self.__juego_mesh = False
+
+ def get_user(self):
+ return self.__usuario
+
+ def get_audio(self):
+ return self.__audio
+
+ def get_video(self):
+ return self.__video
+
+ def get_club(self):
+ return self.__club
+
+ def get_keys(self):
+ return self.__keys
+
+ def get_dialog_manager(self):
+ return self.__dialogo_manager
+
+ def get_navigation_manager(self):
+ return self.__navegacion_manager
+
+ def set_action(self, metodo, parametros=""):
+ self.__accion = {"metodo":metodo,"parametros":parametros}
+
+ def on_play_mesh_game(self):
+ self.__juego_mesh = True
+
+ def off_play_mesh_game(self):
+ self.__juego_mesh = False
+
+ def init_game(self, nombre, con_jugadas_posibles=True, nivel=Ai.FACIL):
+ parser = Parser()
+ archivo_juegos = open(os.path.abspath(self.__path_archivo_juegos))
+ elementos = parser.find_child_element("game_"+str(nombre),archivo_juegos)
+ fichas_iniciales = []
+ if len(elementos) <= 0 :
+ raise Exception("No se encontraron elementos para el juego: " + nombre + " en el archivo xml: " + self.__path_archivo_juegos)
+ for e in elementos:
+ if e.get_name() == 'features':
+ board_dim = int(e.get_attribute('board'))
+ if e.get_attribute('oponent') == "virtual":
+ #Es un juego de mesh contra Humano
+ jugador1 = Player(BLANCO,HUMANO)
+ jugador2 = Player(NEGRO,VIRTUAL)
+ else:
+ #Es un juego contra la PC
+ if e.get_attribute('white') == "user":
+ jugador1 = Player(BLANCO,HUMANO)
+ jugador2 = Player(NEGRO,PC)
+ else:
+ jugador1 = Player(BLANCO,PC)
+ jugador2 = Player(NEGRO,HUMANO)
+ if e.get_attribute('initiator') == "white":
+ comienza = BLANCO
+ else:
+ comienza = NEGRO
+ elif e.get_name() == 'piece':
+ ficha = {}
+ if e.get_attribute('color') == "black":
+ ficha["color"] = NEGRO
+ else:
+ ficha["color"] = BLANCO
+ ficha["posicion"] = (int(e.get_attribute('pos_f')),int(e.get_attribute('pos_c')))
+ fichas_iniciales.append(ficha)
+ tablero_logico = Board(board_dim)
+ if nombre == "tutorial1":
+ tablero_logico.save_initial_configuration(fichas_iniciales)
+ else:
+ tablero_logico.set_up(fichas_iniciales)
+ self.__video.create_graphic_board(tablero_logico)
+ self.juego = Game(self.__video.board,jugador1,jugador2,con_jugadas_posibles,nivel,write_path=self.__write_path)
+ if comienza == BLANCO:
+ self.juego.set_turn(jugador1)
+ else:
+ self.juego.set_turn(jugador2)
+ self.juego.increase_turn_number()
+ if nombre == "mesh":
+ self.juego.set_mesh_game(True)
+ self.__usuario.set_player(jugador1)
+ parser.close()
+ archivo_juegos.close()
+
+ def setup_game(self, config, nombre=""):
+ tablero_logico = Board(config["tablero"]["dimension"])
+ tablero_logico.set_casillas(config["tablero"]["configuracion"])
+ tablero_logico.update_pieces_counters()
+ self.__video.create_graphic_board(tablero_logico)
+ jugador1 = Player(config["jugadores"][0]["color"],VIRTUAL)
+ jugador2 = Player(config["jugadores"][1]["color"],HUMANO)
+ self.juego = Game(self.__video.board,jugador1,jugador2,write_path=self.__write_path)
+ self.juego.set_turn(jugador1)
+ self.juego.increase_turn_number()
+ if nombre == "mesh":
+ self.juego.set_mesh_game(True)
+ self.__usuario.set_player(jugador2)
+
+ def __show_club_introduction(self):
+ self.__video.club.show_room(self.__usuario.get_current_room())
+ if not self.__actividad_compartida:
+ self.__audio.play_voice_sound("club","voz_inicio")
+
+ def __join_the_club(self):
+ self.__audio.play_fx_sound("club","pasos")
+ nueva_hab = self.__usuario.get_current_room().get_up_room()
+ self.__paso_introduccion = True
+ self.__usuario.set_current_room(nueva_hab)
+ if self.__usuario.get_state().is_initial_state():
+ self.__video.club.move_to_another_floor(nueva_hab,ARRIBA,extra="introduccion")
+ self.change_context(DIAL)
+ else:
+ self.__video.club.move_to_another_floor(nueva_hab,ARRIBA)
+ self.change_context(NAVE)
+ self.__begin_game()
+
+ def change_context(self, nuevo_contexto):
+ self.__usuario.set_context(nuevo_contexto)
+ self.__keys.enable_keys(nuevo_contexto)
+
+ def __begin_game(self):
+ self.__run_state_events()
+
+ def __run_state_events(self):
+ #Verificar si existe algun evento para el estado actual y ejecutarlo
+ eventos_iniciales = self.__estado_actual.get_state_events()
+ for evento in eventos_iniciales:
+ #thread.start_new_thread(self.__events.run_events,(self, eventos_iniciales))
+ self.__events.run_event(self, evento)
+
+ def change_state(self, nuevo_estado):
+ self.__usuario.set_state(nuevo_estado)
+ self.__estado_actual = self.__usuario.get_state()
+ self.__club.set_current_state(self.__estado_actual)
+ self.__run_state_events()
+
+
+ def arrive_input(self, accion):
+ if not self.__keys.is_enable(accion):
+ self.__audio.play_disabled_key_sound()
+ else:
+ if accion == SALIR:
+ if self.__actividad_compartida:
+ self.__actividad_compartida = False
+ self.__malla.remove_me()
+ self.__navegacion_manager.exit_club()
+ else:
+ if self.__paso_introduccion:
+ if self.__usuario.get_context() == NAVE:
+ self.__audio.play_key_sound(accion)
+ self.__make_nav_action(accion)
+ elif self.__usuario.get_context() == DIAL:
+ if not self.__usuario.interrupt_dialogue():
+ if self.__audio.get_sound_name() == "more_text":
+ self.__audio.play_key_sound(accion)
+ self.__make_dialog_action(accion)
+ else:
+ self.__audio.play_disabled_key_sound()
+ else:
+ self.__audio.play_key_sound(accion)
+ self.__make_dialog_action(accion)
+ elif self.__usuario.get_context() == PLAY:
+ if not self.__usuario.interrupt_sounds() and self.__audio.get_sound_group_name() == "inicio_turno":
+ self.__audio.play_disabled_key_sound()
+ else:
+ self.__audio.play_key_sound(accion)
+ self.__make_play_action(accion)
+ elif self.__usuario.get_context() == LIST:
+ self.__audio.play_key_sound(accion)
+ self.__make_list_action(accion)
+ else:
+ self.__audio.play_key_sound(accion)
+ if accion == CONTINUAR:
+ self.__join_the_club()
+
+ def __make_nav_action(self, accion):
+ if accion == CONTINUAR:
+ hab_sel = self.__club.room_selected()["habitacion"]
+ pos_hab_sel = self.__club.room_selected()["posicion"]
+ if hab_sel != "":
+ if hab_sel.is_available():
+ self.__navegacion_manager.enter_room(hab_sel, pos_hab_sel)
+ if not hab_sel.is_floor():
+ #Es una habitacion
+ if hab_sel.get_name() != "salon de encuentros" and hab_sel.get_name() != "secretaria":
+ self.change_context(DIAL)
+ per_duenho = hab_sel.get_owner()
+ per_duenho.init_room_action(self)
+ self.__accion = {"metodo":per_duenho.close_action,"parametros":(self)}
+ else:
+ if hab_sel.get_name() == "salon de encuentros":
+ try:
+ ps = olpcgames.ACTIVITY._pservice
+ self.__audio.play_voice_sound("club","ingresando a la red")
+ ps.get_activities_async(reply_handler=self._share_join_activity_cb)
+ except Exception, e:
+ log.debug('Error: ' + str(e) + '. Al intentar usar el presence service (Engine Class)')
+ self.__audio.play_voice_sound("club","error de conexion")
+ self.__audio.play_voice_sound("club","saliendo salon desafios")
+ self.__navegacion_manager.leave_room()
+ elif hab_sel.get_name() == "secretaria":
+ self.change_context(LIST)
+ self.__video.create_selection_list(titulo="OPCIONES DE SECRETARIA",tipo="secretaria")
+ progreso = self.__usuario.get_game_progress()
+ hash_medallas = self.__usuario.get_medals()
+ total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
+ str_medallas = str(hash_medallas["bronce"])+" BR "+str(hash_medallas["plata"])+" PL "+str(hash_medallas["oro"])+" OR "+str(total_medallas)+" TOT"
+ self.__video.selection_list.add_options([{"descripcion":"Progreso del Juego: "+str(progreso)+"%","id":"progreso_juego-"+str(progreso),"visible":True},{"descripcion":"Medallas: "+str_medallas, "id":"medallas_obtenidas-"+str(hash_medallas["bronce"])+"."+str(hash_medallas["plata"])+"."+str(hash_medallas["oro"]),"visible":True}])
+ self.__video.show_selection_list()
+ self.__audio.play_voice_sound("club","secretaria intro")
+ self.__audio.play_voice_sound("club","secretaria desc")
+ self.__audio.play_voice_sound("club","secretaria info")
+ self.__audio.play_fx_sound("otros","wait_input")
+ self.__video.selection_list.read_option(self.__audio)
+ else:
+ log.error("Nombre de habitacion desconocido! (Engine Class)")
+ else:
+ if not hab_sel.is_floor():
+ if hab_sel.get_owner() != "":
+ self.__audio.play_voice_sound("club","bloqueo_acceso_pieza_vocal")
+ else:
+ if hab_sel.get_name() == "salon de encuentros":
+ self.__audio.play_voice_sound("club","bloqueo_acceso_salon_encuentros")
+ else:
+ self.__audio.play_voice_sound("club","bloqueo_acceso_pieza_gral")
+ self.__audio.wait_sound_end()
+ self.__video.club.end_door_animation()
+ self.__club.select_room("","")
+ elif self.__club.get_elevator()["seleccionado"]:
+ if not self.__navegacion_manager.go_to_floor():
+ if self.__usuario.get_state().get_name() == "state1" and self.__usuario.get_current_room().get_name() == "segundo piso":
+ pm = self.__club.get_character_by_name("pedro madera")
+ self.change_context(DIAL)
+ pm.block_third_floor_access(self)
+ self.__accion = {"metodo":pm.close_action,"parametros":(self)}
+ elif self.__usuario.get_current_room().get_name() == "tercer piso":
+ hash_medallas = self.__usuario.get_medals()
+ total_medallas = hash_medallas["bronce"] + hash_medallas["plata"] + hash_medallas["oro"]
+ if int(total_medallas) >= 7 and int(hash_medallas["oro"]) > 0:
+ pass
+ else:
+ self.__audio.play_voice_sound("club","bloqueo_acceso_piso_4")
+ else:
+ self.__audio.play_voice_sound("club","no habitacion sel")
+ elif accion == IZQUIERDA:
+ hab_izq = self.__usuario.get_current_room().get_left_room()
+ if hab_izq != "":
+ self.__navegacion_manager.select_room(hab_izq,accion)
+ else:
+ print "Desde la habitacion actual no se puede acceder a una habitacion a la izquierda"
+ elif accion == DERECHA:
+ hab_der = self.__usuario.get_current_room().get_right_room()
+ if hab_der != "":
+ self.__navegacion_manager.select_room(hab_der, accion)
+ else:
+ print "Desde la habitacion actual no se puede acceder a una habitacion a la derecha"
+ elif accion == ARRIBA:
+ self.__navegacion_manager.select_elevator(ARRIBA)
+ elif accion == ABAJO:
+ self.__navegacion_manager.select_elevator(ABAJO)
+ elif accion == MAS_INFO:
+ self.__navegacion_manager.more_info()
+ elif accion == SELECCION:
+ self.__navegacion_manager.selection_more_info()
+ elif accion == ATRAS:
+ self.__navegacion_manager.leave_room()
+ self.change_context(NAVE)
+ else:
+ #Que pasa si presiono una tecla que no tenga nada que ver con el contexto
+ pass
+
+ def _share_join_activity_cb(self, activity_list):
+ actividades_compartidas = activity_list
+ bundle_club_othello = olpcgames.ACTIVITY.get_bundle_id()
+ co_compartido = False
+ self.__obj_actividad_compartida = ""
+ for self.__obj_actividad_compartida in actividades_compartidas:
+ if bundle_club_othello == self.__obj_actividad_compartida.get_property("type"):
+ co_compartido = True
+ break
+ if not co_compartido:
+ #Comparto
+ try:
+ olpcgames.ACTIVITY.share()
+ self.__actividad_compartida = True
+ self.__malla.set_state(ON)
+ self.change_context(PLAY)
+ log.info('Comparti Club de Othello en el vecindario, esperando que alguien se una para jugar...')
+ except Exception, e:
+ log.debug(str(e) +', al intentar compartir una actividad compartida (Engine Class).')
+ self.__audio.play_voice_sound("club","error de conexion")
+ self.__audio.play_voice_sound("club","saliendo salon desafios")
+ self.__navegacion_manager.leave_room()
+ else:
+ #Me uno
+ try:
+ olpcgames.ACTIVITY.shared_activity = self.__obj_actividad_compartida
+ olpcgames.ACTIVITY._shared_activity = self.__obj_actividad_compartida
+ olpcgames.ACTIVITY._join_id = olpcgames.ACTIVITY.shared_activity.connect("joined", self.__malla.joined_cb)
+ olpcgames.ACTIVITY.shared_activity.join()
+ self.__actividad_compartida = True
+ self.__malla.set_state(ON)
+ self.change_context(LIST)
+ log.info('Me uni a una actividad Club de Othello compartida en el vecindario, listo para jugar...')
+ except Exception, e:
+ log.debug(str(e) +', al intentar unirme a una actividad compartida (Engine Class).')
+ self.__audio.play_voice_sound("club","error de conexion")
+ self.__audio.play_voice_sound("club","saliendo salon desafios")
+ self.__navegacion_manager.leave_room()
+
+ def __close_dialog_action(self):
+ #Cerrar la accion abierta anteriormente
+ if self.__accion["parametros"] != "":
+ nuevo_contexto = self.__accion["metodo"](self.__accion["parametros"])
+ else:
+ nuevo_contexto = self.__accion["metodo"]()
+ #self.__accion.clear()
+ return nuevo_contexto
+
+ def __there_is_action_to_close(self):
+ if self.__accion != {}:
+ return True
+ else:
+ return False
+
+ def __make_dialog_action(self, accion):
+ if accion == ATRAS:
+ self.__dialogo_manager.repeat_dialogue()
+ elif accion == ATAJO_PASAR_TUTORIAL:
+ if self.__usuario.enable_tutorials_shorcuts():
+ if self.__dialogo_manager.get_dialogue_name().find("tutorial") != -1 or self.__dialogo_manager.get_dialogue_name().find("bienvenida") != -1:
+ if self.__there_is_action_to_close():
+ nuevo_contexto = self.__close_dialog_action()
+ #Si el nuevo contexto es igual a vacio significa que no se debe cambiar el contexto porque al cambiar el contexto
+ #se alteran la habitacion/deshabilitacion de las teclas
+ if not nuevo_contexto == "":
+ self.change_context(nuevo_contexto)
+ else:
+ self.__dialogo_manager.manage_dialogue(accion)
+ if self.__dialogo_manager.ended_dialogue():
+ if self.__there_is_action_to_close():
+ nuevo_contexto = self.__close_dialog_action()
+ #Si el nuevo contexto es igual a vacio significa que no se debe cambiar el contexto porque al cambiar el contexto
+ #se alteran la habitacion/deshabilitacion de las teclas
+ if not nuevo_contexto == "":
+ self.change_context(nuevo_contexto)
+
+ def __make_play_action(self, accion):
+ if accion == CONTINUAR:
+ if not self.juego.game_ended():
+ if self.__actividad_compartida:
+ if self.__juego_mesh:
+ hizo_jugada = self.juego.play(audio=self.__audio,marcador=self.__video.marcador,ventana=self.__video.ventana)
+ if hizo_jugada:
+ self.__malla.send_end_move_message()
+ else:
+ log.warn("No puede realizar aun una jugada!. Debe esperar a que el otro jugador finalize su jugada")
+ else:
+ hizo_jugada = self.juego.play(audio=self.__audio,marcador=self.__video.marcador,ventana=self.__video.ventana)
+ else:
+ if self.__usuario.get_current_room().get_name() == "habitacion pedro madera" or \
+ self.__usuario.get_current_room().get_name() == "habitacion sofia dulce" or \
+ self.__usuario.get_current_room().get_name() == "habitacion presidente":
+ per_duenho = self.__usuario.get_current_room().get_owner()
+ nuevo_contexto = per_duenho.close_game(self)
+ self.change_context(nuevo_contexto)
+ else:
+ #Es el salon de encuentros
+ self.__video.dissapear_game_elements()
+ self.change_context(LIST)
+ self.__audio.play_voice_sound("club","seleccione opcion")
+ 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.__malla.set_state(ON)
+ elif accion == IZQUIERDA or accion == DERECHA or accion == ARRIBA or accion == ABAJO:
+ self.__video.board.do_move(accion, self.__audio,self.juego.get_game_log_file())
+ elif accion == SELECCION:
+ self.__video.board.play_box_info_sound(self.__audio)
+ elif accion == MAS_INFO:
+ self.__video.board.play_possible_moves_sound(self.__audio)
+ elif accion == CONTAR_FICHAS:
+ self.__video.board.play_count_pieces_sound(self.__audio,self.juego)
+ elif accion == ATRAS:
+ self.__video.dissapear_game_elements()
+ if self.__actividad_compartida:
+ self.__actividad_compartida = False
+ self.__malla.remove_me()
+ self.__malla.set_state(OFF)
+ self.__navegacion_manager.leave_room()
+ self.change_context(NAVE)
+ else:
+ if self.__usuario.enable_games_shorcuts():
+ if accion == ATAJO_GANAR_JUEGO:
+ self.juego.shorcut_win_game()
+ elif accion == ATAJO_PERDER_JUEGO:
+ self.juego.shorcut_lose_game()
+ elif accion == ATAJO_EMPATAR_JUEGO:
+ self.juego.shorcut_draw_game()
+ per_duenho = self.__usuario.get_current_room().get_owner()
+ nuevo_contexto = per_duenho.close_game(self)
+ self.change_context(nuevo_contexto)
+
+ def __make_list_action(self, accion):
+ if accion == CONTINUAR:
+ if not self.__usuario.get_current_room().get_name() == "secretaria":
+ self.__video.selection_list.read_option(self.__audio)
+ while not self.__audio.silence_channel():
+ self.__video.selection_list.blink_option()
+ opcion = self.__video.selection_list.get_selected_option()
+ self.__video.remove_selection_list()
+ if opcion["id"] == "salir" or opcion["id"] == "salir_pasillo":
+ if not self.__actividad_compartida:
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.dissapear_game_elements()
+ else:
+ if not self.__obj_actividad_compartida == "":
+ self.__malla.remove_me()
+ else:
+ self.__malla.remove_me()
+ self.__malla.set_state(OFF)
+ self.__navegacion_manager.leave_room()
+ self.change_context(NAVE)
+ else:
+ if not self.__actividad_compartida:
+ per_duenho = self.__usuario.get_current_room().get_owner()
+ per_duenho.init_list_action(opcion["id"],self)
+ self.__accion = {"metodo":per_duenho.close_action,"parametros":(self)}
+ else:
+ self.__malla.init_list_action(opcion["id"])
+ elif accion == ARRIBA or accion == ABAJO:
+ self.__video.selection_list.change_selection_options(accion,self.__audio)
+ elif accion == SELECCION:
+ self.__video.selection_list.option_more_info(self.__audio)
+ elif accion == ATRAS:
+ if self.__usuario.get_current_room().get_name() == "salon de encuentros":
+ if not self.__obj_actividad_compartida == "":
+ #log.debug('Voy a desconectarme de una actividad a la cual me uni')
+ self.__malla.remove_me()
+ else:
+ #log.debug('Voy a descompartir una actividad que habia compartido en el vecindario')
+ self.__malla.remove_me()
+ self.__malla.set_state(OFF)
+ else:
+ self.__video.text_box.disappear(self.__video.ventana)
+ self.__video.remove_selection_list()
+ self.__navegacion_manager.leave_room()
+ self.change_context(NAVE)
+ else:
+ pass
+
diff --git a/src/main/engine.pyc b/src/main/engine.pyc Binary files differnew file mode 100644 index 0000000..d334ff9 --- /dev/null +++ b/src/main/engine.pyc diff --git a/src/main/event_manager.py b/src/main/event_manager.py new file mode 100755 index 0000000..9311d04 --- /dev/null +++ b/src/main/event_manager.py @@ -0,0 +1,46 @@ +import pygame
+from olpcgames import pausescreen +
+class EventManager:
+ def __init__(self):
+ self.__id_objeto = 0
+ self.__objetos = {}
+ self.__escuchar_eventos = True
+
+ def subscribe(self, objeto):
+ objeto.set_id = self.__id_objeto
+ self.__objetos[self.__id_objeto] = objeto
+ self.__id_objeto += 1
+
+ def unsubscribe(self, objeto):
+ for o in self.__objetos.items():
+ if o[1].get_id() == objeto.get_id():
+ del self.__objetos[o[0]]
+
+ def __warn(self, event):
+ for o in self.__objetos.items():
+ o[1].new_event(event)
+
+ def listen_event(self, valor):
+ self.__escuchar_eventos = valor
+
+ def run(self):
+ clock = pygame.time.Clock()
+ while True: + milliseconds = 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(sleep_timeout=60) + # Now the main event-processing loop + if events:
+ for event in events:
+ self.__warn(event) + pygame.display.update() + + #while True:
+ #for event in pygame.event.get():
+ #while self.__escuchar_eventos:
+ #event = pygame.event.wait()
+ #self.__warn(event)
+ #Refresco la pantalla
+ #pygame.display.update()
+ diff --git a/src/main/event_manager.pyc b/src/main/event_manager.pyc Binary files differnew file mode 100644 index 0000000..4800195 --- /dev/null +++ b/src/main/event_manager.pyc diff --git a/src/main/keys.py b/src/main/keys.py new file mode 100755 index 0000000..2bcbdc0 --- /dev/null +++ b/src/main/keys.py @@ -0,0 +1,142 @@ +import os, logging
+from _xml.parser import Parser
+from main.constants import TECLA_DESCONOCIDA
+
+log = logging.getLogger( 'src.main.keys' )
+log.setLevel( logging.DEBUG )
+
+class Key:
+ def __init__(self, nombre="", id=-1, habilitada=False, constante=""):
+ self.__nombre = nombre
+ self.__id = id
+ self.__habilitada = habilitada
+ self.__constante = int(constante)
+
+ def get_name(self):
+ return self.__nombre
+
+ def set_name(self, nombre):
+ self.__nombre = nombre
+
+ def get_id(self):
+ return self.__id
+
+ def set_id(self, id):
+ self.__id = id
+
+ def enable(self):
+ return self.__habilitada
+
+ def set_enable(self, habilitada):
+ self.__habilitada = habilitada
+
+ def set_constant(self, constante):
+ self.__constante = constante
+
+ def get_constant(self):
+ return self.__constante
+
+class Keys:
+ def __init__(self, main_path=""):
+ self.__keys = []
+ self.__main_path = main_path
+ try:
+ xml_info = self.__get_xml_info(os.path.abspath(self.__main_path+"/data/keys.xml"),"configuration")
+ self.__init_keys(xml_info)
+ except Exception, e:
+ print e
+ raise Exception("Problemas al inicializar las teclas (Keys Class)")
+
+
+ def __get_xml_info(self,archivo,etiqueta):
+ f = open(archivo)
+ p = Parser()
+ elementos = p.find_child_element(etiqueta,f)
+ p.close()
+ f.close()
+ return elementos
+
+ def __init_keys(self, config_info):
+ for k in config_info:
+ if k.get_name() == 'key':
+ self.__keys.append(Key(nombre=k.get_attribute('name'),id=k.get_attribute('id'),constante=k.get_attribute('constant')))
+
+ def __get_key_by_id(self, id):
+ for k in self.__keys:
+ if k.get_id() == id:
+ return k
+
+ def get_key_by_constant(self, constant):
+ for k in self.__keys:
+ if k.get_constant() == constant:
+ return k
+
+ def __get_key_by_name(self, nombre):
+ for k in self.__keys:
+ if k.get_name() == nombre:
+ return k
+
+ def set_current_state(self, estado_actual):
+ for k in estado_actual.get_keys_state().items():
+ id = k[0]
+ key = self.__get_key_by_id(id)
+ key.set_enable(k[1]['habilitada'])
+
+ def enable_keys(self, contexto):
+ etiqueta = 'context_' + str(contexto)
+ xml_info = self.__get_xml_info(os.path.abspath(self.__main_path+"/data/keys.xml"),etiqueta)
+ for k in xml_info:
+ key = self.__get_key_by_id(k.get_attribute('id'))
+ if k.get_attribute('enable') == 'yes':
+ key.set_enable(True)
+ else:
+ key.set_enable(False)
+
+ def enable_key(self, key_constant):
+ key = self.get_key_by_constant(key_constant)
+ key.set_enable(True)
+
+ def enable_move_keys(self):
+ tecla = self.__get_key_by_name("izquierda")
+ tecla.set_enable(True)
+ tecla = self.__get_key_by_name("derecha")
+ tecla.set_enable(True)
+ tecla = self.__get_key_by_name("arriba")
+ tecla.set_enable(True)
+ tecla = self.__get_key_by_name("abajo")
+ tecla.set_enable(True)
+ tecla = self.__get_key_by_name("seleccion")
+ tecla.set_enable(True)
+
+ #def enable_keys(self, keys):
+ # pass
+
+ def disable_keys(self, teclas, contexto):
+ for t in teclas:
+ self.disable_key(t, contexto)
+
+ def disable_key(self, key_constant, contexto):
+ etiqueta = 'context_' + str(contexto)
+ xml_info = self.__get_xml_info(os.path.abspath(self.__main_path+"/data/keys.xml"),etiqueta)
+ for k in xml_info:
+ key = self.__get_key_by_id(k.get_attribute('id'))
+ if key.get_constant() == key_constant:
+ if k.get_attribute('enable') == 'no':
+ key.set_enable(False)
+
+ #key como constante
+ def is_enable(self, key_constant):
+ for k in self.__keys:
+ if k.get_constant() == key_constant:
+ return k.enable()
+ if key_constant == TECLA_DESCONOCIDA:
+ return False
+
+ def __str__(self):
+ cad = "\n"
+ for k in self.__keys:
+ if k.enable():
+ cad += "Tecla: " + str(k.get_name()) + " habilitada\n"
+ else:
+ cad += "Tecla: " + str(k.get_name()) + " deshabilitada\n"
+ return cad
diff --git a/src/main/keys.pyc b/src/main/keys.pyc Binary files differnew file mode 100644 index 0000000..4018470 --- /dev/null +++ b/src/main/keys.pyc diff --git a/src/main/user.py b/src/main/user.py new file mode 100755 index 0000000..0009892 --- /dev/null +++ b/src/main/user.py @@ -0,0 +1,309 @@ +from constants import NULL, ENTR, WELCOME, TUTORIAL1, F_MEET_BLOCK_VOCALS, MEET, BRONZE
+from hyperhistory.state import State
+import os, logging
+from _xml.parser import Parser
+
+log = logging.getLogger( 'src.main.user' )
+log.setLevel( logging.DEBUG )
+
+class User:
+ def __init__(self, main_path="", write_path="", lugar_inicial = ""):
+ self.__write_path = write_path
+ self.__main_path = main_path
+ self.__nombre = ""
+ self.__open_user_data_file()
+ self.__pieza_actual = lugar_inicial
+# self.set_state()
+
+ def __open_user_data_file(self):
+ try:
+ self.__user_data_file = open(os.path.abspath(self.__write_path + "/data/user_data.xml"),'r')
+ self.__load_user_data()
+ self.__user_data_file.close()
+ except:
+ self.__create_user_data()
+
+ def __create_user_data(self):
+ self.__nivel_de_habilidad = NULL
+ self.__init_character_relations()
+ self.__load_config_settings()
+ self.__init_medals()
+ self.__init_trophies()
+ self.__init_challenge_medals()
+
+ def __load_user_data(self):
+ parser = Parser()
+ elementos_usuario = parser.find_child_element("user_data",self.__user_data_file)
+ character_relations = {}
+ for e in elementos_usuario:
+ if e.get_name() == "state":
+ self.set_state(e.get_attribute('name'))
+ elif e.get_name() == "skill_level":
+ self.__nivel_de_habilidad = int(e.get_attribute('constant'))
+ elif e.get_name() == "character_relation":
+ character_relations[e.get_attribute('name')] = int(e.get_attribute('relation_constant'))
+ elif e.get_name() == "medals":
+ self.__init_medals(e.get_attributes())
+ elif e.get_name() == "trophies":
+ self.__init_trophies(e.get_attributes())
+ elif e.get_name() == "challenges_medals":
+ self.__init_challenge_medals(e.get_attributes())
+ self.__init_character_relations(character_relations)
+ self.__load_config_settings(nuevo_usuario=False)
+ parser.close()
+
+ def __init_trophies(self, trofeos={}):
+ self.__trofeos = {}
+ if trofeos != {}:
+ self.__trofeos["madera"] = int(trofeos["wood"])
+ self.__trofeos["marfil"] = int(trofeos["ivory"])
+ self.__trofeos["oro"] = int(trofeos["gold"])
+ else:
+ self.__trofeos = {"madera":0, "marfil":0, "oro":0}
+
+ def __init_medals(self, medallas={}):
+ self.__medallas = {}
+ if medallas != {}:
+ self.__medallas["bronce"] = int(medallas["bronze"])
+ self.__medallas["plata"] = int(medallas["silver"])
+ self.__medallas["oro"] = int(medallas["gold"])
+ else:
+ self.__medallas = {"bronce":0, "plata":0, "oro":0}
+
+ def __init_challenge_medals(self, medallas_desafios={}):
+ self.__medallas_desafios = {}
+ if medallas_desafios != {}:
+ self.__medallas_desafios["a1"] = int(medallas_desafios["a1"]) if medallas_desafios["a1"] != "" else medallas_desafios["a1"]
+ self.__medallas_desafios["a2"] = int(medallas_desafios["a2"]) if medallas_desafios["a2"] != "" else medallas_desafios["a2"]
+ self.__medallas_desafios["a3"] = int(medallas_desafios["a3"]) if medallas_desafios["a3"] != "" else medallas_desafios["a3"]
+ self.__medallas_desafios["a4"] = int(medallas_desafios["a4"]) if medallas_desafios["a4"] != "" else medallas_desafios["a4"]
+ self.__medallas_desafios["a5"] = int(medallas_desafios["a5"]) if medallas_desafios["a5"] != "" else medallas_desafios["a5"]
+ self.__medallas_desafios["b1"] = int(medallas_desafios["b1"]) if medallas_desafios["b1"] != "" else medallas_desafios["b1"]
+ self.__medallas_desafios["b2"] = int(medallas_desafios["b2"]) if medallas_desafios["b2"] != "" else medallas_desafios["b2"]
+ self.__medallas_desafios["b3"] = int(medallas_desafios["b3"]) if medallas_desafios["b3"] != "" else medallas_desafios["b3"]
+ self.__medallas_desafios["b4"] = int(medallas_desafios["b4"]) if medallas_desafios["b4"] != "" else medallas_desafios["b4"]
+ self.__medallas_desafios["b5"] = int(medallas_desafios["b5"]) if medallas_desafios["b5"] != "" else medallas_desafios["b5"]
+ self.__medallas_desafios["c1"] = int(medallas_desafios["c1"]) if medallas_desafios["c1"] != "" else medallas_desafios["c1"]
+ self.__medallas_desafios["c2"] = int(medallas_desafios["c2"]) if medallas_desafios["c2"] != "" else medallas_desafios["c2"]
+ self.__medallas_desafios["c3"] = int(medallas_desafios["c3"]) if medallas_desafios["c3"] != "" else medallas_desafios["c3"]
+ self.__medallas_desafios["c4"] = int(medallas_desafios["c4"]) if medallas_desafios["c4"] != "" else medallas_desafios["c4"]
+ self.__medallas_desafios["c5"] = int(medallas_desafios["c5"]) if medallas_desafios["c5"] != "" else medallas_desafios["c5"]
+ else:
+ self.__medallas_desafios = {"a1":BRONZE,"a2":BRONZE,"a3":BRONZE,"a4":BRONZE,"a5":"","b1":BRONZE,"b2":"","b3":"","b4":"","b5":"","c1":"","c2":"","c3":"","c4":"","c5":""}
+
+
+ def __load_config_settings(self, nuevo_usuario=True):
+ settings_file = open(os.path.abspath(self.__main_path + "/data/config_settings.xml"))
+ parser = Parser()
+ elementos_configuracion = parser.find_child_element("configuration_settings",settings_file)
+ for e in elementos_configuracion:
+ if e.get_name() == "dialogues":
+ if e.get_attribute('interrupt') == 'yes':
+ self.__interrumpir_dialogos = True
+ else:
+ self.__interrumpir_dialogos = False
+ elif e.get_name() == "sounds":
+ if e.get_attribute('interrupt') == 'yes':
+ self.__interrumpir_sonidos_entre_turnos = True
+ else:
+ self.__interrumpir_sonidos_entre_turnos = False
+ elif e.get_name() == "initial_state" and nuevo_usuario:
+ self.set_state(e.get_attribute('name'))
+ elif e.get_name() == "initial_context":
+ self.__contexto = e.get_attribute('constant')
+ elif e.get_name() == "shorcuts":
+ if e.get_attribute('games') == 'yes':
+ self.__atajos_juegos = True
+ else:
+ self.__atajos_juegos = False
+ if e.get_attribute('tutorials') == 'yes':
+ self.__atajos_tutoriales = True
+ else:
+ self.__atajos_tutoriales = False
+ settings_file.close()
+ parser.close()
+
+ def save_user_data(self):
+ self.__user_data_file = open(os.path.abspath(self.__write_path + "/data/user_data.xml"),'w')
+ self.__user_data_file.write('<?xml version="1.0"?>\n')
+ self.__user_data_file.write('<user_data>\n')
+ self.__user_data_file.write('\t<state name="'+self.__estado.get_name()+'"></state>\n')
+ self.__user_data_file.write('\t<skill_level constant="'+str(self.__nivel_de_habilidad)+'"></skill_level>\n')
+ self.__user_data_file.write('\t<character_relation name="pablo gris" relation_constant="'+str(self.__character_relations['pablo gris'])+'"></character_relation>\n')
+ self.__user_data_file.write('\t<character_relation name="pedro madera" relation_constant="'+str(self.__character_relations['pedro madera'])+'"></character_relation>\n')
+ self.__user_data_file.write('\t<character_relation name="don cano" relation_constant="'+str(self.__character_relations['don cano'])+'"></character_relation>\n')
+ self.__user_data_file.write('\t<character_relation name="sofia dulce" relation_constant="'+str(self.__character_relations['sofia dulce'])+'"></character_relation>\n')
+ self.__user_data_file.write('\t<character_relation name="protasio" relation_constant="'+str(self.__character_relations['protasio'])+'"></character_relation>\n')
+ self.__user_data_file.write('\t<medals bronze="'+str(self.__medallas['bronce'])+'" silver="'+str(self.__medallas['plata'])+'" gold="'+str(self.__medallas['oro'])+'"></medals>\n')
+ self.__user_data_file.write('\t<trophies wood="'+str(self.__trofeos['madera'])+'" ivory="'+str(self.__trofeos['marfil'])+'" gold="'+str(self.__trofeos['oro'])+'"></trophies>\n')
+ self.__user_data_file.write('\t<challenges_medals a1="'+str(self.__medallas_desafios['a1'])+'" a2="'+str(self.__medallas_desafios['a2'])+'" a3="'+str(self.__medallas_desafios['a3'])+ \
+ '" a4="'+str(self.__medallas_desafios['a4'])+'" a5="'+str(self.__medallas_desafios['a5'])+'" b1="'+str(self.__medallas_desafios['b1'])+ \
+ '" b2="'+str(self.__medallas_desafios['b2'])+'" b3="'+str(self.__medallas_desafios['b3'])+'" b4="'+str(self.__medallas_desafios['b4'])+ \
+ '" b5="'+str(self.__medallas_desafios['b5'])+'" c1="'+str(self.__medallas_desafios['c1'])+'" c2="'+str(self.__medallas_desafios['c2'])+ \
+ '" c3="'+str(self.__medallas_desafios['c3'])+'" c4="'+str(self.__medallas_desafios['c4'])+'" c5="'+str(self.__medallas_desafios['c5'])+ '"></challenges_medals>\n')
+ self.__user_data_file.write('</user_data>')
+ self.__user_data_file.close()
+
+ def get_name(self):
+ return self.__nombre
+
+ def get_current_room(self):
+ return self.__pieza_actual
+
+ def set_current_room(self, nueva_pieza):
+ self.__pieza_actual = nueva_pieza
+
+ def get_skill_level(self):
+ return self.__nivel_de_habilidad
+
+ def set_skill_level(self, nuevo_nivel):
+ self.__nivel_de_habilidad = nuevo_nivel
+
+ def __init_character_relations(self, relaciones={}):
+ self.__character_relations = {}
+ if relaciones == {}:
+ self.__character_relations["pablo gris"] = NULL #TUTORIAL1
+ self.__character_relations["pedro madera"] = NULL #F_MEET_BLOCK_VOCALS
+ self.__character_relations["sofia dulce"] = NULL
+ self.__character_relations["don cano"] = NULL
+ self.__character_relations["protasio"] = NULL
+ else:
+ self.__character_relations["pablo gris"] = relaciones["pablo gris"]
+ self.__character_relations["pedro madera"] = relaciones["pedro madera"]
+ self.__character_relations["sofia dulce"] = relaciones["sofia dulce"]
+ self.__character_relations["don cano"] = relaciones["don cano"]
+ self.__character_relations["protasio"] = relaciones["protasio"]
+
+ def set_character_relation(self, nombre_personaje, relacion):
+ self.__character_relations[nombre_personaje] = relacion
+
+ def get_character_relation(self, nombre_personaje):
+ return self.__character_relations[nombre_personaje]
+
+ def get_context(self):
+ return self.__contexto
+
+ def set_context(self, valor):
+ self.__contexto = valor
+
+ def set_state(self, estado="state2"):
+ self.__estado = State()
+ self.__estado.save_state(estado,self.__main_path)
+
+ def get_state(self):
+ return self.__estado
+
+ def set_player(self, jugador):
+ self.__jugador = jugador
+
+ def get_player(self):
+ return self.__jugador
+
+ def interrupt_dialogue(self):
+ return self.__interrumpir_dialogos
+
+ def interrupt_sounds(self):
+ return self.__interrumpir_sonidos_entre_turnos
+
+ def enable_games_shorcuts(self):
+ return self.__atajos_juegos
+
+ def enable_tutorials_shorcuts(self):
+ return self.__atajos_tutoriales
+
+ def get_challenge_medals(self):
+ return self.__medallas_desafios
+
+ def get_challenge_medal(self, desafio):
+ return self.__medallas_desafios[desafio]
+
+ def save_challenge_medal(self, desafio, medalla):
+ self.__medallas_desafios[desafio] = medalla
+
+ def save_medal(self, tipo):
+ self.__medallas[tipo] += 1
+
+ def delete_medal(self, tipo):
+ if self.__medallas[tipo] > 0:
+ self.__medallas[tipo] -= 1
+ else:
+ log.debug("No se puede borrar la medalla, cantidad igual a cero. (Class: User, Method: delete_medal)")
+
+ def save_trophie(self, tipo):
+ self.__trofeos[tipo] += 1
+
+ def delete_trophie(self, tipo):
+ if self.__trofeos[tipo] > 0:
+ self.__trofeos[tipo] -= 1
+ else:
+ log.debug("No se puede borrar el trofeo, cantidad igual a cero. (Class: User, Method: delete_trophie)")
+
+ def get_medal(self, tipo):
+ return self.__medallas[tipo]
+
+ def get_medals(self):
+ return self.__medallas
+
+ def get_game_progress(self):
+ nro_estado = int(self.__estado.get_name().split("state")[1])
+ progreso_real = (100*nro_estado)/self.__estado.get_max_estados()
+ modulo_progreso = progreso_real % 5
+ if modulo_progreso != 0:
+ intervalo = self.__get_interval(progreso_real)
+ nro1 = abs(intervalo[0]-progreso_real)
+ nro2 = abs(intervalo[1]-progreso_real)
+ progreso_multiplo_5 = 0
+ if nro1 == modulo_progreso:
+ progreso_multiplo_5 = intervalo[0]
+ elif nro2 == modulo_progreso:
+ progreso_multiplo_5 = intervalo[1]
+ else:
+ log.debug("El nro. de progreso no corresponde al intervalo. (User Class)")
+ return progreso_multiplo_5
+ else:
+ return progreso_real
+
+ #Retorna el intervalo multiplo de 5 en el cual se encuentra contenido el numero dado
+ def __get_interval(self, numero):
+ if numero > 0 and numero <= 5:
+ return (1,5)
+ elif numero > 5 and numero <= 10:
+ return (5,10)
+ elif numero > 10 and numero <= 15:
+ return (10,15)
+ elif numero > 15 and numero <= 20:
+ return (15,20)
+ elif numero > 20 and numero <= 25:
+ return (20,25)
+ elif numero > 25 and numero <= 30:
+ return (25,30)
+ elif numero > 30 and numero <= 35:
+ return (30,35)
+ elif numero > 35 and numero <= 40:
+ return (35,40)
+ elif numero > 40 and numero <= 45:
+ return (40,45)
+ elif numero > 45 and numero <= 50:
+ return (45,50)
+ elif numero > 50 and numero <= 55:
+ return (50,55)
+ elif numero > 55 and numero <= 60:
+ return (55,60)
+ elif numero > 60 and numero <= 65:
+ return (60,65)
+ elif numero > 65 and numero <= 70:
+ return (65,70)
+ elif numero > 70 and numero <= 75:
+ return (70,75)
+ elif numero > 75 and numero <= 80:
+ return (75,80)
+ elif numero > 80 and numero <= 85:
+ return (80,85)
+ elif numero > 85 and numero <= 90:
+ return (85,90)
+ elif numero > 90 and numero <= 95:
+ return (90,95)
+ elif numero > 95 and numero <= 100:
+ return (95,100)
+ else:
+ log.debug("No se encuentra el intervalo del numero de estado pasado. (User Class)")
\ No newline at end of file diff --git a/src/main/user.pyc b/src/main/user.pyc Binary files differnew file mode 100644 index 0000000..fe7ce52 --- /dev/null +++ b/src/main/user.pyc diff --git a/src/othello/__init__.py b/src/othello/__init__.py new file mode 100755 index 0000000..cb42204 --- /dev/null +++ b/src/othello/__init__.py @@ -0,0 +1,14 @@ +#from game import Game +#from player import * +#from board import NEGRO, BLANCO +# +# +#__all__ = ["ai", "board", "game", "gui", "utils", "player", "referee"] +# +#if __name__ == "__main__": +# #Creo los jugadores que van a competir en el juego +# jugador1 = Player(BLANCO,HUMANO) +# jugador2 = Player(NEGRO,PC) +# juego = Game(jugador1,jugador2) +# juego.set_turn(jugador1) +# juego.play() diff --git a/src/othello/__init__.pyc b/src/othello/__init__.pyc Binary files differnew file mode 100644 index 0000000..221e9b7 --- /dev/null +++ b/src/othello/__init__.pyc diff --git a/src/othello/ai.py b/src/othello/ai.py new file mode 100755 index 0000000..e4396a9 --- /dev/null +++ b/src/othello/ai.py @@ -0,0 +1,342 @@ +from referee import Referee
+from utils import Coordinate
+from board import *
+import logging
+
+MAS_INFI = 100000
+MEN_INFI = -100000
+MAX = 1
+MIN = -1
+ESTADO_GANADOR = 50000
+ESTADO_PERDEDOR = -50000
+ESTADO_EMPATE = 0
+
+log = logging.getLogger( 'src.othello.ai' )
+log.setLevel( logging.DEBUG )
+
+class State:
+ def __init__(self, tablero, turno=NEGRO, etiqueta=MAX, profundidad=0, cantidad_hnos=0):
+ self.tablero = tablero.copy()
+ self.etiqueta = etiqueta
+ self.profundidad = profundidad
+ self.turno = turno
+ self.cantidad_hnos = cantidad_hnos
+ #Guardo la coordenada para llegar al mejor sucesor de este estado
+ self.mejor_sucesor = Coordinate()
+ #Guardo la accion que dio nacimiento al estado
+ self.iniciador = Coordinate()
+
+class Ai:
+ #NIVELES
+ FACIL = 1
+ MEDIO = 2
+ DIFICIL = 3
+
+ def __init__(self, nivel=1):
+ if nivel == Ai.FACIL:
+ self.__profundidad_maxima = 1
+ self.__frontera_peso = 1 #Cuanto mas fichas tengas en la frontera es peor
+ self.__movilidad_peso = 0 #Cuantas jugadas posible se tiene
+ self.__estabilidad_peso = 0 #Cuantas mas fichas logres estabilizar en la jugada mejor
+ self.__diferencia_cantidad_fichas_peso = 8
+ elif nivel == Ai.MEDIO:
+ self.__profundidad_maxima = 2
+ self.__frontera_peso = 1 #Cuanto mas fichas tengas en la frontera es peor
+ self.__movilidad_peso = 0 #Cuantas jugadas posible se tiene
+ self.__estabilidad_peso = 3 #Cuantas mas fichas logres estabilizar en la jugada mejor
+ self.__diferencia_cantidad_fichas_peso = 1
+ elif nivel == Ai.DIFICIL:
+ self.__profundidad_maxima = 3
+ self.__frontera_peso = 2 #Cuanto mas fichas tengas en la frontera es peor
+ self.__movilidad_peso = 1 #Cuantas jugadas posible se tiene
+ self.__estabilidad_peso = 5 #Cuantas mas fichas logres estabilizar en la jugada mejor
+ self.__diferencia_cantidad_fichas_peso = 4
+ else:
+ raise Exception("Nivel desconocido (Ai Class)")
+ #Guardo la ultima jugada de la PC
+ self.__ultima_jugada = Coordinate(0,0)
+
+ def get_last_move(self):
+ return self.__ultima_jugada
+
+ def play(self, tablero, turno):
+ profundidad_raiz = 0
+ cantidad_hnos_raiz = 0
+ if Referee.is_at_least_one_move(turno, tablero):
+ estado_raiz = State(tablero,turno,MAX,profundidad_raiz,cantidad_hnos_raiz)
+ self.__negamax(estado_raiz, MEN_INFI, MAS_INFI)
+ self.__ultima_jugada.set(estado_raiz.mejor_sucesor)
+ return True
+ else:
+ return False
+
+ def __negamax(self, estado, alpha, beta):
+ if self.__is_goal_state(estado):
+ return self.__goal_state_value(estado)
+ elif self.__is_leaf(estado):
+ l = self.__value(estado)
+ return l
+ else:
+ e = MEN_INFI
+ n_estados = self.__childrens(estado)
+ for nuevo_estado in n_estados:
+ e = -1 * self.__negamax(nuevo_estado, -1*beta, -1*alpha)
+ if beta <= e:
+ return e
+ if alpha < e:
+ alpha = e
+ estado.mejor_sucesor = nuevo_estado.iniciador
+ return e
+
+ def __is_goal_state(self,estado):
+ #Si no existen mas jugadas para ninguno de los colores con el tablero actual entonces el juego termino y estamos en una hoja
+ if not Referee.is_at_least_one_move(estado.turno, estado.tablero):
+ if not Referee.is_at_least_one_move(-1*estado.turno, estado.tablero):
+ return True
+ else:
+ return False
+ else:
+ return False
+
+ def __goal_state_value(self,estado):
+ diferencia_fichas = estado.tablero.get_can_fichas_blancas() - estado.tablero.get_can_fichas_negras()
+ #Ganaron las blancas
+ if diferencia_fichas > 0:
+ if estado.turno == BLANCO:
+ return ESTADO_GANADOR + diferencia_fichas
+ else:
+ return ESTADO_PERDEDOR + diferencia_fichas
+ #Ganaron las negras
+ elif diferencia_fichas < 0:
+ if estado.turno == NEGRO:
+ return ESTADO_GANADOR + diferencia_fichas
+ else:
+ return ESTADO_PERDEDOR + diferencia_fichas
+ #Empate
+ else:
+ return ESTADO_EMPATE
+
+ def __is_leaf(self,estado):
+ #Si la profundidad del nodo actual es mayor (nunca deberia llegar) o igual ya estamos en la hoja del recorrido actual
+ if estado.profundidad >= self.__profundidad_maxima:
+ return True
+ else:
+ if len(Referee.possibles_moves(estado.turno,estado.tablero)) == 0:
+ return True
+ else:
+ return False
+
+ def __childrens(self,estado):
+ n_etiqueta = estado.etiqueta * -1
+ n_profundidad = estado.profundidad + 1
+ n_turno = estado.turno * -1
+ aux_tablero = Board(estado.tablero.get_dimension())
+ aux_tablero.set_casillas(estado.tablero.get_casillas())
+ nuevos_estados = []
+
+ lista_jugadas = Referee.possibles_moves(estado.turno,estado.tablero)
+ can_hijos = len(lista_jugadas)
+ for jugada in lista_jugadas:
+ aux_tablero.set_piece_and_turn_oponent_pieces(jugada,estado.turno)
+ #Creo el nuevo estado
+ n_estado = State(aux_tablero,n_turno,n_etiqueta,n_profundidad,can_hijos)
+ n_estado.iniciador = jugada
+ nuevos_estados.append(n_estado)
+ aux_tablero.set_casillas(estado.tablero.get_casillas())
+
+ return nuevos_estados
+
+ def __value(self,estado):
+ tablero = estado.tablero
+ if estado.turno == BLANCO:
+ fichas_jugador = tablero.get_can_fichas_blancas()
+ fichas_oponente = tablero.get_can_fichas_negras()
+ else:
+ fichas_jugador = tablero.get_can_fichas_negras()
+ fichas_oponente = tablero.get_can_fichas_blancas()
+ movimientos_validos_oponente = estado.cantidad_hnos
+ jugador_frontera = self.__border_pieces(tablero, estado.turno)
+ oponente_frontera = self.__border_pieces(tablero, -1*estado.turno)
+ movimientos_validos = Referee.number_of_successors(estado.turno, tablero)
+ fichas_estables_jugador = self.__stable_pieces(tablero, estado.turno)
+ fichas_estables_oponente = self.__stable_pieces(tablero, -1*estado.turno)
+ dif_can_fichas = fichas_jugador - fichas_oponente
+
+ v = self.__frontera_peso * (oponente_frontera - jugador_frontera) + self.__movilidad_peso * estado.turno * (movimientos_validos - movimientos_validos_oponente) + self.__estabilidad_peso * (fichas_estables_jugador - fichas_estables_oponente) + self.__diferencia_cantidad_fichas_peso * dif_can_fichas
+ return v
+
+ def __border_pieces(self,tablero, color):
+ can_fichas_frontera = 0
+ dim = tablero.get_dimension()
+
+ for i in xrange(0,dim):
+ for j in xrange(0,dim):
+ es_frontera = False
+ if tablero.get_valor_casilla(i,j) == color:
+ aux_coord = Coordinate()
+ for inc_fila in xrange(-1,2):
+ for inc_col in xrange(-1,2):
+ aux_coord.x = i + inc_fila
+ aux_coord.y = j + inc_col
+ if not (inc_fila == 0 and inc_col == 0 and tablero.valid_pos(aux_coord) and tablero.get_valor_casilla(aux_coord.x,aux_coord.y) == VACIO):
+ es_frontera = True
+ inc_fila = 2
+ break
+ if es_frontera:
+ can_fichas_frontera += 1
+
+ return can_fichas_frontera
+
+ #Retorna el numero de fichas estables del color dado.
+ def __stable_pieces(self,tablero, color):
+ can_fichas_estables = 0
+ dim = tablero.get_dimension()
+
+ estables = self.__number_stable_boxes(tablero)
+
+ for i in xrange(0,dim):
+ for j in xrange(0,dim):
+ if tablero.get_valor_casilla(i,j) == color and estables[i][j]:
+ can_fichas_estables += 1
+
+ return can_fichas_estables
+
+ #Retorna una matriz que indica cuales casillas son estables, es decir,
+ #cuales casillas ya no pueden ser volteadas en lo que resta del juego.
+ def __number_stable_boxes(self,tablero):
+ pos = Coordinate()
+ estables = []
+ dim = tablero.get_dimension()
+ for _ in xrange(dim):
+ estables.append([False]*dim)
+
+ cambio_estado = True
+ while (cambio_estado):
+ cambio_estado = False
+ for i in xrange(0,dim):
+ for j in xrange(0,dim):
+ pos.x = i
+ pos.y = j
+ if tablero.get_valor_casilla(i,j) != VACIO and not estables[i][j] and not self.__can_turn(pos, tablero, estables):
+ estables[i][j] = True
+ cambio_estado = True
+
+ return estables
+
+ #Retorna false si la ficha en dicha casilla ya no puede ser volteada en lo que resta del juego.
+ #Una ficha puede ser volteada si hay una casilla vacia a ambos lados o
+ #si hay una casilla vacia a un lado y una ficha inestable o una del contrario al otro lado.
+ def __can_turn(self,casilla,tablero,estables):
+ dim = tablero.get_dimension()
+ #Obtiene el color de la ficha.
+ color_ficha = tablero.get_valor_casilla(casilla.x,casilla.y)
+
+ #Verifica cada eje posible (horizontal, vertical y diagonales)
+ #Se verifica horizontalmente
+ lado_uno_vacio = False
+ lado_uno_inseguro = False
+ lado_dos_vacio = False
+ lado_dos_inseguro = False
+ #Lado izquierdo.
+ j = 0
+ while j < casilla.y and not lado_uno_vacio:
+ if tablero.get_valor_casilla(casilla.x,j) == VACIO:
+ lado_uno_vacio = True
+ elif tablero.get_valor_casilla(casilla.x,j) != color_ficha or not estables[casilla.x][j]:
+ lado_uno_inseguro = True
+ j += 1
+ #Lado derecho.
+ j = casilla.y + 1
+ while j < dim and not lado_dos_vacio:
+ if tablero.get_valor_casilla(casilla.x,j) == VACIO:
+ lado_dos_vacio = True
+ elif tablero.get_valor_casilla(casilla.x,j) != color_ficha or not estables[casilla.x][j]:
+ lado_dos_inseguro = True
+ j += 1
+ if (lado_uno_vacio and lado_dos_vacio) or (lado_uno_vacio and lado_dos_inseguro) or (lado_uno_inseguro and lado_dos_vacio):
+ return True
+
+ #Se verifica verticalmente.
+ lado_uno_vacio = False
+ lado_dos_vacio = False
+ lado_uno_inseguro = False
+ lado_dos_inseguro = False
+ #Hacia arriba.
+ i = 0
+ while i < casilla.x and not lado_uno_vacio:
+ if tablero.get_valor_casilla(i,casilla.y) == VACIO:
+ lado_uno_vacio = True
+ elif tablero.get_valor_casilla(i,casilla.y) != color_ficha or not estables[i][casilla.y]:
+ lado_uno_inseguro = True
+ i += 1
+ #Hacia abajo.
+ i = casilla.x + 1
+ while i < dim and not lado_dos_vacio:
+ if tablero.get_valor_casilla(i,casilla.y) == VACIO:
+ lado_dos_vacio = True
+ elif tablero.get_valor_casilla(i,casilla.y) != color_ficha or not estables[i][casilla.y]:
+ lado_dos_inseguro = True
+ i += 1
+ if (lado_uno_vacio and lado_dos_vacio) or (lado_uno_vacio and lado_dos_inseguro) or (lado_uno_inseguro and lado_dos_vacio):
+ return True
+
+ #Se verifica la diagonal \
+ lado_uno_vacio = False
+ lado_dos_vacio = False
+ lado_uno_inseguro = False
+ lado_dos_inseguro = False
+ #Arriba izquierda.
+ i = casilla.x - 1
+ j = casilla.y - 1
+ while i >= 0 and j >= 0 and not lado_uno_vacio:
+ if tablero.get_valor_casilla(i,j) == VACIO:
+ lado_uno_vacio = True
+ elif tablero.get_valor_casilla(i,j) != color_ficha or not estables[i][j]:
+ lado_uno_inseguro = True
+ i = i - 1
+ j = j - 1
+ #Abajo derecha.
+ i = casilla.x + 1
+ j = casilla.y + 1
+ while i < dim and j < dim and not lado_dos_vacio:
+ if tablero.get_valor_casilla(i,j) == VACIO:
+ lado_dos_vacio = True
+ elif tablero.get_valor_casilla(i,j) != color_ficha or not estables[i][j]:
+ lado_dos_inseguro = True
+ i += 1
+ j += 1
+ if (lado_uno_vacio and lado_dos_vacio) or (lado_uno_vacio and lado_dos_inseguro) or (lado_uno_inseguro and lado_dos_vacio):
+ return True
+
+ #Se verifica la diagonal /
+ lado_uno_vacio = False
+ lado_dos_vacio = False
+ lado_uno_inseguro = False
+ lado_dos_inseguro = False
+ #Arriba derecha.
+ i = casilla.x - 1
+ j = casilla.y + 1
+ while i >= 0 and j < dim and not lado_uno_vacio:
+ if tablero.get_valor_casilla(i,j) == VACIO:
+ lado_uno_vacio = True
+ elif tablero.get_valor_casilla(i,j) != color_ficha or not estables[i][j]:
+ lado_uno_inseguro = True
+ i = i - 1
+ j += 1
+ #Abajo izquierda.
+ i = casilla.x + 1
+ j = casilla.y - 1
+ while i < dim and j >= 0 and not lado_dos_vacio:
+ if tablero.get_valor_casilla(i,j) == VACIO:
+ lado_dos_vacio = True
+ elif tablero.get_valor_casilla(i,j) != color_ficha or not estables[i][j]:
+ lado_dos_inseguro = True
+ i += 1
+ j = j - 1
+ if (lado_uno_vacio and lado_dos_vacio) or (lado_uno_vacio and lado_dos_inseguro) or (lado_uno_inseguro and lado_dos_vacio):
+ return True
+
+ #Todas las direcciones son estables, la casilla es estable.
+ return False
+
+
diff --git a/src/othello/ai.pyc b/src/othello/ai.pyc Binary files differnew file mode 100644 index 0000000..d3e6d6a --- /dev/null +++ b/src/othello/ai.pyc diff --git a/src/othello/board.py b/src/othello/board.py new file mode 100755 index 0000000..f11cc79 --- /dev/null +++ b/src/othello/board.py @@ -0,0 +1,207 @@ +from utils import Coordinate +from referee import Referee +import logging + +#Constantes +VACIO = 0 +BLANCO = 1 +NEGRO = -1 + +log = logging.getLogger( 'src.othello.board' ) +log.setLevel( logging.DEBUG ) + +class Board: + def __init__(self, d=4, v=VACIO): + self.__casilla = [] + self.__dimension = d + #Lleno el tablero de espacios vacios + for _ in xrange(d): + self.__casilla.append([v]*d) + self.__can_fichas_blancas = 0 + self.__can_fichas_negras = 0 + self.__conf_inicial = [] + + def set_up(self, conf_inicial=[]): + if not conf_inicial == []: + for pieza in conf_inicial: + self.__casilla[pieza["posicion"][0]][pieza["posicion"][1]] = pieza["color"] + self.update_pieces_counters() + elif not self.__conf_inicial == []: + for pieza in self.__conf_inicial: + self.__casilla[pieza["posicion"][0]][pieza["posicion"][1]] = pieza["color"] + self.update_pieces_counters() + else: + #Coloco las fichas iniciales + pos_inicial = (self.__dimension/2) - 1 + self.__casilla[pos_inicial][pos_inicial] = BLANCO + self.__casilla[pos_inicial][pos_inicial+1] = NEGRO + self.__casilla[pos_inicial+1][pos_inicial] = NEGRO + self.__casilla[pos_inicial+1][pos_inicial+1] = BLANCO + #Inicializo las variables donde contar la cantidad de fichas negras y blancas en el tablero + self.__can_fichas_blancas = 2 + self.__can_fichas_negras = 2 + + def save_initial_configuration(self, conf_inicial): + self.__conf_inicial = conf_inicial + + def get_dimension(self): + return self.__dimension + + def view(self): + for i in xrange(self.__dimension): + print self.__casilla[i] + + def state(self): + return self.__casilla + + def get_casillas(self): + return self.__casilla + + def set_casillas(self,mat_casillas): + try: + for i in xrange(0,self.__dimension): + for j in xrange(0, self.__dimension): + self.__casilla[i][j] = mat_casillas[i][j] + except: + raise Exception("No se pueden copiar las casillas de un tablero en el otro") + + def copy(self): + n_tablero = Board(self.__dimension) + n_tablero.set_casillas(self.get_casillas()) + n_tablero.__can_fichas_blancas = self.__can_fichas_blancas + n_tablero.__can_fichas_negras = self.__can_fichas_negras + return n_tablero + + def get_can_fichas_blancas(self): + return self.__can_fichas_blancas + + def get_can_fichas_negras(self): + return self.__can_fichas_negras + + def valid_pos(self, pos): + if pos < 0 or pos > self.__dimension-1: + return False + return True + + def get_valor_casilla(self,i,j): + return self.__casilla[i][j] + + def valid_coord(self, coord): + if not self.valid_pos(coord.x) or not self.valid_pos(coord.y): + return False + return True + + """ + Set the piece in the coordinate given as a parameter and turn the opponent pieces + + Params: + - coord: coordinate to set the piece + - color: color of the piece + Return: + - True if it is a valid move, False otherwise + """ + def set_piece(self, coord, color): + if self.valid_coord(coord): + #Verifico que sea una jugada valida + if Referee.is_valid_move(color, coord, self): + self.__casilla[coord.x][coord.y] = color + self.update_pieces_counters() + return True + else: + return False + else: + return False + + def set_piece_and_turn_oponent_pieces(self, coord, color): + self.__casilla[coord.x][coord.y] = color + #Doy vuelta las piezas del oponente + self.turn_pieces(color, coord) + + def turn_pieces(self, color, pos_ini): + pos_fin = Coordinate(pos_ini.x, pos_ini.y) + + for inc_fila in xrange(-1,2): + for inc_col in xrange(-1,2): + pos_fin.x = pos_ini.x + inc_fila + pos_fin.y = pos_ini.y + inc_col + #Verifica que haya al menos una ficha del color opuesto para voltear + if Referee.can_turn(color, pos_ini, inc_fila, inc_col, self): + #Voltear las fichas + while True: + self.__casilla[pos_fin.x][pos_fin.y] = color + pos_fin.x += inc_fila + pos_fin.y += inc_col + if not self.__casilla[pos_fin.x][pos_fin.y] == -color: + break + #Actualizo los contadores de las fichas blancas o negras dependiendo del color + self.update_pieces_counters() + + def turn_pieces2(self, coord, color): + self.__casilla[coord.x][coord.y] = color + #Actualizo los contadores de las fichas blancas o negras dependiendo del color + self.update_pieces_counters() + + def get_lines(self,color,coord): + pos_fin = Coordinate(coord.x,coord.y) + pos_inicial = Coordinate(coord.x,coord.y) + can_fichas_volteables = 0 + vec_lineas = [] + for inc_fila in xrange(-1,2): + for inc_col in xrange(-1,2): + pos_fin.x = pos_inicial.x + inc_fila + pos_fin.y = pos_inicial.y + inc_col + #Verifica que haya al menos una ficha del color opuesto para voltear + if Referee.can_turn(color, pos_inicial, inc_fila, inc_col, self): + hash_linea = {} + vec_casillas = [] + #Contar las fichas volteables en esa linea + while True: + can_fichas_volteables += 1 + vec_casillas.append(Coordinate(pos_fin.x,pos_fin.y)) + pos_fin.x += inc_fila + pos_fin.y += inc_col + if not self.__casilla[pos_fin.x][pos_fin.y] == -color: + break + hash_linea["casilla_inicial"] = pos_inicial + hash_linea["casilla_final"] = Coordinate(pos_fin.x,pos_fin.y) + hash_linea["can_fichas_volteables"] = can_fichas_volteables + hash_linea["casillas_volteables"] = vec_casillas + vec_lineas.append(hash_linea) + can_fichas_volteables = 0 + + return vec_lineas + + def update_pieces_counters(self): + self.__can_fichas_blancas = 0 + self.__can_fichas_negras = 0 + for i in xrange(self.__dimension): + for j in xrange(self.__dimension): + if self.__casilla[i][j] == BLANCO: + self.__can_fichas_blancas += 1 + elif self.__casilla[i][j] == NEGRO: + self.__can_fichas_negras += 1 + + def __update_number_pieces(self,color,i=-1,j=-1): + if i != -1 and j != - 1: + if self.__casilla[i][j] == BLANCO: + self.__can_fichas_blancas -= 1 + elif self.__casilla[i][j] == NEGRO: + self.__can_fichas_negras -= 1 + if color == BLANCO: + self.__can_fichas_blancas += 1 + elif color == NEGRO: + self.__can_fichas_negras += 1 + + def get_number_white_pieces(self): + return self.__can_fichas_blancas + + def get_number_black_pieces(self): + return self.__can_fichas_negras + + #Se utilizan los metodos de abajo solo para el caso en que se quiere terminar + #una partida de forma rapida + def set_can_fichas_blancas(self, valor): + self.__can_fichas_blancas = valor + + def set_can_fichas_negras(self, valor): + self.__can_fichas_negras = valor
\ No newline at end of file diff --git a/src/othello/board.pyc b/src/othello/board.pyc Binary files differnew file mode 100644 index 0000000..c6b2693 --- /dev/null +++ b/src/othello/board.pyc diff --git a/src/othello/game.py b/src/othello/game.py new file mode 100755 index 0000000..d23b7bb --- /dev/null +++ b/src/othello/game.py @@ -0,0 +1,280 @@ +from referee import Referee
+from ai import Ai
+from player import PC, HUMANO, VIRTUAL
+import pygame, os, time, board, logging
+from sugar.activity.activity import get_activity_root
+
+log = logging.getLogger( 'src.othello.game' )
+log.setLevel( logging.DEBUG )
+
+class Game:
+ def __init__(self,tablero,jugador1,jugador2,con_jugadas_posibles=True,nivel=Ai.FACIL, write_path=""):
+ #self.__gui = Gui()
+ #self.__tablero = self.__gui.init_board().get_board()
+ self.__tablero_g = tablero
+ self.__tablero = tablero.get_logical_board()
+ #Iniciliazo la inteligencia para la PC
+ self.__pc = Ai(nivel)
+ #Inicializo un vector de jugadores
+ self.__jugadores = [jugador1,jugador2]
+ self.__ganador = ""
+ self.__nro_turno = 0
+ self.__termino_juego = False
+ self.__juego_mesh = False
+ self.__con_jugadas_posibles = con_jugadas_posibles
+ self.__lista_jugadas_posibles = []
+ if write_path != "":
+ #Imprimo en el log la configuracion del juego que se inicia
+ try:
+ f = open(os.path.abspath(write_path + "/data/game.log"),'r')
+ f.close()
+ self.__log_file = open(os.path.abspath(write_path + "/data/game.log"),'a')
+ print >> self.__log_file, '\nGAME LOG: ' + time.asctime()
+ except:
+ self.__log_file = open(os.path.abspath(write_path + "/data/game.log"),'w')
+ print >> self.__log_file, 'GAME LOG: ' + time.asctime()
+ print >> self.__log_file, 'Tablero: ' + str(self.__tablero.get_dimension()) + 'x' + str(self.__tablero.get_dimension())
+ if jugador1.get_color() == board.BLANCO and jugador1.get_name() == PC:
+ print >> self.__log_file, 'PC: Blanco'
+ print >> self.__log_file, 'Jugador: Negro'
+ elif jugador1.get_name() == HUMANO and jugador2.get_name() == HUMANO:
+ if jugador1.get_color() == board.BLANCO:
+ print >> self.__log_file, 'Jugador1: Blanco'
+ print >> self.__log_file, 'Jugador2: Negro'
+ else:
+ print >> self.__log_file, 'Jugador1: Negro'
+ print >> self.__log_file, 'Jugador2: Blanco'
+ else:
+ print >> self.__log_file, 'PC: Negro'
+ print >> self.__log_file, 'Jugador: Blanco'
+
+ def __del__(self):
+ try:
+ self.__log_file.close()
+ except:
+ log.debug("Problemas al cerrar el descriptor de archivo. (Game Class)")
+
+ def get_game_log_file(self):
+ return self.__log_file
+
+ def get_turn(self):
+ return self.__jugadores[self.__turno]
+
+ def set_turn(self,jugador):
+ if jugador.equal(self.__jugadores[0]):
+ self.__turno = 0
+ elif jugador.equal(self.__jugadores[1]):
+ self.__turno = 1
+ else:
+ raise Exception("No se pudo asignar el turno, el jugador no existe! (Game Class)")
+ self.update_possible_moves()
+
+ def update_possible_moves(self):
+ self.__lista_jugadas_posibles = Referee.possibles_moves(self.get_turn().get_color(),self.__tablero)
+
+ def increase_turn_number(self):
+ self.__nro_turno += 1
+
+ def get_turn_number(self):
+ return self.__nro_turno
+
+ def __next_turn(self):
+ color = self.__jugadores[self.__turno].get_color()
+ #Veo si hay jugada posible para el turno siguiente, es decir si era Blanco para el Negro
+ if Referee.is_at_least_one_move(color*-1, self.__tablero):
+ return True
+ else:
+ return False
+
+ def with_possibles_moves(self):
+ return self.__con_jugadas_posibles
+
+ def change_turn(self):
+ #if self.__next_turn():
+ self.__turno = (self.__turno - 1) * -1
+ self.increase_turn_number()
+ # return True
+ #else:
+ # return False
+
+ def is_over(self):
+ if Referee.is_at_least_one_move(board.BLANCO, self.__tablero):
+ return False
+ elif Referee.is_at_least_one_move(board.NEGRO, self.__tablero):
+ return False
+ else:
+ return True
+
+ def init_next_turn(self):
+ pass
+
+ def __print_log(self, mensaje):
+ try:
+ print >> self.__log_file, mensaje
+ except:
+ print mensaje
+
+ def get_mesh_game(self):
+ return self.__juego_mesh
+
+ def set_mesh_game(self, valor):
+ self.__juego_mesh = valor
+
+ def play(self, coord="", audio="", marcador="", ventana="", extra=""):
+ pc_manual = False
+ if not self.is_over():
+ jugadas_posibles_real = len(self.__lista_jugadas_posibles)
+ self.__ultima_jugada_humano = ""
+ if jugadas_posibles_real > 0:
+ nombre_de_turno = self.get_turn().get_name()
+ color_de_turno = self.get_turn().get_color()
+ if nombre_de_turno == HUMANO or nombre_de_turno == VIRTUAL:
+ if coord == "":
+ coord = self.__tablero_g.get_coord_selected_cell()
+ if color_de_turno == board.BLANCO:
+ pudo_jugar = self.__tablero_g.set_piece(coord,color_de_turno,"blanco",audio, ventana)
+ sonido_voltear = "voltear_negro"
+ else:
+ pudo_jugar = self.__tablero_g.set_piece(coord,color_de_turno,"negro",audio, ventana)
+ sonido_voltear = "voltear_blanco"
+ if pudo_jugar:
+ marcador.render_numbers(self.__tablero,self.get_turn().get_color(),ventana)
+ self.__ultima_jugada_humano = coord
+ self.__print_log("JUGADOR jugo en: " + str(self.__ultima_jugada_humano))
+ if nombre_de_turno == VIRTUAL:
+ self.__tablero_g.set_coord_selected_cell(coord)
+ elif nombre_de_turno == PC:
+ if coord == "":
+ pudo_jugar = self.play_pc()
+ else:
+ pudo_jugar = self.__tablero_g.set_piece(coord,color_de_turno,"blanco",audio, ventana)
+ sonido_voltear = "voltear_negro"
+ pc_manual = True
+ if pudo_jugar:
+ if coord == "":
+ coord = self.get_last_pc_move()
+ self.__tablero_g.set_coord_selected_cell(coord)
+ if not pc_manual:
+ if color_de_turno == board.BLANCO:
+ pudo_jugar = self.__tablero_g.set_piece(coord,color_de_turno,"blanco",audio, ventana)
+ sonido_voltear = "voltear_negro"
+ else:
+ pudo_jugar = self.__tablero_g.set_piece(coord,color_de_turno,"negro",audio, ventana)
+ sonido_voltear = "voltear_blanco"
+ marcador.render_numbers(self.__tablero,self.get_turn().get_color(),ventana)
+ self.__print_log("PC jugo en: " + str(coord))
+ if pudo_jugar:
+ audio.wait_sound_end()
+ self.__tablero_g.do_line_animation(coord, color_de_turno, sonido_voltear, audio, marcador, ventana)
+ else:
+ pudo_jugar = True
+ audio.play_voice_sound("game", "pasa_el_turno")
+ audio.wait_sound_end()
+ #extra = {"play_turn_sound":False}
+ if pudo_jugar:
+ if not self.is_over():
+ self.change_turn()
+ self.update_possible_moves()
+ if self.__con_jugadas_posibles:
+ if extra == "" or (not extra == "" and not "update_possibles_moves" in extra):
+ self.__tablero_g.lista_jugadas = self.__lista_jugadas_posibles
+ if not extra == "":
+ if not "change_score_color" in extra:
+ marcador.render_all(self.__tablero,self.get_turn().get_color(),ventana)
+ if not "play_turn_sound" in extra:
+ audio.play_init_turn_sounds(self.__tablero_g,self)
+ else:
+ audio.play_init_turn_sounds(self.__tablero_g,self)
+ marcador.render_all(self.__tablero,self.get_turn().get_color(),ventana)
+ if self.__con_jugadas_posibles:
+ self.__tablero_g.render_list_possible_moves(ventana)
+ pygame.display.update()
+ else:
+ self.__lista_jugadas_posibles = []
+ if extra == "":
+ self.__termino_juego = True
+ marcador.render_all(self.__tablero,self.get_turn().get_color(),ventana)
+ pygame.display.update()
+ audio.play_end_game_sounds(self.__tablero_g,self)
+ else:
+ audio.play_end_game_sounds(self.__tablero_g,self)
+ self.__termino_juego = True
+
+ return pudo_jugar
+
+ def game_ended(self):
+ return self.__termino_juego
+
+ def play_pc(self):
+ return self.__make_a_move()
+
+ def __make_a_move(self):
+ if self.__pc.play(self.__tablero,self.__jugadores[self.__turno].get_color()):
+ self.__ultima_jugada_pc = self.__pc.get_last_move()
+ return True
+ else:
+ return False
+
+ def get_player_by_color(self, color=board.BLANCO):
+ for jugador in self.__jugadores:
+ if jugador.get_color() == color:
+ return jugador
+
+ def get_player_by_name(self, nombre=PC):
+ for jugador in self.__jugadores:
+ if jugador.get_name() == nombre:
+ return jugador
+
+ def get_final_result(self):
+ if self.__tablero.get_can_fichas_blancas() > self.__tablero.get_can_fichas_negras():
+ return self.get_player_by_color(board.BLANCO)
+ elif self.__tablero.get_can_fichas_blancas() < self.__tablero.get_can_fichas_negras():
+ return self.get_player_by_color(board.NEGRO)
+ else:
+ return ''
+
+ def get_last_pc_move(self):
+ return self.__ultima_jugada_pc
+
+ def get_last_human_move(self):
+ return self.__ultima_jugada_humano
+
+ def get_players(self):
+ """ Retorna un vector con los datos de los jugadores."""
+
+ jugador1 = self.__jugadores[0]
+ jugador2 = self.__jugadores[1]
+ return [{'nombre':jugador1.get_name(),'color':jugador1.get_color()},{'nombre':jugador2.get_name(),'color':jugador2.get_color()}]
+
+ def get_board_configuration(self):
+ """ Retorna un diccionario con la configuracion actual del tablero."""
+
+ return {'dimension':self.__tablero.get_dimension(),'configuracion':self.__tablero.get_casillas()}
+
+ def get_board(self):
+ return self.__tablero
+
+ def shorcut_lose_game(self):
+ jug_humano = self.get_player_by_name(HUMANO)
+ if jug_humano.get_color() == board.BLANCO:
+ self.__tablero.set_can_fichas_blancas(0)
+ self.__tablero.set_can_fichas_negras(1)
+ else:
+ self.__tablero.set_can_fichas_blancas(1)
+ self.__tablero.set_can_fichas_negras(0)
+
+ def shorcut_win_game(self):
+ jug_humano = self.get_player_by_name(HUMANO)
+ if jug_humano.get_color() == board.BLANCO:
+ self.__tablero.set_can_fichas_blancas(1)
+ self.__tablero.set_can_fichas_negras(0)
+ else:
+ self.__tablero.set_can_fichas_blancas(0)
+ self.__tablero.set_can_fichas_negras(1)
+
+ def shorcut_draw_game(self):
+ self.__tablero.set_can_fichas_blancas(1)
+ self.__tablero.set_can_fichas_negras(1)
+
+ def get_list_possible_moves(self):
+ return self.__lista_jugadas_posibles
\ No newline at end of file diff --git a/src/othello/game.pyc b/src/othello/game.pyc Binary files differnew file mode 100644 index 0000000..61b3684 --- /dev/null +++ b/src/othello/game.pyc diff --git a/src/othello/gui.py b/src/othello/gui.py new file mode 100755 index 0000000..9b6d2ef --- /dev/null +++ b/src/othello/gui.py @@ -0,0 +1,840 @@ +import pygame +from pygame.locals import * +from sys import exit +from board import Board, BLANCO, NEGRO, VACIO +from utils import * +from resources.sounds import Sounds +from resources.fonts import Fonts +from resources.images import Images +from referee import Referee +import thread, logging +from player import PC, HUMANO +from input_output.audio import Channel +from main.constants import RESOLUTION1, RESOLUTION2, IZQUIERDA, DERECHA, ARRIBA, ABAJO, STANDART_BOARD_DIMENSION + + +log = logging.getLogger( 'src.othello.gui' ) +log.setLevel( logging.DEBUG ) + +class GraphicBoard: + def __init__(self, tablero_logico="", resolucion=RESOLUTION1): + if tablero_logico == "": + self.__tablero = Board(STANDART_BOARD_DIMENSION) + else: + self.__tablero = tablero_logico + #Inicializo el una matriz donde guardo las coordenadas de pantalla de cada celda + self.__coordenadas = [] + for _ in xrange(self.__tablero.get_dimension()): + self.__coordenadas.append([None]*self.__tablero.get_dimension()) + #Inicializo las variables x e y de las posiciones iniciales del tablero dependiendo de la resolucion + self.__init_constants(resolucion) + #Inicializo las imagenes del tablero + self.__init_images(resolucion) + #Inicializo las fuentes + self.__init_fonts() + #Incializo variables que se utilizan en el algoritmo para la animacion de la celda seleccionada + self.__nro_imagen = 0 + self.__factor = -1 + self.__cambiar_imagen = 0 + #Cargo en un vector las imagenes utilizadas en la animacion de la celda seleccionada + efectos = Images.get_images_file_names(resolucion, "animacion_celda") + self.__imagenes_celda_animada = [pygame.image.load(efectos["chica"]).convert(),pygame.image.load(efectos["mediana"]).convert(),pygame.image.load(efectos["grande"]).convert()] + self.__animated_cell = Coordinate() + #Inicializo un reloj que utilizo para la animacion de la celda + self.__reloj = pygame.time.Clock() + self.lista_jugadas = [] + #Inicializo constantes para identificar las esquinas del tablero + self.__IARRIBA = 2 + self.__IABAJO = 3 + self.__DARRIBA = 4 + self.__DABAJO = 5 + #Inicializo la superficie donde voy a guardar el tablero + self.__init_surface() + self.__do_animation_cell = True + self.__marcador = Score() + self.__render_board() + self.__up_images = [] + + def __init_images(self,resolucion): + na_imagenes_tablero = Images.get_images_file_names(resolucion, "tablero") + na_imagenes_piezas = Images.get_images_file_names(resolucion, "piezas") + #Cargo la imagen de la celda vacia + self.__imagen_celda = pygame.image.load(na_imagenes_tablero["celda_vacia"]).convert() + #Cargo la imagen de las cabeceras del tablero + self.__imagen_tablero_bordev = pygame.image.load(na_imagenes_tablero["borde_vertical"]).convert() + self.__imagen_tablero_bordeh = pygame.image.load(na_imagenes_tablero["borde_horizontal"]).convert() + #Cargo las imagenes de las piezas + self.__imagen_pieza_blanca = pygame.image.load(na_imagenes_piezas["blanca"]).convert_alpha() + self.__imagen_pieza_negra = pygame.image.load(na_imagenes_piezas["negra"]).convert_alpha() + self.__imagen_marca = pygame.image.load(na_imagenes_tablero["marca"]).convert_alpha() + + def __init_constants(self,resolucion): + #Si la resolucion es de 800x600 + if resolucion == RESOLUTION1: + self.__pos_ini = Coordinate(0,0) + #Constantes que se utilizan en la funcion que renderea el tablero + self.__inc_numero_borde_h = Coordinate(25,-5) + self.__inc_numero_borde_vi = Coordinate(8,10) + self.__inc_numero_borde_vd = Coordinate(7,10) + self.__inc_borde_vd = Coordinate(70,0) + self.__mitad_tam_celda = 35 + self.__tam_celda = 70 + if self.__tablero.get_dimension() == 4: + self.__pos_graphic_board = Coordinate(200,0) + else: + self.__pos_graphic_board = Coordinate(155,0) + self.__tam_fuente = 35 + self.__current_cell = Coordinate(0,0) + #Si al resolucion es de 1200x900 + elif resolucion == RESOLUTION2: + self.__pos_ini = Coordinate(0,0) + #Constantes que se utilizan en la funcion que renderea el tablero + self.__inc_numero_borde_h = Coordinate(35,-7) + self.__inc_numero_borde_vi = Coordinate(10,17) + self.__inc_numero_borde_vd = Coordinate(11,17) + self.__inc_borde_vd = Coordinate(105,0) + self.__mitad_tam_celda = 52 + self.__tam_celda = 105 + if self.__tablero.get_dimension() == 4: + self.__pos_graphic_board = Coordinate(340,0) + else: + self.__pos_graphic_board = Coordinate(225,0) + self.__tam_fuente = 50 + self.__current_cell = Coordinate(0,0) + else: + raise Exception("Resolucion desconocida (GraphicBoard Class)") + + def __init_fonts(self): + self.__fuente = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"],self.__tam_fuente) + + def __init_surface(self): + tam = (self.__mitad_tam_celda * 2) + (self.__tam_celda * self.__tablero.get_dimension()) + self.__surface = pygame.Surface((tam, tam), SRCALPHA,32) + self.__conf_surface = pygame.Surface((tam, tam), SRCALPHA,32) + + def set_coord_selected_cell(self, nueva_coord): + self.__current_cell.set(nueva_coord) + + def get_coord_selected_cell(self): + return self.__current_cell + + def get_logical_board(self): + return self.__tablero + + def get_board_pos(self): + return self.__pos_graphic_board + + def get_board_surface(self): + return self.__surface + + def get_configuration_surface(self): + return self.__conf_surface + + """ + + Render a piece in a specific position on the board + + Params: + - valor_casilla : BLACK or WHITE + - x_s, y_s : surface render coordinate + - superficie : render surface + """ + def __render_piece(self,valor_casilla,x_s,y_s,superficie): + if valor_casilla == BLANCO: + superficie.blit(self.__imagen_pieza_blanca, (x_s,y_s)) + elif valor_casilla == NEGRO: + superficie.blit(self.__imagen_pieza_negra, (x_s,y_s)) + + """ + + Render an empty cell in the screen + + Params: + - celda_coord : cell screen coordinate + - tablero_coord : cell board coordinate + - ventana : render screen + """ + def __render_cell(self,celda_coord, superficie): + #Coordenadas de pantalla + x = celda_coord.x + y = celda_coord.y + #Muestro la celda en blanco + superficie.blit(self.__imagen_celda, (x,y)) + + def render(self): + #self.__set_corner_pixels(self.__surface) + #self.__render_all_corners() + #self.__render_board() + return self.__surface + #superficie.blit(self.__surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + + """ + + Render the board in the graphic board surface + + Params: + None + """ + def __render_board(self): + x = self.__pos_ini.x + self.__mitad_tam_celda + for j in xrange(0, self.__tablero.get_dimension()): + y = self.__pos_ini.y + for i in xrange(0, self.__tablero.get_dimension()): + #Muestro el borde horizontal junto con el numero si es la primera fila + if i == 0: + self.__surface.blit(self.__imagen_tablero_bordeh, (x,y)) + #Numero del borde horizontal superior + nro_horizontal = self.__fuente.render(str(j+1), True, (255,255,0)) + nx = x + self.__inc_numero_borde_h.x + ny = y + self.__inc_numero_borde_h.y + self.__surface.blit(nro_horizontal, (nx,ny)) + y += self.__mitad_tam_celda + #Calculo el numero a imprimir en el borde vertical + nro_vertical = str(self.__tablero.get_dimension() - i) + nro_vertical_text = self.__fuente.render(nro_vertical, True, (255,255,0)) + #Muestro el borde vertical izquierda junto con el numero si es la primera columna + if j == 0: + self.__surface.blit(self.__imagen_tablero_bordev, (self.__pos_ini.x,y)) + #Numero del borde vertical izquierda + nx = self.__pos_ini.x + self.__inc_numero_borde_vi.x + ny = y + self.__inc_numero_borde_vi.y + self.__surface.blit(nro_vertical_text, (nx,ny)) + #Render una celda vacio + self.__render_cell(Coordinate(x,y), self.__surface) + #Guardo la coordenada de pantalla de la celda + self.__coordenadas[i][j] = Coordinate(x,y) + #Muestro el borde vertical derecha junto con los numeros si es la ultima columna + if j == self.__tablero.get_dimension() - 1: + nx = x + self.__inc_borde_vd.x + ny = y + self.__inc_borde_vd.y + self.__surface.blit(self.__imagen_tablero_bordev, (nx,ny)) + #Numero del borde vertical izquierda + nx = nx + self.__inc_numero_borde_vd.x + ny = ny + self.__inc_numero_borde_vd.y + self.__surface.blit(nro_vertical_text, (nx,ny)) + #Muestro el borde horizontal si es la ultima fila + if i == self.__tablero.get_dimension() - 1: + y += self.__tam_celda + self.__surface.blit(self.__imagen_tablero_bordeh, (x,y)) + #Numero del borde horizontal inferior + nx = x + self.__inc_numero_borde_h.x + ny = y + self.__inc_numero_borde_h.y + self.__surface.blit(nro_horizontal, (nx,ny)) + y += self.__tam_celda + x += self.__tam_celda + + def render_configuration(self, ventana=""): + #self.__render_board() + tam = (self.__mitad_tam_celda * 2) + (self.__tam_celda * self.__tablero.get_dimension()) + self.__conf_surface = pygame.Surface((tam, tam),SRCALPHA,32) + dim = self.__tablero.get_dimension() + #superficie = self.__surface + for i in xrange(0,dim): + for j in xrange(0,dim): + valor_casilla = self.__tablero.get_valor_casilla(i,j) + if valor_casilla != VACIO: + x_s = self.__coordenadas[i][j].x + y_s = self.__coordenadas[i][j].y + self.__render_piece(valor_casilla, x_s, y_s, self.__conf_surface) + ventana.blit(self.__surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + ventana.blit(self.__conf_surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + + def __render_background_corner(self,esquina): + if esquina == self.__IARRIBA: + x_ini = self.__pos_ini.x + y_ini = self.__pos_ini.y + esquina = self.__esquinaiarriba + elif esquina == self.__IABAJO: + x_ini = self.__pos_ini.x + y_ini = self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + esquina = self.__esquinaiabajo + elif esquina == self.__DARRIBA: + x_ini = self.__pos_ini.x + self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + y_ini = self.__pos_ini.y + esquina = self.__esquinadarriba + elif esquina == self.__DABAJO: + x_ini = self.__pos_ini.x + self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + y_ini = self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + esquina = self.__esquinadabajo + for i in xrange(0,self.__mitad_tam_celda): + x = x_ini + i + for j in xrange(0,self.__mitad_tam_celda): + y = y_ini + j + self.__surface.set_at((x,y),esquina[i][j]) + + def __render_all_corners(self): + self.__render_background_corner(self.__IARRIBA) + self.__render_background_corner(self.__IABAJO) + self.__render_background_corner(self.__DARRIBA) + self.__render_background_corner(self.__DABAJO) + + def __get_corner_pixels(self,x_ini,y_ini,ventana): + esquina = [] + for _ in xrange(self.__mitad_tam_celda): + esquina.append([None]*self.__mitad_tam_celda) + + for i in xrange(0,self.__mitad_tam_celda): + for j in xrange(0,self.__mitad_tam_celda): + x = x_ini + i + y = y_ini + j + esquina[i][j] = ventana.get_at((x,y)) + return esquina + + def __set_corner_pixels(self,ventana): + #Esquina Izquierda Arriba + x_ini = self.__pos_graphic_board.x + y_ini = self.__pos_graphic_board.y + self.__esquinaiarriba = self.__get_corner_pixels(x_ini,y_ini,ventana) + #Esquina Izquierda Abajo + y_ini = self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + self.__esquinaiabajo = self.__get_corner_pixels(x_ini, y_ini, ventana) + #Esquina Derecha Arriba + x_ini = self.__pos_graphic_board.x + self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + y_ini = self.__pos_graphic_board.y + self.__esquinadarriba = self.__get_corner_pixels(x_ini, y_ini, ventana) + #Esquina Derecha Abajo + y_ini = self.__mitad_tam_celda + (self.__tam_celda * self.__tablero.get_dimension()) + self.__esquinadabajo = self.__get_corner_pixels(x_ini, y_ini, ventana) + + def __seleccion_is_on_corner(self): + #coord_logica = self.graphic_coord_to_logic_coord(self.__current_cell) + coord_logica = self.__current_cell + dim = self.__tablero.get_dimension() + if (coord_logica.x == 0 or coord_logica.x == dim - 1) and \ + (coord_logica.y == 0 or coord_logica.y == dim - 1): + return True + else: + return False + + def __seleccion_is_on_border(self): + #coord_logica = self.graphic_coord_to_logic_coord(self.__current_cell) + coord_logica = self.__current_cell + dim = self.__tablero.get_dimension() + if coord_logica.x == 0 or coord_logica.x == dim - 1 or \ + coord_logica.y == 0 or coord_logica.y == dim - 1: + return True + else: + return False + + def end_animation_cell(self): + self.__do_animation_cell = False + pygame.time.wait(200) + + def animation_cell_running(self): + return self.__do_animation_cell + + def set_up_image(self, hash_image): + self.__up_images.append(hash_image) + + def remove_up_images(self): + self.__up_images = [] + + def __re_calculate_update_rect(self): + dim = self.__tablero.get_dimension() + coord_logica = self.__current_cell + coord_actual = Coordinate(self.__coordenadas[coord_logica.x][coord_logica.y].x, self.__coordenadas[self.__current_cell.x][self.__current_cell.y].y) + if self.__seleccion_is_on_corner(): + if coord_logica.x == 0 and coord_logica.y == 0: + #Esquina Izquierda Arriba + x = coord_actual.x - self.__imagen_tablero_bordev.get_width() + y = coord_actual.y - self.__imagen_tablero_bordeh.get_height() + elif coord_logica.x == 0 and coord_logica.y == dim - 1: + #Esquina Derecha Arriba + x = coord_actual.x - self.__imagen_celda.get_width() + y = coord_actual.y - self.__imagen_tablero_bordeh.get_height() + elif coord_logica.x == dim - 1 and coord_logica.y == 0: + #Esquina Izquierda Abajo + x = coord_actual.x - self.__imagen_tablero_bordev.get_width() + y = coord_actual.y - self.__imagen_celda.get_height() + else: + #Esquina Derecha Abajo + x = coord_actual.x - self.__imagen_celda.get_width() + y = coord_actual.y - self.__imagen_celda.get_height() + w = 2 * self.__imagen_celda.get_width() + self.__imagen_tablero_bordev.get_width() + h = 2 * self.__imagen_celda.get_height() + self.__imagen_tablero_bordeh.get_height() + elif self.__seleccion_is_on_border(): + #log.debug("La seleccion esta en un borde") + if coord_logica.x == 0: + #Borde Arriba + x = coord_actual.x - self.__imagen_celda.get_width() + y = coord_actual.y - self.__imagen_tablero_bordeh.get_height() + w = 3 * self.__imagen_celda.get_width() + h = 2 * self.__imagen_celda.get_height() + self.__imagen_tablero_bordeh.get_height() + elif coord_logica.y == dim - 1: + #Borde Derecha + x = coord_actual.x - self.__imagen_celda.get_width() + y = coord_actual.y - self.__imagen_celda.get_height() + w = 2 * self.__imagen_celda.get_width() + self.__imagen_tablero_bordev.get_width() + h = 3 * self.__imagen_celda.get_height() + elif coord_logica.y == 0: + #Borde Izquierdo + x = coord_actual.x - self.__imagen_tablero_bordev.get_width() + y = coord_actual.y - self.__imagen_celda.get_height() + w = 2 * self.__imagen_celda.get_width() + self.__imagen_tablero_bordev.get_width() + h = 3 * self.__imagen_celda.get_height() + else: + #Borde Abajo + x = coord_actual.x-self.__imagen_celda.get_width() + y = coord_actual.y-self.__imagen_celda.get_height() + w = 3 * self.__imagen_celda.get_width() + h = 2 * self.__imagen_celda.get_height() + self.__imagen_tablero_bordeh.get_height() + else: + x = coord_actual.x-self.__imagen_celda.get_width() + y = coord_actual.y-self.__imagen_celda.get_height() + w = 3 * self.__imagen_celda.get_width() + h = 3 * self.__imagen_celda.get_height() + rect = pygame.Rect((x,y),(w,h)) + return rect + + """ + + Render the animated cell + + Params: + - pos_casilla : animated cell coordinate + - ventana : render screen + """ + def render_animation_cell(self, superficie): + #update_rect = pygame.Rect((self.__pos_graphic_board.x, self.__pos_graphic_board.y), (self.__surface.get_width(), self.__surface.get_height())) + self.__set_corner_pixels(superficie) + self.__do_animation_cell = True + while self.__do_animation_cell: + render_all_board = False + if not self.__current_cell.equal(self.__animated_cell): + self.__animated_cell.set(self.__current_cell) + self.__factor = -1 + self.__nro_imagen = 0 + render_all_board = True + #Coordenadas de pantalla + x = self.__coordenadas[self.__current_cell.x][self.__current_cell.y].x + self.__pos_graphic_board.x + y = self.__coordenadas[self.__current_cell.x][self.__current_cell.y].y + self.__pos_graphic_board.y + i = self.__nro_imagen + f = self.__factor + if i == 2 or i == 0: + f *= -1 + i = i + f + if self.__seleccion_is_on_corner(): + self.__render_all_corners() + if render_all_board: + superficie.blit(self.__surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + superficie.blit(self.__conf_surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + rect_sub_sup = self.__re_calculate_update_rect() + else: + sub_sup_tablero = self.__surface.subsurface(rect_sub_sup) + sub_sup_conf = self.__conf_surface.subsurface(rect_sub_sup) + superficie.blit(sub_sup_tablero,(rect_sub_sup.left+self.__pos_graphic_board.x,rect_sub_sup.top+self.__pos_graphic_board.y)) + superficie.blit(sub_sup_conf,(rect_sub_sup.left+self.__pos_graphic_board.x,rect_sub_sup.top+self.__pos_graphic_board.y)) + superficie.blit(self.__imagenes_celda_animada[i], (x-(i+i),y-(i+i))) + #Muestro alguna pieza si es que existe alguna en la celda animada + valor_casilla = self.__tablero.get_valor_casilla(self.__current_cell.x,self.__current_cell.y) + if valor_casilla != VACIO: + self.__render_piece(valor_casilla,x,y,superficie) + else: + #Si es una casilla vacia muestro alguna marca si es que existe alguna en la celda animada + self.__render_possible_move(self.__current_cell, superficie) + self.__nro_imagen = i + self.__factor = f + if not render_all_board: + #Si no rendereo todo el tablero, el rectangulo de actualizacion es solo el tamano del sub rectangulo. + update_rect = pygame.Rect((rect_sub_sup.left + self.__pos_graphic_board.x,rect_sub_sup.top + self.__pos_graphic_board.y),(rect_sub_sup.width,rect_sub_sup.height)) + else: + update_rect = pygame.Rect((self.__pos_graphic_board.x, self.__pos_graphic_board.y), (self.__surface.get_width(), self.__surface.get_height())) + if not self.__up_images == []: + for image in self.__up_images: + rect_img = pygame.Rect(image['posicion'],(image['imagen'].get_width(),image['imagen'].get_height())) + if rect_img.colliderect(update_rect): + superficie.blit(image['imagen'],image['posicion']) + pygame.time.wait(150) + pygame.display.update(update_rect) + + def __print_log(self, archivo, mensaje): + if archivo != "": + print >> archivo, mensaje + + def do_move(self, direccion, audio, archivo_juego=""): + #No Pudo realizar el movimiento + if not self.__set_new_coordinates(direccion): + audio.play_fx_sound("board","mal_mov") + if direccion == ARRIBA: + dir_mov = "arriba" + elif direccion == ABAJO: + dir_mov = "abajo" + elif direccion == DERECHA: + dir_mov = "derecha" + else: + dir_mov = "izquierda" + self.__print_log(archivo_juego, "ERROR!, estaba en: " + str(self.__current_cell) + " e hizo un movimiento " + dir_mov) + else: + volumen_laterales = {"volumen":self.__stereo_pan(self.__current_cell.y)} + self.play_box_sound(audio, self.__current_cell, self.lista_jugadas, volumen_laterales) + + def __set_new_coordinates(self, direccion): + nueva_coord = self.get_new_coordinates(direccion) + if not nueva_coord == False: + self.__current_cell = nueva_coord + return True + else: + return False + + """ + + Get the new coordinate from the actual coordinate + + Params: + - direccion : new coordinate direction (left,right,up,down) + - coordenada_actual : actual coordinate + """ + def get_new_coordinates(self,direccion): + coordenada_nueva = self.__current_cell + + if direccion == IZQUIERDA: + if self.__current_cell.y > 0: + coordenada_nueva.y -= 1 + else: + return False + elif direccion == DERECHA: + if self.__current_cell.y < self.__tablero.get_dimension() - 1: + coordenada_nueva.y += 1 + else: + return False + elif direccion == ARRIBA: + if self.__current_cell.x > 0: + coordenada_nueva.x -= 1 + else: + return False + elif direccion == ABAJO: + if self.__current_cell.x < self.__tablero.get_dimension() - 1: + coordenada_nueva.x += 1 + else: + return False + + return coordenada_nueva + + """ + + Render a possible move if exist in the list of possibles moves + Params: + - coord : possible move coordinate + - ventana : render screen + """ + def __render_possible_move(self,coord,ventana): + coordenadas = self.__coordenadas + for c in self.lista_jugadas: + if c.x == coord.x and c.y == coord.y: + x = coordenadas[c.x][c.y].x + self.__pos_graphic_board.x + y = coordenadas[c.x][c.y].y + self.__pos_graphic_board.y + #Muestro la marca en el tablero + ventana.blit(self.__imagen_marca, (x,y)) + break + + """ + + Render a list of possibles moves + + Params: + - ventana : render screen + """ + def render_list_possible_moves(self, ventana): + coordenadas = self.__coordenadas + for c in self.lista_jugadas: + x = coordenadas[c.x][c.y].x + y = coordenadas[c.x][c.y].y + #Muestro la marca en el tablero + self.__conf_surface.blit(self.__imagen_marca, (x,y)) + ventana.blit(self.__conf_surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + + def __render_animation_image(self,imagen,inc,coord,ventana): + x = self.__coordenadas[coord.x][coord.y].x + self.__pos_graphic_board.x + y = self.__coordenadas[coord.x][coord.y].y + self.__pos_graphic_board.y + ventana.blit(imagen, (x-inc,y-inc)) + self.__render_piece(self.__tablero.get_valor_casilla(coord.x,coord.y),x,y,ventana) + + def __render_line_animation(self,linea,color,sonido,audio,ventana): + audio.play_voice_sound("board","linea_entre") + graphic_coord = self.convert_logic_coord_to_graphic_coord(linea["casilla_inicial"]) + volumen_laterales = {"volumen":self.__stereo_pan(linea["casilla_inicial"].y)} + self.__play_coordinate_sound(audio, graphic_coord,volumen_laterales) + audio.play_voice_sound("otros","y") + volumen_laterales = {"volumen":self.__stereo_pan(linea["casilla_final"].y)} + graphic_coord = self.convert_logic_coord_to_graphic_coord(linea["casilla_final"]) + self.__play_coordinate_sound(audio, graphic_coord,volumen_laterales) + i = self.__nro_imagen + f = self.__factor + can_casillas_v = linea["can_fichas_volteables"] - 1 + update_rect = pygame.Rect((self.__pos_graphic_board.x, self.__pos_graphic_board.y), (self.__surface.get_width(), self.__surface.get_height())) + while can_casillas_v >= 0: + if audio.silence_channel(): + self.__tablero.turn_pieces2(linea["casillas_volteables"][can_casillas_v],color) + can_casillas_v = can_casillas_v - 1 + volumen_laterales = {"volumen":self.__stereo_pan(linea["casillas_volteables"][can_casillas_v].y)} + audio.play_fx_sound("board",sonido,volumen_laterales) + self.render_configuration(ventana) + if i == 2: + f *= -1 + elif i == 0: + f *= -1 + i = i + f + ventana.blit(self.__surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + ventana.blit(self.__conf_surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + self.__render_animation_image(self.__imagenes_celda_animada[i], i+i, linea["casilla_inicial"], ventana) + for casilla in linea["casillas_volteables"]: + self.__render_animation_image(self.__imagenes_celda_animada[i], i+i, casilla, ventana) + self.__render_animation_image(self.__imagenes_celda_animada[i], i+i, linea["casilla_final"], ventana) + pygame.display.update(update_rect) + pygame.time.wait(150) + ventana.blit(self.__surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + ventana.blit(self.__conf_surface,(self.__pos_graphic_board.x,self.__pos_graphic_board.y)) + pygame.display.update(update_rect) + + def __play_coordinate_sound(self, audio, coord, vol): + audio.play_voice_sound("numero",get_number_word(coord.y),vol) + audio.play_voice_sound("numero",get_number_word(coord.x),vol) + + def __play_move_sound(self, audio, coord): + volumen_laterales = {"volumen":self.__stereo_pan(coord.y)} + audio.play_voice_sound("board","jugada_en",volumen_laterales) + graphic_coord = self.convert_logic_coord_to_graphic_coord(coord) + self.__play_coordinate_sound(audio, graphic_coord,volumen_laterales) + + def set_piece(self, coord, color, sonido_color, audio, ventana): + pudo_colocar = self.__tablero.set_piece(coord,color) + if pudo_colocar: + self.lista_jugadas = [] + self.render_configuration(ventana) + volumen_laterales = {"volumen":self.__stereo_pan(coord.y)} + audio.play_fx_sound("board",sonido_color,volumen_laterales) + self.__play_move_sound(audio, coord) + update_rect = pygame.Rect((self.__pos_graphic_board.x, self.__pos_graphic_board.y), (self.__surface.get_width(), self.__surface.get_height())) + pygame.display.update(update_rect) + return True + else: + return False + + def convert_logic_coord_to_graphic_coord(self, logic_coord): + return Coordinate(self.__tablero.get_dimension()-logic_coord.x,logic_coord.y+1) + + def graphic_coord_to_logic_coord(self, coord_grafica): + return Coordinate(self.__tablero.get_dimension()-coord_grafica.x,coord_grafica.y-1) + + def do_line_animation(self, coord, color, sonido, canal, marcador, ventana): + lineas_formadas = self.get_logical_board().get_lines(color,coord) + for linea in lineas_formadas: + self.__render_line_animation(linea,color,sonido,canal,ventana) + marcador.render_numbers(self.get_logical_board(),color,ventana) + + def play_possible_moves_sound(self, audio): + audio.play_voice_sound("board","jugada_posible") + can_jp = len(self.lista_jugadas) + con = 0 + if can_jp > 0: + for jp_coord in self.lista_jugadas: + con += 1 + if con == can_jp: + audio.play_voice_sound("otros","y_en") + else: + audio.play_voice_sound("otros","en") + graphic_coord = self.convert_logic_coord_to_graphic_coord(jp_coord) + volumen_laterales = {"volumen":self.__stereo_pan(jp_coord.y)} + self.__play_coordinate_sound(audio, graphic_coord, volumen_laterales) + audio.play_voice_sound("otros","silencio") + else: + audio.play_voice_sound("board","no_hay_jugadas_posibles") + + def play_count_pieces_sound(self, audio, juego=""): + if juego != "": + jugador = juego.get_turn() + can_jugadas_posibles = len(juego.get_list_possible_moves()) + else: + can_jugadas_posibles = len(self.lista_jugadas) + audio.play_voice_sound("board","tablero_tiene") + can_fichas_blancas = self.__tablero.get_number_white_pieces() + can_fichas_negras = self.__tablero.get_number_black_pieces() + if can_fichas_blancas > 1: + audio.play_voice_sound("numero",get_number_word(can_fichas_blancas)) + audio.play_voice_sound("board","fichas_blancas") + else: + audio.play_voice_sound("numero","una") + audio.play_voice_sound("board","ficha_blanca") + if can_fichas_negras > 1: + audio.play_voice_sound("numero",get_number_word(can_fichas_negras)) + audio.play_voice_sound("board","fichas_negras") + else: + audio.play_voice_sound("numero","una") + audio.play_voice_sound("board","ficha_negra") + if juego == "" or (juego != "" and not juego.game_ended()): + audio.play_voice_sound("otros","y") + if not can_jugadas_posibles == 1: + if can_jugadas_posibles == 0 and (jugador != "" and jugador.get_name() == HUMANO): + audio.play_voice_sound("game","no_hay_jugadas_posbiles") + return False + else: + audio.play_voice_sound("numero",get_number_word(can_jugadas_posibles)) + audio.play_voice_sound("board","jugadas_posibles") + return True + else: + audio.play_voice_sound("numero","una") + audio.play_voice_sound("board","jugada_posible") + return True + + def __stereo_pan(self, coord_columna): + volumen_derecha = float(coord_columna) / (self.__tablero.get_dimension() - 1) + volumen_izquierda = 1.0 - volumen_derecha + return {"derecha":volumen_derecha, "izquierda":volumen_izquierda} + + def __play_coordinate_sound_extra_info(self, audio, coord, volumen): + graphic_coord = self.convert_logic_coord_to_graphic_coord(coord) + audio.play_voice_sound("board","columna",volumen) + audio.play_voice_sound("numero",get_number_word(graphic_coord.y),volumen) + audio.play_voice_sound("board","fila",volumen) + audio.play_voice_sound("numero",get_number_word(graphic_coord.x),volumen) + + def play_box_info_sound(self, audio, coord=""): + if coord == "": + coord = self.__current_cell + volumen_laterales = {"volumen":self.__stereo_pan(coord.y)} + self.__play_coordinate_sound_extra_info(audio, coord, volumen_laterales) + self.play_box_sound(audio, coord, [], volumen_laterales) + + def play_box_sound(self, audio, coord, lista_jugadas, volumen_laterales): + tablero = self.__tablero + jugada_posible = False + for jugada in lista_jugadas: + if jugada.x == coord.x and jugada.y == coord.y: + audio.play_fx_sound("board","jugada_posible",volumen_laterales) + audio.play_voice_sound("board","jugada_posible",volumen_laterales) + jugada_posible = True + break + if not jugada_posible: + valor_casilla = tablero.get_valor_casilla(coord.x,coord.y) + if valor_casilla == VACIO: + audio.play_fx_sound("board","vacio",volumen_laterales) + audio.play_voice_sound("board","vacio",volumen_laterales) + elif valor_casilla == BLANCO: + audio.play_fx_sound("board","blanco",volumen_laterales) + audio.play_voice_sound("board","blanco",volumen_laterales) + elif valor_casilla == NEGRO: + audio.play_fx_sound("board","negro",volumen_laterales) + audio.play_voice_sound("board","negro",volumen_laterales) + else: + raise Exception("Error!, valor de casilla desconocido (Othello.Gui Class)") + +class Score: + def __init__(self, resolucion=(800,600)): + #Inicilializo las constasntes graficas dependiendo de la resolucion + self.__init_constants(resolucion) + self.__resolucion = resolucion + #Inicializo las fuentes + self.__init_fonts() + #Inicializo las imagenes + self.__init_images(resolucion) + self.__sup_marcador_izq = "" + self.__sup_marcador_der = "" + + def __init_constants(self,resolucion): + #Si la resolucion es de 800x600 + if resolucion == RESOLUTION1: + self.__barra = Coordinate(0,0) + self.__bandera = Coordinate(6,6) + self.__tam_fuente = 60 + self.__x_marcador = 15 + self.__y_marcador = 300 + #Si la resolucion es de 1200x900 + elif resolucion == RESOLUTION2: + self.__barra = Coordinate(0,0) + self.__bandera = Coordinate(9,7) + self.__tam_fuente = 80 + self.__x_marcador = 25 + self.__y_marcador = 350 + else: + raise Exception("Resolucion desconocida (Score Class)") + #Iniciliazo los colores de las fuentes + self.__color_negro = (0,0,0) + self.__color_amarillo = (255,255,0) + + def __init_fonts(self): + self.__fuente = pygame.font.Font(Fonts.get_fonts_file_names()["fuente1"],self.__tam_fuente) + + def __init_images(self, resolucion): + na_imagenes_marcador = Images.get_images_file_names(resolucion, "marcador") + self.__imagen_barra_negra = pygame.image.load(na_imagenes_marcador["barra_negra"]).convert_alpha() + self.__imagen_barra_amarilla = pygame.image.load(na_imagenes_marcador["barra_amarilla"]).convert_alpha() + self.__imagen_bandera_negra = pygame.image.load(na_imagenes_marcador["bandera_negra"]).convert_alpha() + self.__imagen_bandera_blanca = pygame.image.load(na_imagenes_marcador["bandera_blanca"]).convert_alpha() + + def refresh(self, ventana): + if not self.__sup_marcador_der == "" and not self.__sup_marcador_izq == "": + ventana.blit(self.__sup_marcador_izq,(0,0)) + ventana.blit(self.__sup_marcador_der,(self.__resolucion[0] - self.__sup_marcador_der.get_width(),0)) + x1 = self.__resolucion[0] - self.__imagen_barra_negra.get_width() + x2 = self.__imagen_barra_negra.get_width() + y2 = self.__imagen_barra_negra.get_height() + update_rect_izq = pygame.Rect((0, 0), (x2, y2)) + update_rect_der = pygame.Rect((x1, 0), (x2, y2)) + pygame.display.update([update_rect_izq,update_rect_der]) + + def render_numbers(self, tablero, turno, ventana): + self.__render(tablero, ventana, turno) + x1 = self.__resolucion[0] - self.__imagen_barra_negra.get_width() + x2 = self.__imagen_barra_negra.get_width() + y2 = self.__imagen_barra_negra.get_height() / 2 + update_rect_izq = pygame.Rect((0, 0), (x2, y2)) + update_rect_der = pygame.Rect((x1, 0), (x2, y2)) + pygame.display.update([update_rect_izq,update_rect_der]) + + def render_all(self, tablero, turno, ventana): + self.__render(tablero, ventana, turno) + x1 = self.__resolucion[0] - self.__imagen_barra_negra.get_width() + x2 = self.__imagen_barra_negra.get_width() + y2 = self.__imagen_barra_negra.get_height() + update_rect_izq = pygame.Rect((0, 0), (x2, y2)) + update_rect_der = pygame.Rect((x1, 0), (x2, y2)) + #pygame.display.update([update_rect_izq,update_rect_der]) + + def __render(self,tablero,ventana,turno): + self.__sup_marcador_izq = self.render_left_score(tablero, turno) + self.__sup_marcador_der = self.render_right_score(tablero, turno) + #Pego las superficies de los marcadores a la ventana + ventana.blit(self.__sup_marcador_izq,(0,0)) + ventana.blit(self.__sup_marcador_der,(self.__resolucion[0] - self.__sup_marcador_der.get_width(),0)) + + def render_left_score(self, tablero, turno): + superficie = pygame.Surface(self.__imagen_barra_amarilla.get_size(),SRCALPHA,32) + #Copio la barra izquierda del marcador cambiando el color dependiendo del turno + if turno == BLANCO: + superficie.blit(self.__imagen_barra_amarilla, (self.__barra.x,self.__barra.y)) + color_fuente_barra_iz = self.__color_negro + else: + superficie.blit(self.__imagen_barra_negra, (self.__barra.x,self.__barra.y)) + color_fuente_barra_iz = self.__color_amarillo + #Copio la bandera blanca sobre la barra + superficie.blit(self.__imagen_bandera_blanca, (self.__bandera.x,self.__bandera.y)) + marcador_blancas = tablero.get_number_white_pieces() + if marcador_blancas < 10: + marcador_blancas = "0" + str(marcador_blancas) + else: + marcador_blancas = str(marcador_blancas) + #Muestro los marcadores + superficie.blit(self.__fuente.render(marcador_blancas, True, color_fuente_barra_iz), (self.__x_marcador,self.__y_marcador)) + self.__sup_marcador_izq = superficie + return superficie + + def render_right_score(self, tablero, turno): + superficie = pygame.Surface(self.__imagen_barra_negra.get_size(),SRCALPHA,32) + #Copio la barra derecha del marcador + if turno == NEGRO: + superficie.blit(self.__imagen_barra_amarilla, (self.__barra.x,self.__barra.y)) + color_fuente_barra_de = self.__color_negro + else: + superficie.blit(self.__imagen_barra_negra, (self.__barra.x,self.__barra.y)) + color_fuente_barra_de = self.__color_amarillo + #Copio la bandera negra sobre la barra + superficie.blit(self.__imagen_bandera_negra, (self.__bandera.x,self.__bandera.y)) + marcador_negras = tablero.get_number_black_pieces() + if marcador_negras < 10: + marcador_negras = "0" + str(marcador_negras) + else: + marcador_negras = str(marcador_negras) + #Muestro los marcadores + superficie.blit(self.__fuente.render(marcador_negras, True, color_fuente_barra_de), (self.__x_marcador,self.__y_marcador)) + self.__sup_marcador_der = superficie + return superficie
\ No newline at end of file diff --git a/src/othello/gui.pyc b/src/othello/gui.pyc Binary files differnew file mode 100644 index 0000000..0d90c81 --- /dev/null +++ b/src/othello/gui.pyc diff --git a/src/othello/player.py b/src/othello/player.py new file mode 100755 index 0000000..af147b5 --- /dev/null +++ b/src/othello/player.py @@ -0,0 +1,25 @@ +from board import BLANCO
+
+HUMANO = 8
+PC = -8
+VIRTUAL = -9
+
+class Player:
+ def __init__(self,color_ficha=BLANCO,nombre=PC):
+ self.__color = color_ficha
+ self.__nombre = nombre
+
+ def get_color(self):
+ return self.__color
+
+ def get_name(self):
+ return self.__nombre
+
+ def equal(self,other):
+ if self.__color == other.__color and self.__nombre == other.__nombre:
+ return True
+ else:
+ return False
+
+ def __str__(self):
+ return "Color:" + str(self.__color) + ", Nombre: " + str(self.__nombre)
\ No newline at end of file diff --git a/src/othello/player.pyc b/src/othello/player.pyc Binary files differnew file mode 100644 index 0000000..05fb4b8 --- /dev/null +++ b/src/othello/player.pyc diff --git a/src/othello/referee.py b/src/othello/referee.py new file mode 100755 index 0000000..65269d8 --- /dev/null +++ b/src/othello/referee.py @@ -0,0 +1,141 @@ +import board, logging +from utils import Coordinate + +log = logging.getLogger( 'src.othello.referee' ) +log.setLevel( logging.DEBUG ) + +class Referee: + + """ + Check if is valid to play the color in the position given as a parameter + + Params: + - color: White or Black + - posicion: coordinate to play + - tablero: actual state of board + Return: + - True or False + """ + @staticmethod + def is_valid_move(color, posicion, tablero): + # Si la posicion sale del rango del tablero retorna false. + if not tablero.valid_coord(posicion): + return False + # Si la casilla donde se quiere jugar no esta vacia retorna false. + if tablero.get_casillas()[posicion.x][posicion.y] != board.VACIO: + return False + # Se verifica si hay fichas a voltear en al menos una direccion + dimension = tablero.get_dimension() + for inc_fila in range(-1,2): + for inc_col in range(-1,2): + if Referee.can_turn(color, posicion, inc_fila, inc_col, tablero): + return True + + # Si no hay fichas que voltear en ninguna direccion se retorna false. + return False + + """ + Check in the horizontal and vertical direction if exists pieces to turn + + Params: + -color: Black or White + -pos_ini: Start position + -dir_horizontal: Horizontal direction + -dir_vertical: Vertical direction + -tablero: actual state of board + Return: + - True or False + """ + @staticmethod + def can_turn(color, pos_ini, dir_horizontal, dir_vertical, tablero): + pos_fin = Coordinate(pos_ini.x + dir_horizontal, pos_ini.y + dir_vertical) + if not tablero.valid_coord(pos_fin): + return False + + # Verifica que haya al menos una ficha del color opuesto en esa direccion + if tablero.get_casillas()[pos_fin.x][pos_fin.y] != -1 * color: + return False + + # Ejecuto el while mientras la casilla del tablero contenga piezas del color opuesto, + # es decir no sea VACIO, ni de mi color, ni este fuera del tablero + while True: + pos_fin.x += dir_horizontal + pos_fin.y += dir_vertical + if not tablero.valid_coord(pos_fin): + return False + if tablero.get_casillas()[pos_fin.x][pos_fin.y] == board.VACIO: + return False + elif tablero.get_casillas()[pos_fin.x][pos_fin.y] == color: + return True + + """ + Check if exist at least one move for the color given as a parameter + + Params: + - color: White or Black + - tablero: actual state of board + Return: + - True or False + """ + @staticmethod + def is_at_least_one_move(color, tablero): + dimension = tablero.get_dimension() + pos = Coordinate() + + for i in range (0,dimension): + for j in range (0, dimension): + pos.x = i + pos.y = j + if Referee.is_valid_move(color, pos, tablero): + return True + + return False + + """ + Return a list of possibles moves for the color given as a parameter + + Params: + -color (White or Black) + -tablero: actual state of board + Return: + -List of possible moves + """ + @staticmethod + def possibles_moves(color, tablero): + coordenadas = [] + pos = Coordinate() + dimension = tablero.get_dimension() + + for i in range (0,dimension): + for j in range (0, dimension): + pos.x = i + pos.y = j + if Referee.is_valid_move(color, pos, tablero): + nueva_pos = Coordinate(i, j) + coordenadas.append(nueva_pos) + + return coordenadas + + """ + Calculate the number of successors for the given color in the state of board + + Params: + -color: White or Black + -tablero: actual state of board + Return: + -Number of successors + """ + @staticmethod + def number_of_successors(color, tablero): + cant_sucesores = 0 + pos = Coordinate() + dimension = tablero.get_dimension() + + for i in range (0,dimension): + for j in range (0, dimension): + pos.x = i + pos.y = j + if Referee.is_valid_move(color, pos, tablero): + cant_sucesores += 1 + + return cant_sucesores
\ No newline at end of file diff --git a/src/othello/referee.pyc b/src/othello/referee.pyc Binary files differnew file mode 100644 index 0000000..ebb4b71 --- /dev/null +++ b/src/othello/referee.pyc diff --git a/src/othello/utils.py b/src/othello/utils.py new file mode 100755 index 0000000..b9913cf --- /dev/null +++ b/src/othello/utils.py @@ -0,0 +1,274 @@ +import logging + +log = logging.getLogger( 'src.othello.utils' ) +log.setLevel( logging.DEBUG ) + +""" + Modulo que contiene todo lo que no cabe dentro de las otros modulos. +""" + +class Coordinate(): + + def __init__(self,x=0,y=0): + self.x = x + self.y = y + + def __str__(self): + return "("+str(self.x)+", "+str(self.y)+")" + + """ + Invest the coordinates because x(row) and y(column) in the board are y and x in the screen + """ + def invest(self): + return Coordinate(self.y,self.x) + + def set(self, coord): + self.x = coord.x + self.y = coord.y + + def equal(self,coord): + if coord.x == self.x and coord.y == self.y: + return True + else: + return False + + def equal_xy(self, x, y): + if self.x == x and self.y == y: + return True + else: + return False + + def to_string(self): + return "("+str(self.x)+", "+str(self.y)+")" + + +def get_number_word(num, turno=False, medallas=False): + if num == 1: + if medallas: + return "una" + else: + return "uno" + elif num == 2: + return "dos" + elif num == 3: + return "tres" + elif num == 4: + return "cuatro" + elif num == 5: + return "cinco" + elif num == 6: + return "seis" + elif num == 7: + return "siete" + elif num == 8: + return "ocho" + elif num == 9: + return "nueve" + elif num == 0: + return "cero" + elif num == 10: + return "diez" + elif num == 11: + return "once" + elif num == 12: + return "doce" + elif num == 13: + return "trece" + elif num == 14: + return "catorce" + elif num == 15: + return "quince" + elif num == 16: + return "dieciseis" + elif num == 17: + return "diecisiete" + elif num == 18: + return "dieciocho" + elif num == 19: + return "diecinueve" + elif num == 20: + return "veinte" + elif num == 21: + if turno: + return "veintiuno" + else: + return "veintiun" + elif num == 22: + return "veintidos" + elif num == 23: + return "veintitres" + elif num == 24: + return "veinticuatro" + elif num == 25: + return "veinticinco" + elif num == 26: + return "veintiseis" + elif num == 27: + return "veintisiete" + elif num == 28: + return "veintiocho" + elif num == 29: + return "veintinueve" + elif num == 30: + return "treinta" + elif num == 31: + if turno: + return "treintayuno" + else: + return "treintayun" + elif num == 32: + return "treintaydos" + elif num == 33: + return "treintaytres" + elif num == 34: + return "treintaycuatro" + elif num == 35: + return "treintaycinco" + elif num == 36: + return "treintayseis" + elif num == 37: + return "treintaysiete" + elif num == 38: + return "treintayocho" + elif num == 39: + return "treintaynueve" + elif num == 40: + return "cuarenta" + elif num == 41: + if turno: + return "cuarentayuno" + else: + return "cuarentayun" + elif num == 42: + return "cuarentaydos" + elif num == 43: + return "cuarentaytres" + elif num == 44: + return "cuarentaycuatro" + elif num == 45: + return "cuarentaycinco" + elif num == 46: + return "cuarentayseis" + elif num == 47: + return "cuarentaysiete" + elif num == 48: + return "cuarentayocho" + elif num == 49: + return "cuarentaynueve" + elif num == 50: + return "cinquenta" + elif num == 51: + if turno: + return "cinquentayuno" + else: + return "cinquentayun" + elif num == 52: + return "cinquentaydos" + elif num == 53: + return "cinquentaytres" + elif num == 54: + return "cinquentaycuatro" + elif num == 55: + return "cinquentaycinco" + elif num == 56: + return "cinquentayseis" + elif num == 57: + return "cinquentaysiete" + elif num == 58: + return "cinquentayocho" + elif num == 59: + return "cinquentaynueve" + elif num == 60: + return "sesenta" + elif num == 61: + if turno: + return "sesentayuno" + else: + return "sesentayun" + elif num == 62: + return "sesentaydos" + elif num == 63: + return "sesentaytres" + elif num == 64: + return "sesentaycuatro" + elif num == 65: + return "sesentaycinco" + elif num == 66: + return "sesentayseis" + elif num == 67: + return "sesentaysiete" + elif num == 68: + return "sesentayocho" + elif num == 69: + return "sesentaynueve" + elif num == 70: + return "setenta" + elif num == 71: + if turno: + return "setentayuno" + else: + return "setentayun" + elif num == 72: + return "setentaydos" + elif num == 73: + return "setentaytres" + elif num == 74: + return "setentaycuatro" + elif num == 75: + return "setentaycinco" + elif num == 76: + return "setentayseis" + elif num == 77: + return "setentaysiete" + elif num == 78: + return "setentayocho" + elif num == 79: + return "setentaynueve" + elif num == 80: + return "ochenta" + elif num == 81: + if turno: + return "ochentayuno" + else: + return "ochentayun" + elif num == 82: + return "ochentaydos" + elif num == 83: + return "ochentaytres" + elif num == 84: + return "ochentaycuatro" + elif num == 85: + return "ochentaycinco" + elif num == 86: + return "ochentayseis" + elif num == 87: + return "ochentaysiete" + elif num == 88: + return "ochentayocho" + elif num == 89: + return "ochentaynueve" + elif num == 90: + return "noventa" + elif num == 91: + if turno: + return "noventayuno" + else: + return "noventayun" + elif num == 92: + return "noventaydos" + elif num == 93: + return "noventaytres" + elif num == 94: + return "noventaycuatro" + elif num == 95: + return "noventaycinco" + elif num == 96: + return "noventayseis" + elif num == 97: + return "noventaysiete" + elif num == 98: + return "noventayocho" + elif num == 99: + return "noventaynueve" + elif num == 100: + return "cien" diff --git a/src/othello/utils.pyc b/src/othello/utils.pyc Binary files differnew file mode 100644 index 0000000..1878b4e --- /dev/null +++ b/src/othello/utils.pyc diff --git a/src/resources/__init__.py b/src/resources/__init__.py new file mode 100755 index 0000000..c1340a1 --- /dev/null +++ b/src/resources/__init__.py @@ -0,0 +1,7 @@ +import sys, os
+
+if __name__ == "__main__":
+ print sys.path
+ print os.getcwd()
+ print os.path.abspath('../../resources/fonts/font.ttf')
+
\ No newline at end of file diff --git a/src/resources/__init__.pyc b/src/resources/__init__.pyc Binary files differnew file mode 100644 index 0000000..3912ba3 --- /dev/null +++ b/src/resources/__init__.pyc diff --git a/src/resources/fonts.py b/src/resources/fonts.py new file mode 100755 index 0000000..c8fcaf9 --- /dev/null +++ b/src/resources/fonts.py @@ -0,0 +1,12 @@ +import os
+
+class Fonts:
+ #Variables de clase
+ __file_names = {}
+
+ #Nombre de los archivos de fuentes
+ __file_names['fuente1'] = 'resources/fonts/font.ttf'
+
+ @staticmethod
+ def get_fonts_file_names():
+ return Fonts.__file_names
\ No newline at end of file diff --git a/src/resources/fonts.pyc b/src/resources/fonts.pyc Binary files differnew file mode 100644 index 0000000..d16133c --- /dev/null +++ b/src/resources/fonts.pyc diff --git a/src/resources/images.py b/src/resources/images.py new file mode 100755 index 0000000..0a7c015 --- /dev/null +++ b/src/resources/images.py @@ -0,0 +1,142 @@ +from main.constants import RESOLUTION1, RESOLUTION2
+
+class Images:
+ #Variables de clase
+ __file_names_r1= {}
+ __file_names_r2 = {}
+
+ #Nombre de los archivos de imagenes para la resolucion de 800x600
+ __file_names_r1['medallas'] = {'oro':{'archivo' : 'resources/images/medals/800x600/medal_gold_00.png', 'pos_xy' : (210,66)},
+ 'plata': {'archivo' : 'resources/images/medals/800x600/medal_silver_00.png', 'pos_xy' : (210,66)},
+ 'bronze': {'archivo' : 'resources/images/medals/800x600/medal_bronze_00.png', 'pos_xy' : (210,66)}}
+ __file_names_r1['trofeos'] = {'oro':{'archivo' : 'resources/images/trophies/800x600/trophy_gold_00.png', 'pos_xy' : (210,40)},
+ 'marfil': {'archivo' : 'resources/images/trophies/800x600/trophy_ivory_00.png', 'pos_xy' : (210,40)},
+ 'madera': {'archivo' : 'resources/images/trophies/800x600/trophy_wood_00.png', 'pos_xy' : (210,40)}}
+ __file_names_r1['tablero'] = {'celda_vacia' : 'resources/images/board/800x600/cell_inside_00.png',
+ 'borde_horizontal' : 'resources/images/board/800x600/board_hframe_00.png',
+ 'borde_vertical' : 'resources/images/board/800x600/board_vframe_00.png',
+ 'marca' : 'resources/images/board/800x600/mark_00.png'}
+ __file_names_r1['animacion_celda'] = {'chica' : 'resources/images/board/800x600/cell_inside_01.png',
+ 'mediana' : 'resources/images/board/800x600/cell_inside_02.png',
+ 'grande' : 'resources/images/board/800x600/cell_inside_03.png'}
+ __file_names_r1['piezas'] = {'negra' : 'resources/images/pieces/800x600/token_black_00.png',
+ 'blanca' : 'resources/images/pieces/800x600/token_white_00.png'}
+ __file_names_r1['etc'] = {'caja_texto' : 'resources/images/etc/800x600/textbox_00.png',
+ 'asc_botones' : {'archivo' : 'resources/images/etc/800x600/elevbutton_00.png', 'pos_xy' : (213,166)},
+ 'asc_botones_sel' : {'archivo' : 'resources/images/etc/800x600/elevbutton_01.png' , 'pos_xy' : (213,166)},
+ 'logo' : {'archivo' : 'resources/images/etc/800x600/logo.png' , 'pos_xy' : (213,166)}}
+ __file_names_r1['marcador'] = {'barra_negra' : 'resources/images/etc/800x600/player_bar_01.png',
+ 'barra_amarilla' : 'resources/images/etc/800x600/player_bar_00.png',
+ 'bandera_negra' : 'resources/images/etc/800x600/flag_black_00.png',
+ 'bandera_blanca' : 'resources/images/etc/800x600/flag_white_00.png'}
+ __file_names_r1['habitaciones'] = {'entrada' : 'resources/images/backgrounds/800x600/room_outdoors_00.png',
+ 'primer piso' : 'resources/images/backgrounds/800x600/room_floor0_00.png',
+ 'salon de clases' : 'resources/images/backgrounds/800x600/room_class_00.png',
+ 'secretaria' : 'resources/images/backgrounds/800x600/room_office_00.png',
+ 'segundo piso' : 'resources/images/backgrounds/800x600/room_floor1_00.png',
+ 'salon de desafios' : 'resources/images/backgrounds/800x600/room_challenge_00.png',
+ 'salon de encuentros' : 'resources/images/backgrounds/800x600/room_versus_00.png',
+ 'tercer piso' : 'resources/images/backgrounds/800x600/room_floor2_00.png',
+ 'habitacion pedro madera' : 'resources/images/backgrounds/800x600/room_pm_00.png',
+ 'habitacion sofia dulce' : 'resources/images/backgrounds/800x600/room_sd_00.png',
+ 'cuarto piso' : 'resources/images/backgrounds/800x600/room_floor3_00.png',
+ 'habitacion presidente' : 'resources/images/backgrounds/800x600/room_pt_00.png'}
+ __file_names_r1['puertas'] = {'ascensor' : {'archivo' : 'resources/images/etc/800x600/elevator_00.png', 'pos_xy' : (298,60)},
+ 'asc_subida' : {'archivo' : 'resources/images/etc/800x600/elevator_01.png', 'pos_xy' : (298,60)},
+ 'asc_bajada' : {'archivo' : 'resources/images/etc/800x600/elevator_02.png', 'pos_xy' : (298,60)},
+ 'salon de clases' : {'archivo' : 'resources/images/doors/800x600/door_class_00.png','pos_xy' : (18,26)},
+ 'salon de clases sel' : {'archivo' : 'resources/images/doors/800x600/door_class_01.png', 'pos_xy' : (18,26)},
+ 'secretaria' : {'archivo' : 'resources/images/doors/800x600/door_office_00.png', 'pos_xy' : (710,26)},
+ 'secretaria sel' : {'archivo' : 'resources/images/doors/800x600/door_office_01.png', 'pos_xy' : (710,26)},
+ 'salon de desafios' : {'archivo' : 'resources/images/doors/800x600/door_challenge_00.png', 'pos_xy' : (18,26)},
+ 'salon de desafios sel' : {'archivo' : 'resources/images/doors/800x600/door_challenge_01.png', 'pos_xy': (18,26)},
+ 'salon de encuentros' : {'archivo' : 'resources/images/doors/800x600/door_versus_00.png', 'pos_xy' : (710,26)},
+ 'salon de encuentros sel' : {'archivo' : 'resources/images/doors/800x600/door_versus_01.png', 'pos_xy' : (710,26)},
+ 'habitacion pedro madera' : {'archivo' : 'resources/images/doors/800x600/door_pm_00.png', 'pos_xy' : (18,26)},
+ 'habitacion pedro madera sel' : {'archivo' : 'resources/images/doors/800x600/door_pm_01.png', 'pos_xy' : (18,26)},
+ 'habitacion sofia dulce' : {'archivo' : 'resources/images/doors/800x600/door_sd_00.png', 'pos_xy' : (710,26)},
+ 'habitacion sofia dulce sel' : {'archivo' : 'resources/images/doors/800x600/door_sd_01.png', 'pos_xy' : (710,26)},
+ 'habitacion presidente' : {'archivo' : 'resources/images/doors/800x600/door_pt_00.png', 'pos_xy' : (710,26)},
+ 'habitacion presidente sel' : {'archivo' : 'resources/images/doors/800x600/door_pt_01.png', 'pos_xy' : (710,26)}}
+ __file_names_r1['personajes'] = {'pablo gris' : {'archivo' : 'resources/images/characters/800x600/char_pg_00.png', 'pos_xy' : (79,33), 'pos_xy_f' : (453,34), 'pos_xy_end':(120,50)},
+ 'don cano' : {'archivo' : 'resources/images/characters/800x600/char_dc_00.png', 'pos_xy' : (26,36), 'pos_xy_end':(26,36)},
+ 'pedro madera' : {'archivo' : 'resources/images/characters/800x600/char_pm_00.png', 'pos_xy' : (473,110), 'pos_xy_f' : (500,96), 'pos_xy_end':(500,36)},
+ 'sofia dulce' : {'archivo' : 'resources/images/characters/800x600/char_sd_00.png', 'pos_xy' : (523,56), 'pos_xy_f' : (470,70), 'pos_xy_end':(370,36)},
+ 'protasio' : {'archivo' : 'resources/images/characters/800x600/char_pt_00.png', 'pos_xy' : (546,100), 'pos_xy_end':(220,36)}}
+ #Nombre de los archivos de imagenes para la resolucion de 1200x900
+ __file_names_r2['medallas'] = {'oro':{'archivo' : 'resources/images/medals/1200x900/medal_gold_00.png', 'pos_xy' : (300,100)},
+ 'plata':{'archivo' : 'resources/images/medals/1200x900/medal_silver_00.png', 'pos_xy' : (300,100)},
+ 'bronze': {'archivo' : 'resources/images/medals/1200x900/medal_bronze_00.png', 'pos_xy' : (300,100)}}
+ __file_names_r2['trofeos'] = {'oro':{'archivo' : 'resources/images/trophies/1200x900/trophy_gold_00.png', 'pos_xy' : (300,60)},
+ 'marfil': {'archivo' : 'resources/images/trophies/1200x900/trophy_ivory_00.png', 'pos_xy' : (300,60)},
+ 'madera': {'archivo' : 'resources/images/trophies/1200x900/trophy_wood_00.png', 'pos_xy' : (300,60)}}
+ __file_names_r2['tablero'] = {'celda_vacia' : 'resources/images/board/1200x900/cell_inside_00.png',
+ 'borde_horizontal' : 'resources/images/board/1200x900/board_hframe_00.png',
+ 'borde_vertical' : 'resources/images/board/1200x900/board_vframe_00.png',
+ 'marca' : 'resources/images/board/1200x900/mark_00.png'}
+ __file_names_r2['animacion_celda'] = {'chica' : 'resources/images/board/1200x900/cell_inside_01.png',
+ 'mediana' : 'resources/images/board/1200x900/cell_inside_02.png',
+ 'grande' : 'resources/images/board/1200x900/cell_inside_03.png'}
+ __file_names_r2['piezas'] = {'negra' : 'resources/images/pieces/1200x900/token_black_00.png',
+ 'blanca' : 'resources/images/pieces/1200x900/token_white_00.png'}
+ __file_names_r2['etc'] = {'caja_texto' : 'resources/images/etc/1200x900/textbox_00.png',
+ 'asc_botones' : {'archivo' : 'resources/images/etc/1200x900/elevbutton_00.png', 'pos_xy' : (320,250)},
+ 'asc_botones_sel' : {'archivo' : 'resources/images/etc/1200x900/elevbutton_01.png' , 'pos_xy' : (320,250)},
+ 'logo' : {'archivo' : 'resources/images/etc/1200x900/logo.png' , 'pos_xy' : (320,250)}}
+ __file_names_r2['marcador'] = {'barra_negra' : 'resources/images/etc/1200x900/player_bar_01.png',
+ 'barra_amarilla' : 'resources/images/etc/1200x900/player_bar_00.png',
+ 'bandera_negra' : 'resources/images/etc/1200x900/flag_black_00.png',
+ 'bandera_blanca' : 'resources/images/etc/1200x900/flag_white_00.png'}
+ __file_names_r2['habitaciones'] = {'entrada' : 'resources/images/backgrounds/1200x900/room_outdoors_00.png',
+ 'primer piso' : 'resources/images/backgrounds/1200x900/room_floor0_00.png',
+ 'salon de clases' : 'resources/images/backgrounds/1200x900/room_class_00.png',
+ 'secretaria' : 'resources/images/backgrounds/1200x900/room_office_00.png',
+ 'segundo piso' : 'resources/images/backgrounds/1200x900/room_floor1_00.png',
+ 'salon de desafios' : 'resources/images/backgrounds/1200x900/room_challenge_00.png',
+ 'salon de encuentros' : 'resources/images/backgrounds/1200x900/room_versus_00.png',
+ 'tercer piso' : 'resources/images/backgrounds/1200x900/room_floor2_00.png',
+ 'habitacion pedro madera' : 'resources/images/backgrounds/1200x900/room_pm_00.png',
+ 'habitacion sofia dulce' : 'resources/images/backgrounds/1200x900/room_sd_00.png',
+ 'cuarto piso' : 'resources/images/backgrounds/1200x900/room_floor3_00.png',
+ 'habitacion presidente' : 'resources/images/backgrounds/1200x900/room_pt_00.png'}
+ __file_names_r2['puertas'] = {'ascensor' : {'archivo' : 'resources/images/etc/1200x900/elevator_00.png', 'pos_xy' : (447,90)},
+ 'asc_subida' : {'archivo' : 'resources/images/etc/1200x900/elevator_01.png', 'pos_xy' : (447,90)},
+ 'asc_bajada' : {'archivo' : 'resources/images/etc/1200x900/elevator_02.png', 'pos_xy' : (447,90)},
+ 'salon de clases' : {'archivo' : 'resources/images/doors/1200x900/door_class_00.png','pos_xy' : (27,40)},
+ 'salon de clases sel' : {'archivo' : 'resources/images/doors/1200x900/door_class_01.png', 'pos_xy' : (27,40)},
+ 'secretaria' : {'archivo' : 'resources/images/doors/1200x900/door_office_00.png', 'pos_xy' : (1060,40)},
+ 'secretaria sel' : {'archivo' : 'resources/images/doors/1200x900/door_office_01.png', 'pos_xy' : (1060,40)},
+ 'salon de desafios' : {'archivo' : 'resources/images/doors/1200x900/door_challenge_00.png', 'pos_xy' : (27,40)},
+ 'salon de desafios sel' : {'archivo' : 'resources/images/doors/1200x900/door_challenge_01.png', 'pos_xy': (27,40)},
+ 'salon de encuentros' : {'archivo' : 'resources/images/doors/1200x900/door_versus_00.png', 'pos_xy' : (1060,40)},
+ 'salon de encuentros sel' : {'archivo' : 'resources/images/doors/1200x900/door_versus_01.png', 'pos_xy' : (1060,40)},
+ 'habitacion pedro madera' : {'archivo' : 'resources/images/doors/1200x900/door_pm_00.png', 'pos_xy' : (27,40)},
+ 'habitacion pedro madera sel' : {'archivo' : 'resources/images/doors/1200x900/door_pm_01.png', 'pos_xy' : (27,40)},
+ 'habitacion sofia dulce' : {'archivo' : 'resources/images/doors/1200x900/door_sd_00.png', 'pos_xy' : (1060,40)},
+ 'habitacion sofia dulce sel' : {'archivo' : 'resources/images/doors/1200x900/door_sd_01.png', 'pos_xy' : (1060,40)},
+ 'habitacion presidente' : {'archivo' : 'resources/images/doors/1200x900/door_pt_00.png', 'pos_xy' : (1060,40)},
+ 'habitacion presidente sel' : {'archivo' : 'resources/images/doors/1200x900/door_pt_01.png', 'pos_xy' : (1060,40)}}
+ __file_names_r2['personajes'] = {'pablo gris' : {'archivo' : 'resources/images/characters/1200x900/char_pg_00.png', 'pos_xy' : (110,50), 'pos_xy_f' : (680,52), 'pos_xy_end':(180,75)},
+ 'don cano' : {'archivo' : 'resources/images/characters/1200x900/char_dc_00.png', 'pos_xy' : (40,55), 'pos_xy_end':(40,55)},
+ 'pedro madera' : {'archivo' : 'resources/images/characters/1200x900/char_pm_00.png', 'pos_xy' : (770,165), 'pos_xy_f' : (750,145), 'pos_xy_end':(750,55)},
+ 'sofia dulce' : {'archivo' : 'resources/images/characters/1200x900/char_sd_00.png', 'pos_xy' : (785,85), 'pos_xy_f' : (705,105), 'pos_xy_end':(555,55)},
+ 'protasio' : {'archivo' : 'resources/images/characters/1200x900/char_pt_00.png', 'pos_xy' : (820,150), 'pos_xy_end':(330,55)}}
+
+ @staticmethod
+ def get_images_file_names(resolucion=(800,600),tipo_imagen=""):
+ try:
+ if resolucion == RESOLUTION1:
+ if tipo_imagen != "":
+ return Images.__file_names_r1[tipo_imagen]
+ else:
+ return Images.__file_names_r1
+ elif resolucion == RESOLUTION2:
+ if tipo_imagen != "":
+ return Images.__file_names_r2[tipo_imagen]
+ else:
+ return Images.__file_names_r2
+ else:
+ raise Exception("Resolucion desconocida (Images Class)")
+ except:
+ raise Exception("Problemas al retornar imagen (Images Class)")
+
diff --git a/src/resources/images.pyc b/src/resources/images.pyc Binary files differnew file mode 100644 index 0000000..190ad6a --- /dev/null +++ b/src/resources/images.pyc diff --git a/src/resources/sounds.py b/src/resources/sounds.py new file mode 100755 index 0000000..dad530a --- /dev/null +++ b/src/resources/sounds.py @@ -0,0 +1,20 @@ +import os
+from _xml.parser import Parser
+
+class Sounds:
+ def __init__(self, main_path):
+ self.__main_path = main_path
+
+ def set_main_path(self, path):
+ self.__main_path = path
+
+ def get_sound_file_name(self, categoria="",tipo="",nombre=""):
+ self.__f = open(os.path.abspath(self.__main_path + "/data/resources.xml"))
+ self.__parser = Parser()
+ attrs = {'type' : tipo, 'name' : nombre}
+ elemento = self.__parser.find_element_attribute(categoria,attrs,self.__f)
+ if elemento.is_empty():
+ raise Exception("No se encontro el elemento en el archivo XML (Sounds Class)")
+ self.__f.close()
+ self.__parser.close()
+ return os.path.abspath(self.__main_path+elemento.get_text('str'))
diff --git a/src/resources/sounds.pyc b/src/resources/sounds.pyc Binary files differnew file mode 100644 index 0000000..f8b93f4 --- /dev/null +++ b/src/resources/sounds.pyc |