def __init__(self, parent):
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/contest.glade'))
        
        self.contest_dialog = builder.get_object("contest_dialog")
        self.contest_dialog.set_transient_for(parent)

        self.files = {}
        self.teams = {}

        #---------------------------
        self.cName = 0
        self.cRules = 1
        self.cFormation = 2
        
        self.sName = _("Name")
        self.sRules = _("Rules")
        self.sFormation = _("Formation")
        
        self.list_view = builder.get_object("list_es_view")
        self.list_view.set_reorderable(False)

        self.addColumn(self.sName, self.cName)
        self.addColumn(self.sRules, self.cRules)
        self.addColumn(self.sFormation, self.cFormation)

        self.list_store = builder.get_object("list_expert_system")
        #-----------------------------

        self.file_chooser_rules = builder.get_object('file_chooser_rules')
        #self.file_chooser_rules.set_transient_for(self.players_selector)
        self.file_chooser_formation = builder.get_object('file_chooser_formation')
        #self.file_chooser_formation.set_transient_for(self.players_selector)

        self.format_contest = 'league'
        self.radio_league = builder.get_object('radio_league')
        self.radio_cup = builder.get_object('radio_cup')
        self.radio_groups = builder.get_object('radio_groups')
        self.radio_playoff = builder.get_object('radio_playoff')
        self.check_backround = builder.get_object('check_backround')
        self.check_fast = builder.get_object('check_onlyresults')

        self.back_round = False
        self.fast = False
        self.all_teams = False
        
        def_path = configure.load_configuration()['se_path']
        self.file_chooser_rules.set_current_folder(def_path + '/rules')
        self.file_chooser_formation.set_current_folder(def_path + '/formations')

        self.start_button = builder.get_object('btn_start')
        self.frame_selection_teams = builder.get_object('box_selection')
        
        self.num_turns = 120
        self.spin_turns = builder.get_object("spin_num_turns")
        self.spin_turns.set_range(50,300)
        self.spin_turns.set_increments(2,10)
        self.spin_turns.set_value(self.num_turns)
        
        builder.connect_signals(self)
示例#2
0
 def on_file_chs_se_file_set(self, widget, data=None):
     if (self.comprobarDirectorios()):
         mensaje = _("<b>Correct directory</b>")
         mensaje += "\n    <b>" + _("Rules") + "</b>: %s" % os.path.join(widget.get_filename(), "rules")
         mensaje += "\n    <b>" + _("Teams") + "</b>: %s" % os.path.join(widget.get_filename(), "formations")
         self.label_subfolders.set_markup(mensaje)
     else:
         self.label_subfolders.set_markup("<span foreground=\"red\" weight=\"bold\">" + _("Invalid directory") + "</span>")
示例#3
0
def init_contest(contest_format, teams, fast=False, back_round=False,
                 num_turns=120):

    logging.info("#### INIT CONTEST")

    teams = _clean_dictionary(teams)

    progress_bar = pbs.ProgressBarDialog(None, _('Checking teams...'))
    progress_bar_dialog = progress_bar.progress_bar_dialog
    progress_bar.set_num_elements(len(teams))
    progress_bar_dialog.show()

    while gtk.events_pending():
        gtk.main_iteration(False)    

    bannedTeams = []
    for equipo in teams:
        logging.info("Probando equipo: %s", equipo)

        if (not filenames.comprobar_nombre_reglas(equipo[0]) or 
            not filenames.comprobar_nombre_formacion(equipo[1])):
            bannedTeams.append(equipo)
            logging.warning("Equipo baneado: %s", equipo)
            continue

        try:
            probar_equipo(equipo)
        except:
            progress_bar_dialog.hide()
            notificacion = notify_result.SimpleNotify(_("The rules file <b>\"%s\"</b> has errors. This team will be out of the competition.\n\nCheck \"<i>log_gsiege</i>\" log file for details.") % equipo[0])
            notificacion.dlg_result.run()
            progress_bar_dialog.show()
            bannedTeams.append(equipo)
            
        progress_bar.pulse()
        
        while gtk.events_pending():
            gtk.main_iteration(False)    

    progress_bar_dialog.hide()

    for t in bannedTeams:
        teams.remove(t)

    controlPartida.restaurarCampeonato()

    if len(teams) > 1:
        if contest_format == 'playoff':
            _init_playoff(teams, fast, num_turns, back_round)
        else:
            _init_game(contest_format, teams, fast, num_turns, back_round)
    else:
         notificacion = notify_result.SimpleNotify(_("Not enough teams to hold the competition. Aborting."))
         notificacion.dlg_result.run()

    logging.info("#### END CONTEST")
 def fill_results(self):
     for e in self.results:
         teamA = e[0][0].replace('aux_ghost_team', _('Rests'))
         teamB = e[0][1].replace('aux_ghost_team', _('Rests'))
         win_color = '#0C0C9D'
         draw_color = '#5DEA5D'
         if e[1] == 1:
             teamA = _draw_string(teamA, win_color)
         elif e[1] == -1:
             teamB = _draw_string(teamB, win_color)
         else: #draw
             teamA = _draw_string(teamA, draw_color)
             teamB = _draw_string(teamB, draw_color)
         self.list_store_results.append((teamA, teamB))
示例#5
0
def _init_league(teams, fast, num_turns, back_round):
    l = league.League(teams, num_turns, back_round)

    band = False
    
    while not l.league_completed and not band:
        i = l.get_round_number()
        progress_bar = None
        if fast:
            progress_bar = pbs.ProgressBarDialog(None,
                                                 _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(l.get_round(i).number_games)
            progress_bar_dialog.show()
            while gtk.events_pending():
                gtk.main_iteration(False)
        l.play_round(progress_bar, fast)
        r = l.get_round(i)
        
        classifications = l.get_actual_puntuations()
        results = r.get_round_results()
        
        R = round_results.roundResults(classifications, results,
                                       l.get_prev_round_number() + 1,
                                       l.get_number_of_rounds())
        if fast:
            progress_bar_dialog.hide()
        button_pressed = R.result_dialog.run()
        
        while gtk.events_pending():
            gtk.main_iteration(False)
            
        if button_pressed == -4 or button_pressed == 0:
            band = True
示例#6
0
def _init_tournament(teams, num_turns, fast):
    t = tournament.Tournament(teams, num_turns)
    band = False
    
    while not t.tournament_completed and not band:
        i = t.get_round_number()
        progress_bar = None
        if fast:
            progress_bar = pbs.ProgressBarDialog(None,
                                                 _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(t.get_round(i).number_games)
            progress_bar_dialog.show()
            while gtk.events_pending():
                gtk.main_iteration(False)
        t.play_round(progress_bar, fast)
        r = t.get_round(i)

        classifications = []
        results = r.get_round_results()
        
        R = round_results.roundResults(classifications, results,
                                       t.get_prev_round_number() + 1,
                                       t.get_number_of_rounds(),
                                       show_classifications=False)
        if fast:
            progress_bar_dialog.hide()
        button_pressed = R.result_dialog.run()
        
        while gtk.events_pending():
            gtk.main_iteration(False)
            
        if button_pressed == -4 or button_pressed == 0:
            band = True
    print teams
示例#7
0
    def __init__(self, main_team, teams, rounds_number, num_turns):
        self.main_team = main_team
        self.teams = teams
        self.num_turns = num_turns
        
        self.translator_teams = _generate_key_names(teams)
        self.translator_main_team = _generate_key_names([main_team])

        self.keys_teams = []
        self.key_main_team = []

        self.rounds_number = rounds_number

        base_path = configure.load_configuration()['games_path'] + '/'
        base_path += filenames.generate_filename('labdir', main_team) +'/'

        os.mkdir(base_path)

        

        self.filename = base_path + filenames.generate_filename('stats',
                                                                main_team)

        
        for _team in self.translator_teams:
            self.keys_teams.append(_team)

        for _team in self.translator_main_team:
            self.key_main_team.append(_team)

        self.translator = self.translator_teams.copy()
        for k in self.translator_main_team:
            self.translator[k] = self.translator_main_team[k]

        self.rounds = []
        stats_writer = csv.writer(open(self.filename, 'w'), delimiter=',',
                                  quotechar='|', quoting=csv.QUOTE_MINIMAL)
        stats_writer.writerow([_('Opponent'), _('As team'),
                               _('Result'), _("Number of turns"),
                               _('Number of pieces'), _("Value of the pieces"),
                               _('Turn when max value piece died')])

        for i in range(self.rounds_number):
            round_games = pairing.test_pairing(self.key_main_team[0],
                                               self.keys_teams, i%2)
            self.rounds.append(test_round.TestRound((round_games,
                                                    self.translator),
                                                    num_turns = self.num_turns,
                                                    log_file=self.filename,
                                                    player=i%2, logFolder = base_path))

        self.total_stats = {}
        self.total_stats['wins'] = 0
        self.total_stats['looses'] = 0
        self.total_stats['draws'] = 0
        self.total_stats['turns_winning'] = 0
        self.total_stats['turns_losing'] = 0
        self.total_stats['num_pieces'] = 0
        self.total_stats['val_pieces'] = 0
        self.total_stats['max_death'] = 0
def cancelarCampeonato():
    mensajeDialogo = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO)

    mensajeDialogo.set_markup(_("<b>Cancel competition?</b>"))
    mensajeDialogo.format_secondary_markup(_("Are you sure to cancel the entire competition?"))
    respuesta = mensajeDialogo.run()
    mensajeDialogo.destroy()

    global flagCancelarCampeonato

    if respuesta == gtk.RESPONSE_YES:
        flagCancelarCampeonato = True
        logging.info("Cancelando campeonato...")
    else:
        flagCancelarCampeonato = False

    while gtk.events_pending():
        gtk.main_iteration(False)
示例#9
0
def comprobar_nombre_formacion (s):
    n, e = path.splitext(path.basename(s))

    if n[:6] != 'equipo' or e != '.form':
        errorMsg = _("The formation file <b>\"%s\"</b> is not properly formed. \n\nIt should have the following syntax: <i>equipo<b>Nombre</b>.form</i>, where <b>Nombre</b> is the name of the team.") % (n + e)
        notificacion = resistencia.gui.notify_result.SimpleNotify(errorMsg)
        notificacion.dlg_result.run()
        return False
    else:
        return True
    def __init__(self, teams, winner):
        name_teamA = teams[0]
        name_teamB = teams[1]
        
        result = ''
        
        if winner == 0:
            result = _('Draw')
        elif winner == 1:
            result = _('Wins ') + name_teamA
        else:
            result = _('Gana ') + name_teamB
            
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/resultNotifier.glade'))

        self.dlg_result = builder.get_object('dlg_result')
        self.dlg_result.connect('response', lambda d, r: d.hide())
        self.dlg_result.format_secondary_text(result)
def cancelarCampeonato():
    mensajeDialogo = gtk.MessageDialog(None, gtk.DIALOG_MODAL,
                                       gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO)

    mensajeDialogo.set_markup(_("<b>Cancel competition?</b>"))
    mensajeDialogo.format_secondary_markup(
        _("Are you sure to cancel the entire competition?"))
    respuesta = mensajeDialogo.run()
    mensajeDialogo.destroy()

    global flagCancelarCampeonato

    if respuesta == gtk.RESPONSE_YES:
        flagCancelarCampeonato = True
        logging.info("Cancelando campeonato...")
    else:
        flagCancelarCampeonato = False

    while gtk.events_pending():
        gtk.main_iteration(False)
示例#12
0
def comprobar_nombre_formacion(s):
    n, e = path.splitext(path.basename(s))

    if n[:6] != 'equipo' or e != '.form':
        errorMsg = _(
            "The formation file <b>\"%s\"</b> is not properly formed. \n\nIt should have the following syntax: <i>equipo<b>Nombre</b>.form</i>, where <b>Nombre</b> is the name of the team."
        ) % (n + e)
        notificacion = resistencia.gui.notify_result.SimpleNotify(errorMsg)
        notificacion.dlg_result.run()
        return False
    else:
        return True
    def fill_results(self):
        for e in self.results:
            teamA = e[0][0].replace('aux_ghost_team', _('Rests'))
            teamB = e[0][1].replace('aux_ghost_team', _('Rests'))
            win_color = '#0C0C9D'
            draw_color = '#5DEA5D'

            if e[2] == "normal":
                reason = _("King died")
            elif e[2] == "puntos":
                reason = _("Number of points")
            elif e[2] == "piezas":
                reason = _("Number of pieces")
            else:
                reason = _("Can't handle draw, team B wins")

            if e[0][0] == "aux_ghost_team":
                teamA = _draw_string(teamA, win_color)
            elif e[0][1] == "aux_ghost_team":
                teamB = _draw_string(teamB, win_color)
            elif e[1] == 1:
                teamA = _draw_string(teamA, win_color)
            elif e[1] == -1:
                teamB = _draw_string(teamB, win_color)
            else:  #draw
                teamA = _draw_string(teamA, draw_color)
                teamB = _draw_string(teamB, draw_color)
                reason = "-"

            self.list_store_results.append((teamA, teamB, reason))
    def fill_results(self):
        for e in self.results:
            teamA = e[0][0].replace('aux_ghost_team', _('Rests'))
            teamB = e[0][1].replace('aux_ghost_team', _('Rests'))
            win_color = '#0C0C9D'
            draw_color = '#5DEA5D'

            if e[2] == "normal":
                reason = _("King died")
            elif e[2] == "puntos":
                reason = _("Number of points")
            elif e[2] == "piezas":
                reason = _("Number of pieces")
            else:
                reason = _("Can't handle draw, team B wins")

            if e[0][0] == "aux_ghost_team":
                teamA = _draw_string(teamA, win_color)
            elif e[0][1] == "aux_ghost_team":
                teamB = _draw_string(teamB, win_color)
            elif e[1] == 1:
                teamA = _draw_string(teamA, win_color)
            elif e[1] == -1:
                teamB = _draw_string(teamB, win_color)
            else: #draw
                teamA = _draw_string(teamA, draw_color)
                teamB = _draw_string(teamB, draw_color)
                reason = "-"

            self.list_store_results.append((teamA, teamB, reason))
    def load_board(self):
        controlPartida.restaurarCampeonato()

        ambosEquipos = [(self.es_team_a, self.team_team_a), (self.es_team_b, self.team_team_b)]
        
        for equipo in ambosEquipos:
            if (not filenames.comprobar_nombre_reglas(equipo[0]) or 
                not filenames.comprobar_nombre_formacion(equipo[1])):

                return

            logging.info("Probando equipo: %s", equipo)
            try:
                probar_equipo(equipo)
            except Exception as e:
                #progress_bar_dialog.hide()
                logging.error("Algo ha fallado")
                logging.error(e)
                notificacion = notify_result.SimpleNotify(_("The rules file <b>\"%s\"</b> has errors. This quick game will be cancelled.\n\nCheck \"<i>log_gsiege</i>\" log file for details.") % equipo[0])
                notificacion.dlg_result.run()
                #progress_bar_dialog.show()

                return
            logging.info("Equipo probado")

        try:
            winner,kk = guada_board.run(
                ((self.es_team_a, self.team_team_a),
                 xdg.get_data_path('images/piece-orange.png')),
                ((self.es_team_b,self.team_team_b),
                 xdg.get_data_path('images/piece-violete.png')),

                self.fast_game, 
                self.dont_save_game,
                self.hidde_values, 
                str(int(self.num_turns))
                )
        except guada_board.GuadaFileError as e:
            raise guada_board.GuadaFileError(e.msg)
        
        # Se ha seleccionado mostrar sólo los resultados
        if self.fast_game:
            teamA = (self.es_team_a, self.team_team_a)
            teamB = (self.es_team_b, self.team_team_b)

            n = notify_result.notifyResult((teamA, teamB), winner)
            
            n.dlg_result.run()
    def load_board(self):
        controlPartida.restaurarCampeonato()

        ambosEquipos = [(self.es_team_a, self.team_team_a),
                        (self.es_team_b, self.team_team_b)]

        for equipo in ambosEquipos:
            if (not filenames.comprobar_nombre_reglas(equipo[0])
                    or not filenames.comprobar_nombre_formacion(equipo[1])):

                return

            logging.info("Probando equipo: %s", equipo)
            try:
                probar_equipo(equipo)
            except Exception as e:
                #progress_bar_dialog.hide()
                logging.error("Algo ha fallado")
                logging.error(e)
                notificacion = notify_result.SimpleNotify(
                    _("The rules file <b>\"%s\"</b> has errors. This quick game will be cancelled.\n\nCheck \"<i>log_gsiege</i>\" log file for details."
                      ) % equipo[0])
                notificacion.dlg_result.run()
                #progress_bar_dialog.show()

                return
            logging.info("Equipo probado")

        try:
            winner, kk = guada_board.run(
                ((self.es_team_a, self.team_team_a),
                 xdg.get_data_path('images/piece-orange.png')),
                ((self.es_team_b, self.team_team_b),
                 xdg.get_data_path('images/piece-violete.png')),
                self.fast_game, self.dont_save_game, self.hidde_values,
                str(int(self.num_turns)))
        except guada_board.GuadaFileError as e:
            raise guada_board.GuadaFileError(e.msg)

        # Se ha seleccionado mostrar sólo los resultados
        if self.fast_game:
            teamA = (self.es_team_a, self.team_team_a)
            teamB = (self.es_team_b, self.team_team_b)

            n = notify_result.notifyResult((teamA, teamB), winner)

            n.dlg_result.run()
    def __init__(self, teams, winner):
        """ Genera un nuevo diálogo de notificación de resultados.

        teams será un par cuyos elementos pueden ser cadenas con el nombre del
        equipo o un par con la ruta del fichero de formación y de reglas, de los
        que sacarán los nombres.
        """

        result = ''

        if type(teams[0]) == str:
            msg_team_a = teams[0]
            msg_team_b = teams[1]
        else:

            team_a = filenames.quitar_prefijo_multiple(teams[0])
            team_b = filenames.quitar_prefijo_multiple(teams[1])
        
            msg_team = "equipo <b>%s</b> con formación <b>%s</b>"
            msg_team_a = msg_team % team_a
            msg_team_b = msg_team % team_b
        
        if winner == 0:
            result = '<span foreground="red"><b>' + _('Draw') + '</b></span>\n'
            result += msg_team_a + '\n' + msg_team_b
        elif winner == 1:
            result  = '<span foreground="red"><b>Ganador</b>: '
            result += msg_team_a 
            result += '</span>\n'
            result +=  "Contrincante: "  + msg_team_b
        else:
            result  = '<span foreground="red"><b>Ganador</b>: '
            result += msg_team_b
            result += '</span>\n'
            result +=  "Contrincante: "  + msg_team_a
            
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/resultNotifier.glade'))

        self.dlg_result = builder.get_object('dlg_result')
        self.dlg_result.connect('response', lambda d, r: d.hide())
        self.dlg_result.format_secondary_markup(result)
    def __init__(self, teams, winner):
        """ Genera un nuevo diálogo de notificación de resultados.

        teams será un par cuyos elementos pueden ser cadenas con el nombre del
        equipo o un par con la ruta del fichero de formación y de reglas, de los
        que sacarán los nombres.
        """

        result = ''

        if type(teams[0]) == str:
            msg_team_a = teams[0]
            msg_team_b = teams[1]
        else:

            team_a = filenames.quitar_prefijo_multiple(teams[0])
            team_b = filenames.quitar_prefijo_multiple(teams[1])

            msg_team = "equipo <b>%s</b> con formación <b>%s</b>"
            msg_team_a = msg_team % team_a
            msg_team_b = msg_team % team_b

        if winner == 0:
            result = '<span foreground="red"><b>' + _('Draw') + '</b></span>\n'
            result += msg_team_a + '\n' + msg_team_b
        elif winner == 1:
            result = '<span foreground="red"><b>Ganador</b>: '
            result += msg_team_a
            result += '</span>\n'
            result += "Contrincante: " + msg_team_b
        else:
            result = '<span foreground="red"><b>Ganador</b>: '
            result += msg_team_b
            result += '</span>\n'
            result += "Contrincante: " + msg_team_a

        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/resultNotifier.glade'))

        self.dlg_result = builder.get_object('dlg_result')
        self.dlg_result.connect('response', lambda d, r: d.hide())
        self.dlg_result.format_secondary_markup(result)
def leer_comentario(rutaFichero, wrap = True):
    try:
        fichero = open(rutaFichero, 'r')
    except IOError:
        return "ERROR"

    primeraLinea = fichero.readline().strip()
    # Un comentario válido será aquél cuya línea empiece con ; DOC: Lorem ipsum dillum...
    busqueda = re.match(r"^\s*;\s*DOC\s*:\s*(.*)$", primeraLinea)
    if busqueda:
        cadena = busqueda.group(1)

        if wrap:
            nuevaCadena = ""
            # Vamos a añadir un salto de línea cada X caracteres
            anchoMaximo = 40
            for i in range(0, len(cadena), anchoMaximo):
                nuevaCadena += cadena[i : i + anchoMaximo] + "\n"

            return nuevaCadena[:-1]
        else:
            return cadena

    return _("No comment")
def leer_comentario(rutaFichero, wrap=True):
    try:
        fichero = open(rutaFichero, 'r')
    except IOError:
        return "ERROR"

    primeraLinea = fichero.readline().strip()
    # Un comentario válido será aquél cuya línea empiece con ; DOC: Lorem ipsum dillum...
    busqueda = re.match(r"^\s*;\s*DOC\s*:\s*(.*)$", primeraLinea)
    if busqueda:
        cadena = busqueda.group(1)

        if wrap:
            nuevaCadena = ""
            # Vamos a añadir un salto de línea cada X caracteres
            anchoMaximo = 40
            for i in range(0, len(cadena), anchoMaximo):
                nuevaCadena += cadena[i:i + anchoMaximo] + "\n"

            return nuevaCadena[:-1]
        else:
            return cadena

    return _("No comment")
示例#21
0
    def __init__(self, parent):
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/contest.glade'))

        self.contest_dialog = builder.get_object("contest_dialog")
        self.contest_dialog.set_transient_for(parent)

        self.files = {}
        self.teams = {}

        #---------------------------
        self.cName = 0
        self.cRules = 1
        self.cFormation = 2

        self.sName = _("Name")
        self.sRules = _("Rules")
        self.sFormation = _("Formation")

        self.list_view = builder.get_object("list_es_view")
        self.list_view.set_reorderable(False)

        self.addColumn(self.sName, self.cName)
        self.addColumn(self.sRules, self.cRules)
        self.addColumn(self.sFormation, self.cFormation)
        self.addColumn(_("Description"), 3)

        self.list_store = builder.get_object("list_expert_system")
        #-----------------------------

        self.file_chooser_rules = builder.get_object('file_chooser_rules')
        #self.file_chooser_rules.set_transient_for(self.players_selector)
        self.file_chooser_formation = builder.get_object(
            'file_chooser_formation')
        #self.file_chooser_formation.set_transient_for(self.players_selector)

        self.format_contest = 'league'
        self.radio_league = builder.get_object('radio_league')
        self.radio_cup = builder.get_object('radio_cup')
        self.radio_groups = builder.get_object('radio_groups')
        self.radio_playoff = builder.get_object('radio_playoff')
        self.check_backround = builder.get_object('check_backround')
        self.check_fast = builder.get_object('check_onlyresults')

        self.back_round = False
        self.fast = False
        self.all_teams = False

        self.def_path = configure.load_configuration()['se_path']
        self.file_chooser_rules.set_current_folder(self.def_path + '/rules')
        self.file_chooser_formation.set_current_folder(self.def_path +
                                                       '/formations')

        self.start_button = builder.get_object('btn_start')
        self.frame_selection_teams = builder.get_object('box_selection')

        self.num_turns = 120
        self.spin_turns = builder.get_object("spin_num_turns")
        self.spin_turns.set_range(50, 300)
        self.spin_turns.set_increments(2, 10)
        self.spin_turns.set_value(self.num_turns)

        self.check_default_formations = builder.get_object(
            'check_default_formations')

        builder.connect_signals(self)
示例#22
0
def init_contest(contest_format,
                 teams,
                 fast=False,
                 back_round=False,
                 num_turns=120):

    logging.info("#### INIT CONTEST")

    teams = _clean_dictionary(teams)

    progress_bar = pbs.ProgressBarDialog(None, _('Checking teams...'))
    progress_bar_dialog = progress_bar.progress_bar_dialog
    progress_bar.set_num_elements(len(teams))
    progress_bar_dialog.show()

    while gtk.events_pending():
        gtk.main_iteration(False)

    bannedTeams = []
    for equipo in teams:
        logging.info("Probando equipo: %s", equipo)

        if (not filenames.comprobar_nombre_reglas(equipo[0])
                or not filenames.comprobar_nombre_formacion(equipo[1])):
            bannedTeams.append(equipo)
            logging.warning("Equipo baneado: %s", equipo)
            continue

        try:
            probar_equipo(equipo)
        except:
            progress_bar_dialog.hide()
            notificacion = notify_result.SimpleNotify(
                _("The rules file <b>\"%s\"</b> has errors. This team will be out of the competition.\n\nCheck \"<i>log_gsiege</i>\" log file for details."
                  ) % equipo[0])
            notificacion.dlg_result.run()
            progress_bar_dialog.show()
            bannedTeams.append(equipo)

        progress_bar.pulse()

        while gtk.events_pending():
            gtk.main_iteration(False)

    progress_bar_dialog.hide()

    for t in bannedTeams:
        teams.remove(t)

    controlPartida.restaurarCampeonato()

    if len(teams) > 1:
        if contest_format == 'playoff':
            _init_playoff(teams, fast, num_turns, back_round)
        else:
            _init_game(contest_format, teams, fast, num_turns, back_round)
    else:
        notificacion = notify_result.SimpleNotify(
            _("Not enough teams to hold the competition. Aborting."))
        notificacion.dlg_result.run()

    logging.info("#### END CONTEST")
    def __init__(self, classification, results, round, rounds,
                 show_classifications=True, show_top_teams=False): #add parent
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/results.glade'))

        self.classifications = classification
        self.results = results
        self.round = round
        self.rounds = rounds
        self.show_top_teams = show_top_teams

        self.result_dialog = builder.get_object('dlg_results')
        title = self.result_dialog.get_title()  + ' ' + str(round) + '/' + str(rounds)
        self.result_dialog.set_title(title)
        self.confirmation_dialog = builder.get_object('dlg_confirmation_close')
        self.confirmation_dialog.connect('response', lambda d, r: d.hide())
        self.confirmation_dialog.set_transient_for(self.result_dialog)
        self.finalround_dialog = builder.get_object('dlg_finalround')
        self.finalround_dialog.connect('response', lambda d, r: d.hide())
        self.finalround_dialog.set_transient_for(self.result_dialog)

        self.list_view_classifications = builder.get_object('treeview_classification')
        self.list_view_results = builder.get_object('treeview_results')

        if show_classifications:
            self.cPosition = 0
            self.cTeamName = 1
            self.cPuntuations = 2
        
            self.sPosition = 'Pos'
            self.sTeamName = _('Team name')
            self.sPuntuations = 'Punt'

            self.add_column(self.list_view_classifications,
                            self.sPosition, self.cPosition)
            self.add_column(self.list_view_classifications,
                            self.sTeamName, self.cTeamName)
            self.add_column(self.list_view_classifications,
                            self.sPuntuations, self.cPuntuations)

        self.list_store_classifications = builder.get_object('list_classification')
        if show_classifications:
            self.fill_classification()
        else:
            builder.get_object('hbox1').remove(builder.get_object('frame_classifications'))

        self.cTeamA = 0
        self.cTeamB = 1

        self.sTeamA = _('Team A')
        self.sTeamB = _('Team B')

        self.add_column(self.list_view_results, self.sTeamA, self.cTeamA)
        self.add_column(self.list_view_results, self.sTeamB, self.cTeamB)

        self.list_store_results = builder.get_object('list_results')
        self.fill_results()

        self.end_contest = False
        
        builder.connect_signals(self)
示例#24
0
    def __startGame(self):
        """Intialize rules and facts of the main environment.

        This function loads differents modules and create an environment that provides
        the proper context where a game can be played.
        """
        clips.Eval('(clear)')

        clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

        random.seed()
        clips.Eval("(seed " + str(random.randint(0, 9999)) + ")")

        try:
            # Se cargan una serie de funciones de utilidad, como "minimo" o "mov-valido"
            funciones.LoadFunctions(clips)

            # Se inicializan las opciones de juego (deffacts)
            f1.init_world(clips, self.number_turns)

            # Se cargan las plantillas ficha-r, ficha, mueve y obstaculo
            # además de las reglas para el control de los turnos
            f1.LoadFunctions(clips)
            mover.LoadFunctions(clips)
            texto.LoadFunctions(clips)
            traducirF.LoadFunctions(clips)
            traducirM.LoadFunctions(clips)

            nombreFicheroObstaculos = parsear_fichero_obstaculos.generar_reglas_obstaculos(
            )
            if nombreFicheroObstaculos:
                clips.Load(nombreFicheroObstaculos)
                os.unlink(nombreFicheroObstaculos)

        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError("W===============TTTT")

        logging.info("Parseando ficheros de formación...")
        temp_form_A = parsear_fichero_formacion.parsear_fichero_formacion(
            self.teamA[1], "A")
        temp_form_B = parsear_fichero_formacion.parsear_fichero_formacion(
            self.teamB[1], "B")

        self.teamA = (self.teamA[0], temp_form_A)
        self.teamB = (self.teamB[0], temp_form_B)

        temp_team = mirroring.mirroring_team(self.teamB[1])

        logging.info('Cargando %s', self.teamA[1])
        #create a temporally file that mirror the formation of B team,
        #because it's written thinking in A team
        try:
            clips.Load(self.teamA[1])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(
                _('Error parsing the file ') + self.teamA[1] + "\n" + e)

        logging.info('Cargando %s', self.teamB[1])

        try:
            clips.Load(temp_team)
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + self.teamB[1])

        os.remove(temp_team)
        os.remove(temp_form_A)
        os.remove(temp_form_B)

        try:
            fA.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamA[0])
            clips.Load(self.teamA[0])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")
            raise FileError(_('Error parsing the file ') + self.teamA[0])

        temp_rules = mirroring.mirroring_rules(self.teamB[0])

        #same thing that for the formation, but this time using the rules

        try:
            fB.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamB[0])
            clips.Load(temp_rules)
        except clips.ClipsError as e:
            os.remove(temp_rules)
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(
                _('Error parsing the file ') + self.teamB[0] + "\n")

        os.remove(temp_rules)

        clips.Reset()  #restart the environment

        clips.Run()  #start the simulation

        t = clips.StdoutStream.Read()  #print the output

        clipsOutputFile = open("clipsOutputFile", "w")
        clipsOutputFile.write(t)
        clipsOutputFile.close()

        f = clips.FactList()

        last_fact = f[len(f) - 1].PPForm()
        prev_last_fact = f[len(f) - 2].PPForm()

        winner = self.__define_winner(last_fact, prev_last_fact)

        return winner
def init_human_game(player_formation,
                    computer_team,
                    player_as,
                    number_turns,
                    dont_save=False):
    """
    Intialize the clips environment
    """

    player_num = 0
    team_a = None
    team_b = None
    name_team_a = ''
    name_team_b = ''

    team_a_piece = xdg.get_data_path('images/piece-orange.png')
    team_b_piece = xdg.get_data_path('images/piece-violete.png')
    default_piece = xdg.get_data_path('images/piece-default.png')

    formacion_temporal_player = None
    formacion_temporal_pc = None

    formacion_temporal_player = parsear_fichero_formacion(player_formation)
    player_formation = formacion_temporal_player
    formacion_temporal_pc = parsear_fichero_formacion(computer_team[1])

    computer_team = (computer_team[0], formacion_temporal_pc)

    if player_as == 'A':
        player_num = 1
        team_a = player_formation
        team_b = computer_team
        name_team_a = filenames.extract_simple_name_es((None, team_a))
        name_team_b = filenames.extract_name_expert_system(team_b)
    else:
        player_num = -1
        team_b = player_formation
        team_a = computer_team
        name_team_b = filenames.extract_simple_name_es((None, team_b))
        name_team_a = filenames.extract_name_expert_system(team_a)

    aux_team_a = (name_team_a, team_a_piece)
    aux_team_b = (name_team_b, team_b_piece)

    clips.Eval('(reset)')
    clips.Eval('(clear)')

    clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

    random.seed()
    clips.Eval("(seed %d)" % random.randint(0, 9999))

    funciones.LoadFunctions(clips)
    f1.init_world(clips, number_turns)

    try:
        f1.LoadFunctions(clips)
    except Exception:
        print clips.ErrorStream.Read()
        exit(-1)

    mover.LoadFunctions(clips)
    texto.LoadFunctions(clips)
    traducirF.LoadFunctions(clips)
    traducirM.LoadFunctions(clips)

    if player_num == 1:
        int_team = mirroring.interactive_formation(team_a)
        temp_team = mirroring.mirroring_team(team_b[1])

        try:
            clips.Load(int_team)
        except clips.ClipsError:
            os.remove(int_team)
            raise FileError(_('Error parsing the file ') + team_a)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_b[1])

        os.remove(int_team)
        os.remove(temp_team)

        fB.LoadFunctions(clips)
        temp_rules = mirroring.mirroring_rules(team_b[0])
        try:
            clips.Load(temp_rules)
        except clips.ClipsError:
            os.remove(temp_rules)
            raise FileError(_('Error parsing the file ') + team_b[0])
        os.remove(temp_rules)
    else:
        try:
            clips.Load(team_a[1])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[1])

        int_team = mirroring.interactive_formation(team_b)
        temp_team = mirroring.mirroring_team(int_team)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_a[1])
        os.remove(temp_team)

        fA.LoadFunctions(clips)
        try:
            clips.Load(team_a[0])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[0])

    interaccion.LoadFunctions(clips, player_as)

    interaccion.interaction_object = r_intact.HumanInteraction(
        aux_team_a, aux_team_b, default_piece, player_num, number_turns)

    clips.Reset()  # restart the environment

    clips.Run()  # start the simulation

    interaccion.interaction_object.finish()

    _stream = clips.StdoutStream.Read()  # print the output

    # print _stream
    # print interaccion.interaction_object.define_winner()

    if not dont_save:
        _rename_output_file(_generate_file_name(name_team_a, name_team_b))

    if os.path.isfile("resultado.txt"):
        os.remove('resultado.txt')

    os.remove(formacion_temporal_pc)
    os.remove(formacion_temporal_player)

    clips.Eval('(reset)')
    clips.Eval('(clear)')
    def __init__(self, classification, results, round, rounds,
                 show_classifications=True, show_top_teams=False, stats = None, next_matches = None): #add parent
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/results.glade'))

        self.classifications = classification
        self.results = results
        self.round = round
        self.rounds = rounds
        self.show_top_teams = show_top_teams
        self.stats = stats

        self.result_dialog = builder.get_object('dlg_results')
        title = self.result_dialog.get_title()  + ' ' + str(round) + '/' + str(rounds)
        self.result_dialog.set_title(title)

        self.confirmation_dialog = builder.get_object('dlg_confirmation_close')
        self.confirmation_dialog.connect('response', lambda d, r: d.hide())
        self.confirmation_dialog.set_transient_for(self.result_dialog)

        self.finalround_dialog = builder.get_object('dlg_finalround')
        self.finalround_dialog.connect('response', lambda d, r: d.hide())
        self.finalround_dialog.set_transient_for(self.result_dialog)

        self.list_view_classifications = builder.get_object('treeview_classification')
        self.list_view_results = builder.get_object('treeview_results')
        self.list_view_matches = builder.get_object('treeview_matches')

        if show_classifications:
            self.cPosition = 0
            self.cTeamName = 1
            self.cPuntuations = 2
        
            self.sPosition = 'Pos'
            self.sTeamName = _('Team name')
            self.sPuntuations = 'Punt'

            self.add_column(self.list_view_classifications,
                            self.sPosition, self.cPosition)
            self.add_column(self.list_view_classifications,
                            self.sTeamName, self.cTeamName)
            self.add_column(self.list_view_classifications,
                            self.sPuntuations, self.cPuntuations)

            if self.stats != None:
                self.cNumGanados = 3
                self.cNumEmpatados = 4
                self.cNumPerdidos = 5

                self.sNumGanados = '✓'
                self.sNumEmpatados = '='
                self.sNumPerdidos = '✗'

                self.add_column(self.list_view_classifications, self.sNumGanados, self.cNumGanados)
                self.add_column(self.list_view_classifications, self.sNumEmpatados, self.cNumEmpatados)
                self.add_column(self.list_view_classifications, self.sNumPerdidos, self.cNumPerdidos)

        self.list_store_classifications = builder.get_object('list_classification')
        
        if show_classifications:
            self.fill_classification()
        else:
            builder.get_object('hbox1').remove(builder.get_object('frame_classifications'))

        if next_matches:
            self.list_store_matches = builder.get_object('list_matches')
            self.add_column(self.list_view_matches, _("Team A"), 0)
            self.add_column(self.list_view_matches, _("Team B"), 1)

            for m in next_matches:
                n = list(m)

                if n[0] == "aux_ghost_team":
                    n[0] = _("Rests")

                if n[1] == "aux_ghost_team":
                    n[1] = _("Rests")

                self.list_store_matches.append(n)
        else:
            builder.get_object('hbox1').remove(builder.get_object('frame_matches'))

        self.cTeamA = 0
        self.cTeamB = 1

        self.sTeamA = _('Team A')
        self.sTeamB = _('Team B')

        self.add_column(self.list_view_results, self.sTeamA, self.cTeamA)
        self.add_column(self.list_view_results, self.sTeamB, self.cTeamB)
        self.add_column(self.list_view_results, _("Reason"), 2)

        self.list_store_results = builder.get_object('list_results')
        self.fill_results()

        self.end_contest = False
        
        builder.get_object('dlg_results').set_focus(builder.get_object('btn_results_next'))
        builder.connect_signals(self)
示例#27
0
def main():
    "Main function"
    editor = main_window.Resistencia()
    editor.window.show()
    print _("Loading main window")
    gtk.main()
示例#28
0
def _init_game(game_type, teams, fast, num_turns, back_round = False, log_base_folder = None):

    logging.info(">>>> INIT GAME")

    if log_base_folder == None:
        log_base_folder = configure.load_configuration()['games_path'] + '/'


    # Generamos el nombre del fichero de log según el tipo de juego
    log_base_name = filenames.generate_filename(game_type, noExtension = True)
    log_folder_name = log_base_folder + log_base_name
    log_file_name = log_folder_name + "/" + game_type + ".txt"

    logging.info("Fichero de log: %s", log_file_name)
    logging.info("Carpeta de log: %s", log_folder_name)

    os.mkdir(log_folder_name)
    
    # Lanzamos el tipo de juego apropiado
    if game_type == 'cup':
        game = tournament.Tournament(teams, num_turns, log_folder = log_folder_name)
    else:
        game = league.League(teams, num_turns, back_round, log_folder = log_folder_name)

    band = False

    # Contenedor para clasificaciones
    classifications = {}

    results = None

    # Cada elemento tendrá una tupla de 3: ganadas, empatadas y perdidas
    estadisticas = {"aux_ghost_team": {"ganadas":0, "empatadas":0, "perdidas":0}}

    for equipo in contest.generate_key_names(teams).keys():
        estadisticas[equipo] = {"ganadas":0, "empatadas":0, "perdidas":0};

    # Mientras no se haya completado el juego
    while not game.completed() and not band and not controlPartida.flagCancelarCampeonato:

        logging.info("---- START OF THE ROUND")

        if results != None:

            # Cargamos el diálogo de resultados
            R = round_results.roundResults(classifications, results,
                                           game.get_prev_round_number() + 1,
                                           game.get_number_of_rounds(),
                                           show_classifications = (game_type != 'cup'),
                                           stats = estadisticas,
                                           show_top_teams = True,
                                           next_matches = game.matchs[game.get_round_number()])

        # Mostramos el diálogo de resultados
            button_pressed = R.result_dialog.run()
        
            while gtk.events_pending():
                gtk.main_iteration(False)
            
            if button_pressed == -4 or button_pressed == 0:
                band = True
                continue


        # Guardamos el número de la ronda
        roundNumber = game.get_round_number()

        if roundNumber == 0:
            show_round_matches(game)

        # Por defecto que la barra de progreso no exista
        progress_bar = None

        # Si no mostramos el progreso del juego, que salga la barra
        if fast:
            progress_bar = pbs.ProgressBarDialog(None, _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(game.get_round(roundNumber).number_games)
            progress_bar_dialog.show()

            while gtk.events_pending():
                gtk.main_iteration(False)
    
        # Jugamos esta ronda
        game.play_round(progress_bar, fast)

        if controlPartida.flagCancelarCampeonato:
            return
        
        # Guardamos en r la ronda actual, con sus resultados y tal
        r = game.get_round(roundNumber)
        
        # Resultados de la ronda
        results = r.get_round_results()

        # Actualizamos el fichero del log
        update_log_round(log_file_name, results, roundNumber)

        for partido in results:
            if partido[1] == 1:
                estadisticas[partido[0][0]]["ganadas"] += 1
                estadisticas[partido[0][1]]["perdidas"] += 1
            elif partido[1] == -1:
                estadisticas[partido[0][1]]["ganadas"] += 1
                estadisticas[partido[0][0]]["perdidas"] += 1                    
            else:
                estadisticas[partido[0][0]]["empatadas"] += 1
                estadisticas[partido[0][1]]["empatadas"] += 1

        if game_type == 'cup':
            pass
        else:
            # "Puntuations" es una palabra que no existe
            classifications = game.get_actual_puntuations()

        # Ocultamos la barra de progreso (que ya habrá acabado)
        if fast:
            progress_bar_dialog.hide()

        logging.info("---- END OF THE ROUND")

    if not band:
        # Mostramos los resultados FINALES
        R = round_results.roundResults(classifications, results,
                                       game.get_prev_round_number() + 1,
                                       game.get_number_of_rounds(),
                                       show_classifications = (game_type != 'cup'),
                                       show_top_teams = True,
                                       stats = estadisticas)

        # Mostramos el diálogo de resultados
        button_pressed = R.result_dialog.run()
        
        while gtk.events_pending():
            gtk.main_iteration(False)
            
    if not band and not controlPartida.flagCancelarCampeonato:
        if game_type == 'cup':
            update_log_ending_tournament(log_file_name, estadisticas)
            dibujoClasificacion = dibujo_clasificacion.DibujoClasificacion(game)
        else:        
            update_log_ending_league(log_file_name, classifications)
        
    logging.info(">>>> END INIT GAME")
    return (band, classifications)
def init_human_game(player_formation, computer_team, player_as,
                    number_turns, dont_save=False):
    """
    Intialize the clips environment
    """
    
    
    player_num = 0
    team_a = None
    team_b = None
    name_team_a = ''
    name_team_b = ''

    team_a_piece = xdg.get_data_path('images/piece-orange.png')
    team_b_piece = xdg.get_data_path('images/piece-violete.png')
    default_piece = xdg.get_data_path('images/piece-default.png')

    formacion_temporal_player = None
    formacion_temporal_pc = None

    formacion_temporal_player = parsear_fichero_formacion(player_formation)
    player_formation = formacion_temporal_player
    formacion_temporal_pc = parsear_fichero_formacion(computer_team[1])

    computer_team = (computer_team[0], formacion_temporal_pc)

    if player_as == 'A':
        player_num = 1
        team_a = player_formation
        team_b = computer_team
        name_team_a = filenames.extract_simple_name_es((None, team_a))
        name_team_b = filenames.extract_name_expert_system(team_b)
    else:
        player_num = -1
        team_b = player_formation
        team_a = computer_team
        name_team_b = filenames.extract_simple_name_es((None, team_b))
        name_team_a = filenames.extract_name_expert_system(team_a)

    
    

    aux_team_a = (name_team_a, team_a_piece)
    aux_team_b = (name_team_b, team_b_piece)

    clips.Eval('(reset)')
    clips.Eval('(clear)')

    clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

    random.seed()
    clips.Eval("(seed %d)" % random.randint(0, 9999))

    funciones.LoadFunctions(clips)
    f1.init_world(clips, number_turns)

    try:
        f1.LoadFunctions(clips)
    except Exception:
        print clips.ErrorStream.Read()
        exit(-1)
    
    mover.LoadFunctions(clips)
    texto.LoadFunctions(clips)
    traducirF.LoadFunctions(clips)
    traducirM.LoadFunctions(clips)

    
    
    if player_num == 1:
        int_team = mirroring.interactive_formation(team_a)
        temp_team = mirroring.mirroring_team(team_b[1])

        try:
            clips.Load(int_team)
        except clips.ClipsError:
            os.remove(int_team)
            raise FileError(_('Error parsing the file ') + team_a)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_b[1])

        os.remove(int_team)
        os.remove(temp_team)

        fB.LoadFunctions(clips)
        temp_rules = mirroring.mirroring_rules(team_b[0])
        try:
            clips.Load(temp_rules)
        except clips.ClipsError:
            os.remove(temp_rules)
            raise FileError(_('Error parsing the file ') + team_b[0])
        os.remove(temp_rules)
    else:
        try:
            clips.Load(team_a[1])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[1])

        int_team = mirroring.interactive_formation(team_b)
        temp_team = mirroring.mirroring_team(int_team)

        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') + team_a[1])
        os.remove(temp_team)

        fA.LoadFunctions(clips)
        try:
            clips.Load(team_a[0])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') + team_a[0])

    interaccion.LoadFunctions(clips, player_as)

    
    interaccion.interaction_object = r_intact.HumanInteraction(
        aux_team_a, aux_team_b, default_piece, player_num, number_turns)

    
    clips.Reset()  # restart the environment

    
    clips.Run()  # start the simulation

    
    interaccion.interaction_object.finish()

    
    _stream = clips.StdoutStream.Read()  # print the output

    # print _stream
    # print interaccion.interaction_object.define_winner()

    if not dont_save:
        _rename_output_file(_generate_file_name(name_team_a, name_team_b))
        
    if os.path.isfile("resultado.txt"):
        os.remove('resultado.txt')

    
    os.remove(formacion_temporal_pc)
    os.remove(formacion_temporal_player)
    
    clips.Eval('(reset)')
    clips.Eval('(clear)')
示例#30
0
    def __init__(self, parent):
        self.rules_main_team = ''
        self.formation_main_team = ''
        self.files = {}
        self.teams = {}

        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/testDialog.glade'))

        self.tests_dialog = builder.get_object('tests_dialog')
        self.tests_dialog.set_transient_for(parent)

        # ---- Init file chooser buttons
        default_path = configure.load_configuration()['se_path']
        default_rules_path = default_path + '/rules'
        default_formations_path = default_path + '/formations'
        builder.get_object('btn_filechooser_rules').set_current_folder(default_rules_path)
        builder.get_object('btn_filechooser_formation').set_current_folder(default_formations_path)
        # ----

        self.num_rounds = 2
        self.spin_rounds = builder.get_object('spin_rounds')
        self.spin_rounds.set_range(2, 100)
        self.spin_rounds.set_increments(2,10)
        self.spin_rounds.set_value(self.num_rounds)
        
        self.num_turns = 120
        self.spin_turns = builder.get_object("spin_num_turns")
        self.spin_turns.set_range(50,300)
        self.spin_turns.set_increments(2,10)
        self.spin_turns.set_value(self.num_turns)

        self.all_teams = False
        self.frame_selection_teams = builder.get_object('frame_es_selection')

        self.start_button = builder.get_object('btn_apply')
        self.start_button.set_sensitive(False)
        
        #---------------------------
        self.cName = 0
        self.cRules = 1
        self.cFormation = 2
        
        self.sName = _("Name")
        self.sRules = _("Rules")
        self.sFormation = _("Formation")
        
        self.list_view = builder.get_object("list_es_view")
        self.list_view.set_reorderable(False)

        self.addColumn(self.sName, self.cName)
        self.addColumn(self.sRules, self.cRules)
        self.addColumn(self.sFormation, self.cFormation)

        self.list_store = builder.get_object("list_expert_system")
        #-----------------------------
        self.file_chooser_rules = builder.get_object('file_chooser_rules')
        self.file_chooser_formation = builder.get_object('file_chooser_formation')
        self.file_chooser_rules.set_current_folder(default_rules_path)
        self.file_chooser_formation.set_current_folder(default_formations_path)

        
        self.error_es = builder.get_object("error_no_es")
        self.error_es.connect('response', lambda d, r: d.hide())
        self.error_es.set_transient_for(self.tests_dialog)
        
        self.error_team = builder.get_object("error_no_team")
        self.error_team.connect('response', lambda d, r: d.hide())
        self.error_team.set_transient_for(self.tests_dialog)

        self.progress_bar = pbs.ProgressBarDialog(self.tests_dialog,
                                                  _('Running the test'))
        self.progress_bar_dialog = self.progress_bar.progress_bar_dialog
        
        builder.connect_signals(self)
示例#31
0
def _init_game(game_type,
               teams,
               fast,
               num_turns,
               back_round=False,
               log_base_folder=None):

    logging.info(">>>> INIT GAME")

    if log_base_folder == None:
        log_base_folder = configure.load_configuration()['games_path'] + '/'

    # Generamos el nombre del fichero de log según el tipo de juego
    log_base_name = filenames.generate_filename(game_type, noExtension=True)
    log_folder_name = log_base_folder + log_base_name
    log_file_name = log_folder_name + "/" + game_type + ".txt"

    logging.info("Fichero de log: %s", log_file_name)
    logging.info("Carpeta de log: %s", log_folder_name)

    os.mkdir(log_folder_name)

    # Lanzamos el tipo de juego apropiado
    if game_type == 'cup':
        game = tournament.Tournament(teams,
                                     num_turns,
                                     log_folder=log_folder_name)
    else:
        game = league.League(teams,
                             num_turns,
                             back_round,
                             log_folder=log_folder_name)

    band = False

    # Contenedor para clasificaciones
    classifications = {}

    results = None

    # Cada elemento tendrá una tupla de 3: ganadas, empatadas y perdidas
    estadisticas = {
        "aux_ghost_team": {
            "ganadas": 0,
            "empatadas": 0,
            "perdidas": 0
        }
    }

    for equipo in contest.generate_key_names(teams).keys():
        estadisticas[equipo] = {
            "ganadas": 0,
            "empatadas": 0,
            "perdidas": 0
        }

    # Mientras no se haya completado el juego
    while not game.completed(
    ) and not band and not controlPartida.flagCancelarCampeonato:

        logging.info("---- START OF THE ROUND")

        if results != None:

            # Cargamos el diálogo de resultados
            R = round_results.roundResults(
                classifications,
                results,
                game.get_prev_round_number() + 1,
                game.get_number_of_rounds(),
                show_classifications=(game_type != 'cup'),
                stats=estadisticas,
                show_top_teams=True,
                next_matches=game.matchs[game.get_round_number()])

            # Mostramos el diálogo de resultados
            button_pressed = R.result_dialog.run()

            while gtk.events_pending():
                gtk.main_iteration(False)

            if button_pressed == -4 or button_pressed == 0:
                band = True
                continue

        # Guardamos el número de la ronda
        roundNumber = game.get_round_number()

        if roundNumber == 0:
            show_round_matches(game)

        # Por defecto que la barra de progreso no exista
        progress_bar = None

        # Si no mostramos el progreso del juego, que salga la barra
        if fast:
            progress_bar = pbs.ProgressBarDialog(None,
                                                 _('Running the contest'))
            progress_bar_dialog = progress_bar.progress_bar_dialog
            progress_bar.set_num_elements(
                game.get_round(roundNumber).number_games)
            progress_bar_dialog.show()

            while gtk.events_pending():
                gtk.main_iteration(False)

        # Jugamos esta ronda
        game.play_round(progress_bar, fast)

        if controlPartida.flagCancelarCampeonato:
            return

        # Guardamos en r la ronda actual, con sus resultados y tal
        r = game.get_round(roundNumber)

        # Resultados de la ronda
        results = r.get_round_results()

        # Actualizamos el fichero del log
        update_log_round(log_file_name, results, roundNumber)

        for partido in results:
            if partido[1] == 1:
                estadisticas[partido[0][0]]["ganadas"] += 1
                estadisticas[partido[0][1]]["perdidas"] += 1
            elif partido[1] == -1:
                estadisticas[partido[0][1]]["ganadas"] += 1
                estadisticas[partido[0][0]]["perdidas"] += 1
            else:
                estadisticas[partido[0][0]]["empatadas"] += 1
                estadisticas[partido[0][1]]["empatadas"] += 1

        if game_type == 'cup':
            pass
        else:
            # "Puntuations" es una palabra que no existe
            classifications = game.get_actual_puntuations()

        # Ocultamos la barra de progreso (que ya habrá acabado)
        if fast:
            progress_bar_dialog.hide()

        logging.info("---- END OF THE ROUND")

    if not band:
        # Mostramos los resultados FINALES
        R = round_results.roundResults(
            classifications,
            results,
            game.get_prev_round_number() + 1,
            game.get_number_of_rounds(),
            show_classifications=(game_type != 'cup'),
            show_top_teams=True,
            stats=estadisticas)

        # Mostramos el diálogo de resultados
        button_pressed = R.result_dialog.run()

        while gtk.events_pending():
            gtk.main_iteration(False)

    if not band and not controlPartida.flagCancelarCampeonato:
        if game_type == 'cup':
            update_log_ending_tournament(log_file_name, estadisticas)
            dibujoClasificacion = dibujo_clasificacion.DibujoClasificacion(
                game)
        else:
            update_log_ending_league(log_file_name, classifications)

    logging.info(">>>> END INIT GAME")
    return (band, classifications)
    def __init__(self,
                 classification,
                 results,
                 round,
                 rounds,
                 show_classifications=True,
                 show_top_teams=False,
                 stats=None,
                 next_matches=None):  #add parent
        builder = gtk.Builder()
        builder.add_from_file(xdg.get_data_path('glade/results.glade'))

        self.classifications = classification
        self.results = results
        self.round = round
        self.rounds = rounds
        self.show_top_teams = show_top_teams
        self.stats = stats

        self.result_dialog = builder.get_object('dlg_results')
        title = self.result_dialog.get_title() + ' ' + str(round) + '/' + str(
            rounds)
        self.result_dialog.set_title(title)

        self.confirmation_dialog = builder.get_object('dlg_confirmation_close')
        self.confirmation_dialog.connect('response', lambda d, r: d.hide())
        self.confirmation_dialog.set_transient_for(self.result_dialog)

        self.finalround_dialog = builder.get_object('dlg_finalround')
        self.finalround_dialog.connect('response', lambda d, r: d.hide())
        self.finalround_dialog.set_transient_for(self.result_dialog)

        self.list_view_classifications = builder.get_object(
            'treeview_classification')
        self.list_view_results = builder.get_object('treeview_results')
        self.list_view_matches = builder.get_object('treeview_matches')

        if show_classifications:
            self.cPosition = 0
            self.cTeamName = 1
            self.cPuntuations = 2

            self.sPosition = 'Pos'
            self.sTeamName = _('Team name')
            self.sPuntuations = 'Punt'

            self.add_column(self.list_view_classifications, self.sPosition,
                            self.cPosition)
            self.add_column(self.list_view_classifications, self.sTeamName,
                            self.cTeamName)
            self.add_column(self.list_view_classifications, self.sPuntuations,
                            self.cPuntuations)

            if self.stats != None:
                self.cNumGanados = 3
                self.cNumEmpatados = 4
                self.cNumPerdidos = 5

                self.sNumGanados = '✓'
                self.sNumEmpatados = '='
                self.sNumPerdidos = '✗'

                self.add_column(self.list_view_classifications,
                                self.sNumGanados, self.cNumGanados)
                self.add_column(self.list_view_classifications,
                                self.sNumEmpatados, self.cNumEmpatados)
                self.add_column(self.list_view_classifications,
                                self.sNumPerdidos, self.cNumPerdidos)

        self.list_store_classifications = builder.get_object(
            'list_classification')

        if show_classifications:
            self.fill_classification()
        else:
            builder.get_object('hbox1').remove(
                builder.get_object('frame_classifications'))

        if next_matches:
            self.list_store_matches = builder.get_object('list_matches')
            self.add_column(self.list_view_matches, _("Team A"), 0)
            self.add_column(self.list_view_matches, _("Team B"), 1)

            for m in next_matches:
                n = list(m)

                if n[0] == "aux_ghost_team":
                    n[0] = _("Rests")

                if n[1] == "aux_ghost_team":
                    n[1] = _("Rests")

                self.list_store_matches.append(n)
        else:
            builder.get_object('hbox1').remove(
                builder.get_object('frame_matches'))

        self.cTeamA = 0
        self.cTeamB = 1

        self.sTeamA = _('Team A')
        self.sTeamB = _('Team B')

        self.add_column(self.list_view_results, self.sTeamA, self.cTeamA)
        self.add_column(self.list_view_results, self.sTeamB, self.cTeamB)
        self.add_column(self.list_view_results, _("Reason"), 2)

        self.list_store_results = builder.get_object('list_results')
        self.fill_results()

        self.end_contest = False

        builder.get_object('dlg_results').set_focus(
            builder.get_object('btn_results_next'))
        builder.connect_signals(self)
示例#33
0
 def on_file_chs_prev_games_selection_changed(self, widget, data=None):
     self.label_logfolder.set_markup(_("<b>Full path</b>: ") + widget.get_filename())
示例#34
0
    def __startGame(self):
        """Intialize rules and facts of the main environment.

        This function loads differents modules and create an environment that provides
        the proper context where a game can be played.
        """
        clips.Eval('(clear)')
        
        clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

        random.seed()
        clips.Eval("(seed " + str(random.randint(0,9999)) + ")") 

        funciones.LoadFunctions(clips)
        f1.init_world(clips, self.number_turns)
        f1.LoadFunctions(clips)
        mover.LoadFunctions(clips)
        texto.LoadFunctions(clips)
        traducirF.LoadFunctions(clips)
        traducirM.LoadFunctions(clips)

        #print self.teams_path + "/equipo" + self.teamA + ".clp"
        temp_team = mirroring.mirroring_team(self.teamB[1])
        print _('Loading ') + self.teamA[1]
        #create a temporally file that mirror the formation of B team,
        #because it's written thinking in A team
        try:
            clips.Load(self.teamA[1])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') +  self.teamA[1])
        print _('Loading ') + self.teamB[1]
        try:
            clips.Load(temp_team)
        except clips.ClipsError:
            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') +  self.teamB[1])
        
        os.remove(temp_team)

        fA.LoadFunctions(clips)
        print _('Loading ') + self.teamA[0]
        try:
            clips.Load(self.teamA[0])
        except clips.ClipsError:
            raise FileError(_('Error parsing the file ') +  self.teamA[0])
        temp_rules = mirroring.mirroring_rules(self.teamB[0])
        #same thing that for the formation, but this time using the rules
        fB.LoadFunctions(clips)
        print _('Loading ') + self.teamB[0]
        try:
            clips.Load(temp_rules)
        except clips.ClipsError:
            os.remove(temp_rules)
            raise FileError(_('Error parsing the file ') +  self.teamB[0])
        
        os.remove(temp_rules)

        clips.Reset() #restart the environment

        clips.Run() #start the simulation
        t = clips.StdoutStream.Read() #print the output
        f = clips.FactList()

        last_fact = f[len(f)-1].PPForm()
        prev_last_fact = f[len(f)-2].PPForm()

        winner = self.__define_winner(last_fact, prev_last_fact)

        print t

        return winner
示例#35
0
    def __startGame(self):
        """Intialize rules and facts of the main environment.

        This function loads differents modules and create an environment that provides
        the proper context where a game can be played.
        """
        clips.Eval('(clear)')
        
        clips.EngineConfig.Strategy = clips.RANDOM_STRATEGY

        random.seed()
        clips.Eval("(seed " + str(random.randint(0,9999)) + ")") 
        
        try:
            # Se cargan una serie de funciones de utilidad, como "minimo" o "mov-valido"
            funciones.LoadFunctions(clips)

            # Se inicializan las opciones de juego (deffacts)
            f1.init_world(clips, self.number_turns)

            # Se cargan las plantillas ficha-r, ficha, mueve y obstaculo
            # además de las reglas para el control de los turnos
            f1.LoadFunctions(clips)
            mover.LoadFunctions(clips)
            texto.LoadFunctions(clips)
            traducirF.LoadFunctions(clips)
            traducirM.LoadFunctions(clips)

            nombreFicheroObstaculos = parsear_fichero_obstaculos.generar_reglas_obstaculos()
            if nombreFicheroObstaculos:
                clips.Load(nombreFicheroObstaculos)
                os.unlink(nombreFicheroObstaculos)

        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError("W===============TTTT")


        logging.info("Parseando ficheros de formación...")
        temp_form_A = parsear_fichero_formacion.parsear_fichero_formacion(self.teamA[1], "A")
        temp_form_B = parsear_fichero_formacion.parsear_fichero_formacion(self.teamB[1], "B")

        self.teamA = (self.teamA[0], temp_form_A)
        self.teamB = (self.teamB[0], temp_form_B)

        temp_team = mirroring.mirroring_team(self.teamB[1])

        logging.info('Cargando %s', self.teamA[1])
        #create a temporally file that mirror the formation of B team,
        #because it's written thinking in A team
        try:
            clips.Load(self.teamA[1])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(_('Error parsing the file ') +  self.teamA[1] + "\n" + e)

        logging.info('Cargando %s', self.teamB[1])

        try:
            clips.Load(temp_team)
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            os.remove(temp_team)
            raise FileError(_('Error parsing the file ') +  self.teamB[1])
        
        os.remove(temp_team)
        os.remove(temp_form_A)
        os.remove(temp_form_B)


        try:
            fA.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamA[0])
            clips.Load(self.teamA[0])
        except clips.ClipsError as e:
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")
            raise FileError(_('Error parsing the file ') +  self.teamA[0])

        temp_rules = mirroring.mirroring_rules(self.teamB[0])
        
        #same thing that for the formation, but this time using the rules

        try:
            fB.LoadFunctions(clips)
            logging.info('Cargando %s', self.teamB[0])
            clips.Load(temp_rules)
        except clips.ClipsError as e:
            os.remove(temp_rules)
            logging.error("####################")
            logging.error("ERROR de clips: %s", e)
            logging.error("Mensaje: ")
            logging.error(clips.ErrorStream.Read())
            logging.error("####################")

            raise FileError(_('Error parsing the file ') +  self.teamB[0] + "\n")
        
        os.remove(temp_rules)

        clips.Reset() #restart the environment

        clips.Run() #start the simulation

        t = clips.StdoutStream.Read() #print the output

        clipsOutputFile = open("clipsOutputFile", "w")
        clipsOutputFile.write(t)
        clipsOutputFile.close()

        f = clips.FactList()

        last_fact = f[len(f)-1].PPForm()
        prev_last_fact = f[len(f)-2].PPForm()

        winner = self.__define_winner(last_fact, prev_last_fact)

        return winner
示例#36
0
    def __init__(self, main_team, teams, rounds_number, num_turns):
        self.main_team = main_team
        self.teams = teams
        self.num_turns = num_turns

        self.translator_teams = _generate_key_names(teams)
        self.translator_main_team = _generate_key_names([main_team])

        self.keys_teams = []
        self.key_main_team = []

        self.rounds_number = rounds_number

        base_path = configure.load_configuration()['games_path'] + '/'
        base_path += filenames.generate_filename('labdir', main_team) + '/'

        os.mkdir(base_path)

        self.filename = base_path + filenames.generate_filename(
            'stats', main_team)

        for _team in self.translator_teams:
            self.keys_teams.append(_team)

        for _team in self.translator_main_team:
            self.key_main_team.append(_team)

        self.translator = self.translator_teams.copy()
        for k in self.translator_main_team:
            self.translator[k] = self.translator_main_team[k]

        self.rounds = []
        stats_writer = csv.writer(open(self.filename, 'w'),
                                  delimiter=',',
                                  quotechar='|',
                                  quoting=csv.QUOTE_MINIMAL)
        stats_writer.writerow([
            _('Opponent'),
            _('As team'),
            _('Result'),
            _("Number of turns"),
            _('Number of pieces'),
            _("Value of the pieces"),
            _('Turn when max value piece died')
        ])

        for i in range(self.rounds_number):
            round_games = pairing.test_pairing(self.key_main_team[0],
                                               self.keys_teams, i % 2)
            self.rounds.append(
                test_round.TestRound((round_games, self.translator),
                                     num_turns=self.num_turns,
                                     log_file=self.filename,
                                     player=i % 2,
                                     logFolder=base_path))

        self.total_stats = {}
        self.total_stats['wins'] = 0
        self.total_stats['looses'] = 0
        self.total_stats['draws'] = 0
        self.total_stats['turns_winning'] = 0
        self.total_stats['turns_losing'] = 0
        self.total_stats['num_pieces'] = 0
        self.total_stats['val_pieces'] = 0
        self.total_stats['max_death'] = 0