def __init__(self, character):
        super(SimulationConfiguration, self).__init__()
        self.setupUi(self)

        self.character = character
        self.Map = self.character.get_map()
        self.graph = self.Map.get_graph()

        self.load_coords()
        self.load_map()

        self.character.set_label_idx(None)
        self.load_character_lbl()
        self.load_character_errors()
        self.load_character_textline()

        self.goal = Goal(lbl_idx=None)

        self.load_goal_lbl()
        self.load_goal_errors()
        self.load_goal_textline()

        self.adjust_sizes(None, None)

        self.load_accept_btn()

        self.priority_list = list()
        self.simulation_option = None
        self.show()
    def __init__(self, character, goal=None):
        super(SimulationConfiguration, self).__init__()
        self.setupUi(self)

        self.character = character
        self.Map = self.character.get_map()
        self.graph = self.Map.get_graph()

        self.distance = None
        self.load_coords()
        self.load_map()
        self.character.set_label_idx(None)
        self.load_character_lbl()
        self.load_character_errors()
        self.load_character_indications()
        self.load_character_textline()

        from_simulation = False
        r = 0
        c = 0
        if goal == None:
            self.goal = Goal(lbl_idx=None)
        else:
            self.goal = goal
            r, c = self.goal.get_last_position()
            from_simulation = True

        self.load_goal_lbl()
        self.load_goal_errors()
        self.load_goal_indications()
        self.load_goal_textline()

        self.adjust_sizes(None, None)

        self.load_accept_btn()

        if from_simulation:
            self.load_goal(r, c + 1)
            r, c = self.character.get_last_position()
            self.load_character(r, c + 1)

        self.priority_list = list()
        self.simulation_option = None
        self.setStyleSheet("font-family:Verdana;")
        self.show()
Esempio n. 3
0
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('goals',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('key', sa.String(length=50), nullable=False),
    sa.Column('name', sa.String(length=100), nullable=False),
    sa.Column('icon', sa.String(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('teachers',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=100), nullable=False),
    sa.Column('about', sa.String(length=1000), nullable=False),
    sa.Column('rating', sa.Integer(), nullable=False),
    sa.Column('picture', sa.String(), nullable=False),
    sa.Column('price', sa.Integer(), nullable=False),
    sa.Column('free', sa.String(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('teachers_goals',
    sa.Column('teacher_id', sa.Integer(), nullable=True),
    sa.Column('goal_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['goal_id'], ['goals.id'], ),
    sa.ForeignKeyConstraint(['teacher_id'], ['teachers.id'], )
    )
    # ### end Alembic commands ###

    goals = []
    for goal in reader.get_all_goals():
        goals.append(
            Goal(
                key=goal['key'],
                name=goal['name'],
                icon=goal['icon']
            ))

    teachers = []
    for teacher in reader.get_all_teachers():
        teachers.append(
            Teacher(
                id=teacher['id'],
                name=teacher['name'],
                about=teacher['about'],
                rating=teacher['rating'],
                picture=teacher['picture'],
                price=teacher['price'],
                goals=[goal for goal in goals if goal.key in teacher['goals']],
                free=json.dumps(teacher['free'])
            ))

    db.session.add_all(goals)
    db.session.add_all(teachers)
    db.session.commit()
Esempio n. 4
0
def team_2_goals(game):
    goals = []

    sql = "SELECT * FROM goals WHERE game_id = %s"
    values = [game.id]
    results = run_sql(sql, values)

    for result in results:
        player = player_repo.select(result['player_id'])
        if player.team.id == game.team_2.id:
            goal = Goal(player, game, result['id'])
            goals.append(goal)
    return goals
Esempio n. 5
0
def new_goal_individual(league_id, game_id):
    game = game_repo.select(game_id)
    player_id = request.form['player_id']
    player = player_repo.select(player_id)
    goal = Goal(player, game)
    goal_repo.save(goal)
    if player.team.id == game.team_1.id:
        game.team_1_score += 1
    else:
        game.team_2_score += 1
    player.goals_scored += 1
    game_repo.goal_scored(game)
    player_repo.goal_scored(player)

    return redirect(f"/edit/games/{game_id}")
Esempio n. 6
0
def seed_all():

    db.create_all()

    # Players
    players = None
    with open('seed_data/players.json') as f:
        players = json.load(f)

    for player in players:
        new_player = Player(**player)
        db.session.add(new_player)
        db.session.commit()

    # Torunaments
    tournaments = None
    with open('seed_data/tournaments.json') as f:
        tournaments = json.load(f)

    for tournament in tournaments:
        new_tournament = Tournament(**tournament)
        db.session.add(new_tournament)
        db.session.commit()

    # stages
    stages = None
    with open('seed_data/stages.json') as f:
        stages = json.load(f)

    for single_round in stages:
        new_round = Stage(**single_round)
        db.session.add(new_round)
        db.session.commit()

    # teams
    teams = None
    with open('seed_data/teams.json') as f:
        teams = json.load(f)
    for team in teams:
        new_team = Team(**team)
        db.session.add(new_team)
        db.session.commit()

    tournament_data = None
    with open('seed_data/tournament_data.json') as f:
        tournament_data = json.load(f)
    for tournament in tournament_data:

        for squad_player in tournament['squad']:
            player = Player.query.filter(
                Player.lastName == squad_player['lastName'],
                Player.firstName == squad_player['firstName']).first()
            tournament_found = Tournament.query.filter_by(
                year=tournament['year']).first()
            new_squad_player = {
                "playerId": player.id,
                "tournamentId": tournament_found.id,
                "goals": squad_player['goals'],
                "position": squad_player["position"],
                "appearances": squad_player['matches']
            }

            db.session.add(Squad(**new_squad_player))
            db.session.commit()

        # matches
        for match in tournament['matches']:
            home_team = Team.query.filter_by(name=match['homeTeam']).first()
            away_team = Team.query.filter_by(name=match['awayTeam']).first()
            tournament_found = Tournament.query.filter_by(
                year=tournament['year']).first()
            stage = Stage.query.filter(
                Stage.tournamentId == tournament_found.id,
                Stage.position == match['round']).first()
            match_date = datetime.strptime(match['date'].strip(),
                                           "%d.%m.%Y").date()
            match_obj = {
                "homeTeam": home_team,
                "awayTeam": away_team,
                "tournamentId": tournament_found.id,
                "stageId": stage.id,
                "date": match_date,
                "goalsHomeTeam": match['result']['goalsHomeTeam'],
                "goalsAwayTeam": match['result']['goalsAwayTeam']
            }
            new_match = Match(**match_obj)
            db.session.add(new_match)
            db.session.commit()

            # homegoalscorers
            for goal in match['goalscorers']['homeGoalScorers']:
                if '(k)' in goal['player'] or '(s)' in goal['player']:
                    goal['player'] = goal['player'][3:]

                pl_split = goal['player'].split()
                found_player = Player.query.filter(
                    (Player.lastName == goal['player'])
                    | ((Player.lastName == pl_split[-1])
                       & (Player.firstName == pl_split[0]))).first()
                if not found_player:
                    pdb.set_trace()
                new_goal = Goal(matchId=new_match.id,
                                minute=goal['minute'],
                                playerId=found_player.id,
                                homeTeamGoal=True)
                db.session.add(new_goal)
                db.session.commit()

            # awaygoalscorers
            for goal in match['goalscorers']['awayGoalScorers']:
                if '(k)' in goal['player'] or '(s)' in goal['player']:
                    goal['player'] = goal['player'][3:]

                pl_split = goal['player'].split()
                found_player = Player.query.filter(
                    (Player.lastName == goal['player'])
                    | ((Player.lastName == pl_split[-1])
                       & (Player.firstName == pl_split[0]))).first()
                if not found_player:
                    pdb.set_trace()
                new_goal = Goal(matchId=new_match.id,
                                minute=goal['minute'],
                                playerId=found_player.id,
                                awayTeamGoal=True)
                db.session.add(new_goal)
                db.session.commit()

        # standings
        for standing in tournament['standings']:

            found_team = Team.query.filter_by(
                name=standing['teamName']).first()

            tournament_found = Tournament.query.filter_by(
                year=tournament['year']).first()
            stage = Stage.query.filter(
                Stage.tournamentId == tournament_found.id,
                Stage.position == standing['round']).first()

            if not found_team:
                pdb.set_trace()
            new_standing = Standing(stageId=stage.id,
                                    teamId=found_team.id,
                                    tournamentId=tournament_found.id,
                                    position=standing['position'],
                                    points=standing['points'],
                                    wins=standing['position'],
                                    losses=standing['loses'],
                                    draws=standing['draws'],
                                    goalsScored=standing['goalsScored'],
                                    goalsConceded=standing['goalsConceded'])
            db.session.add(new_standing)
            db.session.commit()
class SimulationConfiguration(QMainWindow, Ui_MainWindow):
    def __init__(self, character, goal=None):
        super(SimulationConfiguration, self).__init__()
        self.setupUi(self)

        self.character = character
        self.Map = self.character.get_map()
        self.graph = self.Map.get_graph()

        self.distance = None
        self.load_coords()
        self.load_map()
        self.character.set_label_idx(None)
        self.load_character_lbl()
        self.load_character_errors()
        self.load_character_indications()
        self.load_character_textline()

        from_simulation = False
        r = 0
        c = 0
        if goal == None:
            self.goal = Goal(lbl_idx=None)
        else:
            self.goal = goal
            r, c = self.goal.get_last_position()
            from_simulation = True

        self.load_goal_lbl()
        self.load_goal_errors()
        self.load_goal_indications()
        self.load_goal_textline()

        self.adjust_sizes(None, None)

        self.load_accept_btn()

        if from_simulation:
            self.load_goal(r, c + 1)
            r, c = self.character.get_last_position()
            self.load_character(r, c + 1)

        self.priority_list = list()
        self.simulation_option = None
        self.setStyleSheet("font-family:Verdana;")
        self.show()

#-------
#Map
#-------

    def load_coords(self):
        total_row = len(self.graph)
        total_column = len(self.graph[0])
        for i in range(total_column + 1):
            if i == 0:
                data = " "
            else:
                data = chr(64 + i)
            row_lbl = QLabel()

            row_lbl.setFixedSize(40, 40)
            row_lbl.setText(data)
            row_lbl.setAlignment(Qt.AlignCenter)
            self.XGrd.addWidget(row_lbl, 0, i)

    def load_map(self):
        for i in range(len(self.graph)):
            row = self.graph[i]
            data = str(i + 1)
            node_lbl = QLabel()
            node_lbl.setAlignment(Qt.AlignCenter)
            node_lbl.setFixedSize(40, 40)
            node_lbl.setText(data)
            self.mapGrd.addWidget(node_lbl, i, 0)
            for j in range(len(row)):
                node = row[j]
                node_lbl = QLabel()
                if node.get_image() != None:
                    data = node.get_image()
                    node_lbl.setPixmap(QPixmap(data))
                    node_lbl.setSizePolicy(QSizePolicy.Ignored,
                                           QSizePolicy.Ignored)
                    node_lbl.setScaledContents(True)
                    self.mapGrd.addWidget(node_lbl, i, j + 1)

#----------
#Utils
#----------

    def valid_coord(self, coords):
        coord_reg_ex = r"(\s*[a-zA-Z]+\s*\x2c\s*[1-9][0-9]*\s*)"
        if re.fullmatch(coord_reg_ex, coords):
            coords = coords.replace(" ", "")
            coords = coords.replace('\n', "")
            coords = coords.replace('\r', "")
            coords = coords.split(',')
            coords[0] = ord(coords[0].upper()) - 64
            coords[1] = int(coords[1]) - 1
            if self.valid_ranges(coords[1], coords[0]):
                coords = [coords[1], coords[0]]
                return True, coords
        return False, None

    def valid_ranges(self, row, column):
        row = row + 1
        if row < 0 or column < 0:
            return False
        if row <= len(self.graph) and column <= len(self.graph[0]):
            return True
        return False

    def adjust_sizes(self, height, width):
        self.characterLbl.setFixedSize(40, 40)
        self.goalLbl.setFixedSize(40, 40)

    def enable_change_btn(self):
        c_pos1, c_pos2 = self.character.get_last_position()
        g_pos1, g_pos2 = self.goal.get_last_position()
        if c_pos1 != None and c_pos2 != None and g_pos1 != None and g_pos2 != None:
            self.accept_btn.setEnabled(True)

#-------
#Goal
#-------

    def load_goal_lbl(self):
        self.goalLbl = QLabel(self.goal.get_path())
        self.goalLbl.setPixmap(QPixmap(self.goal.get_path()))
        self.goalLbl.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.goalLbl.setScaledContents(True)
        self.contentVLayout.addWidget(self.goalLbl)

    def load_goal_textline(self):
        self.goalTxt = QLineEdit()
        self.goalTxt.setEnabled(True)
        self.goalTxt.setMaximumSize(QSize(370, 30))
        self.goalTxt.setPlaceholderText("Columna , Fila. Ej: A , 1")
        self.contentVLayout.addWidget(self.goalTxt)

        self.goalTxt.textChanged.connect(self.goal_changed_textLine)

    def load_goal_errors(self):
        self.error_goal_exist_coord_lbl = QLabel("Coordenada inexistente")
        self.error_goal_exist_coord_lbl.setVisible(False)
        self.contentVLayout.addWidget(self.error_goal_exist_coord_lbl)

        self.error_goal_invalid_coord_lbl = QLabel(
            "Coordenada invalida para el personaje")
        self.error_goal_invalid_coord_lbl.setVisible(False)
        self.contentVLayout.addWidget(self.error_goal_invalid_coord_lbl)

    def goal_changed_textLine(self):
        coords = self.goalTxt.text()
        ok, coords = self.valid_coord(coords)
        if ok:
            self.error_goal_exist_coord_lbl.setVisible(False)
            self.error_goal_invalid_coord_lbl.setVisible(False)
            if self.Map.get_cost_coord(coords[0], coords[1] - 1) != None:
                if self.goal.get_label_idx() != None:
                    if self.mapGrd.itemAt(self.goal.get_label_idx()) != None:
                        self.delete_position_goal()
                self.load_goal(coords[0], coords[1])
            else:
                self.error_goal_invalid_coord_lbl.setVisible(True)
                if self.goal.get_label_idx() != None:
                    self.delete_position_goal()
        else:
            self.error_goal_exist_coord_lbl.setVisible(True)
            if self.goal.get_label_idx() != None:
                self.delete_position_goal()

    def load_goal_indications(self):
        self.indications_goal_lbl = QLabel(
            "Ingresa Coordenadas(Columna, Fila) Ejemplo : A , 1")
        self.indications_goal_lbl.setVisible(True)
        self.contentVLayout.addWidget(self.indications_goal_lbl)

    def load_goal(self, x, y):
        old_lbl = self.mapGrd.itemAtPosition(x, y)
        old_lbl = old_lbl.widget()
        self.mapGrd.addWidget(self.goal.create_lbl(), x, y)
        self.goal.set_last_position(x, y - 1)
        self.goal.set_label_idx(self.mapGrd.count() - 1)
        self.enable_change_btn()

    def delete_position_goal(self):
        self.goal.set_last_position(None, None)
        chIdx = self.character.get_label_idx()
        gIdx = self.goal.get_label_idx()
        if chIdx != None and gIdx != None:
            if gIdx < chIdx:
                self.character.set_label_idx(chIdx - 1)
        old_lbl = self.mapGrd.itemAt(self.goal.get_label_idx())
        old_lbl = self.mapGrd.indexOf(old_lbl)
        old_lbl = self.mapGrd.takeAt(old_lbl)
        old_lbl.widget().deleteLater()
        self.goal.set_label_idx(None)
        self.accept_btn.setEnabled(False)

#----------
#Character
#----------

    def load_character_lbl(self):
        self.characterLbl = QLabel(self.character.get_path())
        self.characterLbl.setPixmap(QPixmap(self.character.get_path()))
        self.characterLbl.setSizePolicy(QSizePolicy.Ignored,
                                        QSizePolicy.Ignored)
        self.characterLbl.setScaledContents(True)
        self.contentVLayout.addWidget(self.characterLbl)

    def load_character_textline(self):
        self.characterTxt = QLineEdit()
        self.characterTxt.setEnabled(True)
        self.characterTxt.setMaximumSize(QSize(370, 30))
        self.characterTxt.setPlaceholderText("Columna , Fila. Ej: A , 1")
        self.contentVLayout.addWidget(self.characterTxt)

        self.characterTxt.textChanged.connect(self.character_changed_textLine)

    def load_character_errors(self):
        self.error_exist_coord_lbl = QLabel("Coordenada inexistente")
        self.error_exist_coord_lbl.setVisible(False)
        self.contentVLayout.addWidget(self.error_exist_coord_lbl)

        self.error_invalid_coord_lbl = QLabel(
            "Coordenada invalida para el personaje")
        self.error_invalid_coord_lbl.setVisible(False)
        self.contentVLayout.addWidget(self.error_invalid_coord_lbl)

    def character_changed_textLine(self):
        coords = self.characterTxt.text()
        ok, coords = self.valid_coord(coords)
        if ok:
            self.error_exist_coord_lbl.setVisible(False)
            self.error_invalid_coord_lbl.setVisible(False)
            if self.Map.get_cost_coord(coords[0], coords[1] - 1) != None:
                if self.character.get_label_idx() != None:
                    if self.mapGrd.itemAt(
                            self.character.get_label_idx()) != None:
                        self.delete_position_character()
                self.load_character(coords[0], coords[1])
            else:
                self.error_invalid_coord_lbl.setVisible(True)
                if self.character.get_label_idx() != None:
                    self.delete_position_character()
        else:
            self.error_exist_coord_lbl.setVisible(True)
            if self.character.get_label_idx() != None:
                self.delete_position_character()

    def load_character_indications(self):
        self.indications_character_lbl = QLabel(
            "Ingresa Coordenadas(Columna, Fila) Ejemplo : A , 1")
        self.indications_character_lbl.setVisible(True)
        self.contentVLayout.addWidget(self.indications_character_lbl)

    def load_character(self, x, y):
        old_lbl = self.mapGrd.itemAtPosition(x, y)
        old_lbl = old_lbl.widget()
        self.mapGrd.addWidget(self.character.create_lbl(), x, y)
        self.character.set_last_position(x, y - 1)
        self.character.set_label_idx(self.mapGrd.count() - 1)
        self.enable_change_btn()

    def delete_position_character(self):
        self.character.set_last_position(None, None)
        chIdx = self.character.get_label_idx()
        gIdx = self.goal.get_label_idx()
        if gIdx != None and chIdx != None:
            if chIdx < gIdx:
                self.goal.set_label_idx(gIdx - 1)
        old_lbl = self.mapGrd.itemAt(self.character.get_label_idx())
        old_lbl = self.mapGrd.indexOf(old_lbl)
        old_lbl = self.mapGrd.takeAt(old_lbl)
        old_lbl.widget().deleteLater()
        self.character.set_label_idx(None)
        self.accept_btn.setEnabled(False)

#--------
# Accept Button
#-------

    def load_accept_btn(self):
        PrimaryBtnStyleEnabled = "QPushButton:enabled{background-color:#4e73df;border-radius:6px;color:#ffffff;font-family:Verdana;text-decoration:none;}"
        btnStyleDisabled = " QPushButton:disabled{background-color:#949494;border-radius:6px;font-family:Verdana;text-decoration:none; }"
        self.accept_btn = QPushButton("Aceptar")
        self.accept_btn.setEnabled(False)
        self.accept_btn.setStyleSheet(btnStyleDisabled +
                                      PrimaryBtnStyleEnabled)
        #self.accept_btn.setEnabled(True)
        self.accept_btn.clicked.connect(self.allow_change)
        self.contentVLayout.addWidget(self.accept_btn)

    def allow_change(self):
        self.simulations_options = OptionsDialog(self)


#--------
# SIMULATIONS
#-------

    def manual_simulation(self, sm=0):
        from scripts.simulation import SimulationWindow
        g_pos1, g_pos2 = self.goal.get_last_position()
        self.Map.set_goal(g_pos1, g_pos2)
        self.simulation = SimulationWindow(self.Map, self.character, self.goal,
                                           sm)
        self.close()

    def set_priority_list(self, l):
        self.priority_list = l

    def automatic_simulation(self):
        self.close()
        from scripts.simulation import SimulationWindow
        g_pos1, g_pos2 = self.goal.get_last_position()
        self.Map.set_goal(g_pos1, g_pos2)
        self.simulation = SimulationWindow(self.Map, self.character, self.goal,
                                           self.simulation_option,
                                           self.priority_list, self.distance)

    def priority_selection(self, sm):
        self.simulation_option = sm
        if sm >= 5:
            self.distances_options = DistancesDialog(self)
        else:
            self.priority_options = PriorityDialog(self)

    def set_distance(self, d):
        self.distance = d
        self.priority_options = PriorityDialog(self)