Beispiel #1
0
 def default_values(self):
   "Set some default values in the database"
   
   # Add some information
   box = hub.getConnection()
   t1 = Team(city='Pittsburgh', nickname='Ferrous Metals')
   box.memorize(t1)
   t2 = Team(city='Seattle', nickname='Seagulls')
   box.memorize(t2)
   p1 = Player(name='Bob Waffleburger', birthdate=datetime.date(1982,3,2), points=21)
   box.memorize(p1)
   p2 = Player(name='Mike Handleback', birthdate=datetime.date(1975,9,25), points=10)
   box.memorize(p2)
   p1.team = t1.ID
   p2.team = t2.ID
   
   # Add a default Page
   page = Page( pagename="FrontPage", data="This is the main page, please edit it." )
   box.memorize( page )
   
   # Setup identity data 
   jrodrigo = TG_User( user_name = "jrodrigo" )
   box.memorize( jrodrigo )
   jrodrigo.password = "******"
   
   root = TG_User( user_name = "root" )
   box.memorize( root )
   root.password = "******"
   
   user = TG_Group( group_name = "user" )
   box.memorize( user )
   
   admin = TG_Group( group_name = "admin" )
   box.memorize( admin )
   
   format = TG_Permission( permission_name = "format" )
   box.memorize( format )
   ls = TG_Permission( permission_name = "ls" )
   box.memorize( ls )
   cat = TG_Permission( permission_name = "cat" )
   box.memorize( cat )
   
   o = TG_UserGroup( user_id = root.user_id, group_id = user.group_id )
   box.memorize( o )
   o = TG_UserGroup( user_id = root.user_id, group_id = admin.group_id )
   box.memorize( o )
   o = TG_UserGroup( user_id = jrodrigo.user_id, group_id = user.group_id )
   box.memorize( o )
   
   o = TG_GroupPermission( group_id = admin.group_id, permission_id = format.permission_id )
   box.memorize( o )
   o = TG_GroupPermission( group_id = user.group_id, permission_id = ls.permission_id )
   box.memorize( o )
   o = TG_GroupPermission( group_id = user.group_id, permission_id = cat.permission_id )
   box.memorize( o )
   
   return "done"
Beispiel #2
0
    def __init__(self, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10):

        self.t1 = T.Team(p1, p2, p3, p4, p5)
        self.t2 = T.Team(p6, p7, p8, p9, p10)

        self.score = 0
        self.rating = 0
        self.level_diff = 0
        self.role_pref = 0
        self.value_diff = 0
        self.synergy = 0
        self.other_value_diff = 0

        self.calc_score()
Beispiel #3
0
def edit_team():
    getid = request.args.get('id')
    teamData = db_session.query(Team).filter(Team.id == getid).\
     with_entities(Team.title, Team.id).first()
    form = EditTeamForm()
    if teamData:
        form.id.data = teamData.id
        form.title.data = teamData.title

    db_session.close()
    if form.validate_on_submit():
        id = request.form.get('id')
        title = request.form.get('title')
        team = Team(title=title)
        db_session.query(Team).filter(Team.id == id).update(
            {Team.title: title})
        db_session.commit()
        # 记录日志
        actions = ('%s%s%s' % ('修改产品组', ':', title))
        savelog(actions)
        db_session.close()

        flash("修改成功,<span id='time'>3</span>秒后自动跳转管理页。")
        return redirect('/manage/edit_team')
    return render_template("edit_team.html",
                           pagename='manage_team',
                           this='edit',
                           form=form)
Beispiel #4
0
def add_slack():
    try:
        code = request.args.get('code')
        # state = request.args.get('state')

        # An empty string is a valid token for this request
        temp_sc = SlackClient("")

        # Request the auth tokens from Slack
        auth_response = temp_sc.api_call("oauth.access",
                                         client_id=SLACK_CLIENT_ID,
                                         client_secret=SLACK_CLIENT_SECRET,
                                         code=code)

        user_token = auth_response['access_token']
        bot_token = auth_response['bot']['bot_access_token']
        team_id = auth_response['team_id']
        team_name = auth_response['team_name']
        team = Team(code=code,
                    bot_token=bot_token,
                    user_token=user_token,
                    team_name=team_name,
                    team_id=team_id)
        team.save()
        return render_template('add_successful.html')
    except:  # noqa: #722
        return render_template('error.html')
Beispiel #5
0
def add_team():
    form = AddTeamForm()
    if form.validate_on_submit():
        title = request.form.get('title')
        team = Team(title=title, addtime=datetime.datetime.now())
        team_check = db_session.query(Team).filter(Team.title == title).first()
        if team_check:
            flash('产品组已存在')
            return redirect('/manage/add_team')
        if len(title):
            try:
                db_session.add(team)
                db_session.commit()
                # 记录日志
                actions = ('%s%s%s' % ('增加产品组', ':', title))
                savelog(actions)
                db_session.close()
            except:
                flash("数据库错误!")
                return redirect('/manage/add_team')

            flash("添加成功,<span id='time'>3</span>秒后自动跳转管理页。")
            return redirect('/manage/add_team')
    return render_template("edit_team.html",
                           pagename='manage_team',
                           this='add',
                           form=form)
    def parseTeam(self, teamName):
        if isinstance(teamName, Team):
            team = teamName
        else:
            team = Team(teamName)

        return self.teamSrv[team]
Beispiel #7
0
def load_teams(teams_json):
    """load teams json into data base"""

    py_dict = json.loads(open(teams_json).read())
    for team in py_dict:
        team_id = team['id']
        name = team['name']
        country_code = team['country_code']
        result = team['result']
        position = result['position']
        points_check = result.get('points', 0)
        podiums_check = result.get('podiums', 0)
        victories_check = result.get('victories', 0)

        team = Team(team_id=team_id,
                    name=name,
                    country_code=country_code,
                    position=position,
                    points=points_check,
                    podiums=podiums_check,
                    victories=victories_check)
        print(team)

        db.session.add(team)
    db.session.commit()
Beispiel #8
0
    def POST(self, playerName, teamName, teamNameConfirm):
        try:
            connection = functions.Worker()
            playerTagObject = PlayerTag()
            playerTagObject.SetPlayerTag(playerName)

            teamObject = Team()
            teamObject.SetTeamName(teamName)
        except:
            template = jinja_environment.get_template(
                'templates/createnewteam.html')
            return template.render({
                'playerTagHeader':
                playerTagObject.GetPlayerTag(),
                'errorMatch': ("Unexpected error:", sys.exc_info()[1])
            })

        if (teamName != teamNameConfirm):
            template = jinja_environment.get_template(
                'templates/createnewteam.html')
            return template.render({
                'playerTagHeader':
                playerTagObject.GetPlayerTag(),
                'errorTeam':
                'Team Name does not match!'
            })

        elif (teamName == ""):
            template = jinja_environment.get_template(
                'templates/createnewteam.html')
            return template.render({
                'playerTagHeader':
                playerTagObject.GetPlayerTag(),
                'errorTeam':
                'Empty Name not accepted!'
            })

        else:
            #Find Duplicates
            teams = connection.FindTeam(teamObject)
            if (str(teams) != 'None'):
                template = jinja_environment.get_template(
                    'templates/createnewteam.html')
                return template.render({
                    'playerTagHeader':
                    playerTagObject.GetPlayerTag(),
                    'errorTeam':
                    'This team already exist!'
                })
            else:
                teamObject.SetAdministrator(playerTagObject.GetPlayerTag())
                teamObject.SetMembers(playerTagObject.GetPlayerTag())
                connection.InsertTeam(teamObject)

                playerDB = connection.FindPlayerTagNoPass(playerTagObject)
                playerDB['Teams'].append(teamObject.GetTeamName())
                connection.UpdatePlayerTag(playerDB)

                raise cherrypy.HTTPRedirect("/dash/", 302)
 def get_teams_by_league_and_names(self, league, names):
     teams = []
     for name in names:
         result = self.session.query(Team).filter(
             Team.league == league).filter(Team.name == name).first()
         teams.append(result if result is not None else Team(league=league,
                                                             name=name))
     return teams
Beispiel #10
0
    def test_basics(self):
        team = Team()
        team.id = 1
        team.code = 'MAR'
        team.name = "Martian War Machines"
        team.name_full = "Martian War Machines"
        team.name_brief = "Mars"
        self.session.add(team)

        team2 = Team()
        team2.id = 2
        team2.code = 'VEN'
        team2.name = "Venusian Pressure Cookers"
        team2.name_full = "Venusian Pressure Cookers"
        team2.name_brief = "Venus"
        self.session.add(team2)
        self.session.flush()
Beispiel #11
0
 def POST(self,playerName, currentTeam, selectedMember):
     try:
         connection = functions.Worker()
         playerTagObject = PlayerTag()                                  
         playerTagObject.SetPlayerTag(playerName)
         
         currentTeamObject = Team()                                  
         currentTeamObject.SetTeamName(currentTeam)
 
         selectedMemberObject = PlayerTag()                                  
         selectedMemberObject.SetPlayerTag(selectedMember)
         
         teamDB = connection.FindTeam(currentTeamObject)
         members = []
         for member in teamDB['Members']:
             if(members.__contains__(member)):continue
             else: members.append(member)
     except:
         template = jinja_environment.get_template('templates/manageateam.html')
         return template.render({'the_title': 'Manage A Team.',
                                 'playerTagHeader': playerName,
                                 'errorMatch': ("Unexpected error:", sys.exc_info()[1]),
                                 'team' : currentTeam,
                                 'members' : members})
      
     if(teamDB['Administrator'] != playerName):
         template = jinja_environment.get_template('templates/manageateam.html')
         return template.render({'the_title': 'Manage A Team.',
                                 'playerTagHeader': playerName,
                                 'errorMatch': 'Administrators privilege required in order to remove members.',
                                 'team' : currentTeam,
                                 'members' : members})
     else:   
         if(teamDB['Administrator'] == selectedMember):
             template = jinja_environment.get_template('templates/manageateam.html')
             return template.render({'the_title': 'Manage A Team.',
                                     'playerTagHeader': playerName,
                                     'errorMatch': 'Administrators cannot be removed. Delete the Team instead!',
                                     'team' : currentTeam,
                                     'members' : members})
         else:
             t = [] 
             t = teamDB['Members']
             for item in t:
                 if(item.__contains__(selectedMember)):
                     #Get the member
                     t.remove(item)
                     
                     playerTagObject = PlayerTag()                                  
                     playerTagObject.SetPlayerTag(str(item))
                     playerDB = connection.FindPlayerTagNoPass(playerTagObject)
                     playerDB['Teams'].remove(teamDB['TeamName'])
                     connection.UpdatePlayerTag(playerDB)
                     
             teamDB['Members'] = t
             connection.UpdateTeam(teamDB)
             raise cherrypy.HTTPRedirect("/dash/", 302)   
Beispiel #12
0
def marc_algo(pizza_list, nb_2group, nb_3group, nb_4group, hist):
    teams_list = []
    # Add Pizza to each Team
    for i in range(nb_2group):
        if len(pizza_list) > 2:
            t = Team(2)
            p1 = pizza_list[0]
            p2 = pizza_list[1]
            t.add_pizza(p1)
            t.add_pizza(p2)
            pizza_list.remove(p1)
            pizza_list.remove(p2)
            teams_list.append(t)
    for i in range(nb_3group):
        if len(pizza_list) > 3:
            t = Team(3)
            p1 = pizza_list[0]
            p2 = pizza_list[1]
            p3 = pizza_list[2]
            t.add_pizza(p1)
            t.add_pizza(p2)
            t.add_pizza(p3)
            pizza_list.remove(p1)
            pizza_list.remove(p2)
            pizza_list.remove(p3)
            teams_list.append(t)
    for i in range(nb_4group):
        if len(pizza_list) > 4:
            t = Team(4)
            p1 = pizza_list[0]
            p2 = pizza_list[1]
            p3 = pizza_list[2]
            p4 = pizza_list[3]
            t.add_pizza(p1)
            t.add_pizza(p2)
            t.add_pizza(p3)
            t.add_pizza(p4)
            pizza_list.remove(p1)
            pizza_list.remove(p2)
            pizza_list.remove(p3)
            pizza_list.remove(p4)
            teams_list.append(t)

    return teams_list
Beispiel #13
0
 def setup_teams(teamnames):
     """Teamnames is {teamid: team_name} dict"""
     app.logger.info("Setup teams: {}".format(teamnames))
     game = Game.query.one()
     if game.state == GameState.uninitialized:
         for _tid, _tn in teamnames.items():
             team = Team(_tid, _tn)
             db.session.add(team)
         db.session.commit()
     else:
         raise GameProblem("Trying to setup a game that is already started")
     return True
Beispiel #14
0
    def init_team(self, team):
        """Create team if not exists."""

        team_stored = Team.all().filter('name =', team['name']).get()
        if team_stored is None:
            team_stored = Team(name=team['name'])
            short_match = re.search(r'([a-z]{3})\.gif$', team['flag'])
            team_stored.flag = team['flag']
            team_stored.short = short_match.group(1)
            team_stored.href = team['href']
            team_stored.put()

        return team_stored
Beispiel #15
0
    def POST(self, playerName, selectedTeam):
        try:
            connection = functions.Worker()
            playerTagObject = PlayerTag()
            playerTagObject.SetPlayerTag(playerName)

            selectedTeamObject = Team()
            selectedTeamObject.SetTeamName(selectedTeam)

            teamNames = connection.GetAllTeams()
            team = connection.GetTeams(playerTagObject)
            for item in team:
                if (teamNames.__contains__(item)):
                    teamNames.remove(item)
        except:
            template = jinja_environment.get_template(
                'templates/joinateam.html')
            return template.render({
                'playerTagHeader':
                playerTagObject.GetPlayerTag(),
                'errorMatch': ("Unexpected error:", sys.exc_info()[1]),
                'teams':
                teamNames
            })

        #Check if this user is part of this current team
        teamMember = connection.GetTeams(playerTagObject)

        if (teamMember.__contains__(selectedTeam)):
            template = jinja_environment.get_template(
                'templates/joinateam.html')
            return template.render({
                'the_title':
                'Join A Team.',
                'playerTagHeader':
                playerTagObject.GetPlayerTag(),
                'errorMatch':
                'Player Tag is already a member of this Team!',
                'teams':
                teamNames
            })
        else:
            teamDB = connection.FindTeam(selectedTeamObject)
            teamDB['Members'].append(playerName)
            connection.UpdateTeam(teamDB)

            playerDB = connection.FindPlayerTagNoPass(playerTagObject)
            playerDB['Teams'].append(teamDB['TeamName'])
            connection.UpdatePlayerTag(playerDB)
            raise cherrypy.HTTPRedirect("/dash/", 302)
    def __init__(self, settings):

        # ----- init simulator -----
        self.simulation_id = settings['simulation_id'] if settings[
            'simulation_id'] else random.randint(1000, 9999)
        self.time = 0.0
        self.time_step = 1.0
        random.seed(self.simulation_id)

        # ----- create scenario -----
        scenario = Scenario(settings['scenario_type'], settings['scenario_id'])
        self.scenario_type = scenario.scenario_type
        self.scenario_id = scenario.scenario_id
        self.time_max = scenario.time_max

        # ----- init logger -----
        self.logger = Logger(settings['logger_verbose_level'])

        # ----- init reporter -----
        reporter_settings = {
            'print_enabled': settings['reporter_print'],
            'export_enabled': settings['reporter_export']
        }
        reporter_init_data = {
            'experiment_id':
            settings['experiment_id'],
            'scenario_type':
            self.scenario_type,
            'scenario_id':
            self.scenario_id,
            'time_max':
            self.time_max,
            'simulation_id':
            self.simulation_id,
            'planner':
            settings['planner'],
            'agents_ids': [
                agent_specs['id']
                for agent_specs in scenario.team_specs['agents_specs']
            ],
        }
        self.reporter = Reporter(reporter_settings, reporter_init_data)

        # ----- init behavior & team -----
        self.behavior = Behavior(scenario.behavior_specs,
                                 scenario.actions_names, self.logger)
        self.team = Team(scenario.team_specs, settings['planner'], self.logger,
                         self.reporter)
Beispiel #17
0
    def init_team(self, team):
        """Create team if not exists."""

        team_stored = Team.all().filter('name =', team['name']).get()
        if team_stored is None:
            team_stored = Team(name=team['name'])
            short_match = re.search(r'([a-z]{3})\.png$', team['flag'])
            team_stored.flag = team['flag']
            team_stored.short = short_match.group(1)
            team_stored.href = "http://www.uefa.com/" + team['href']
            team_stored.teamId = re.match(
                r'/uefaeuro/season=2012/teams/team=([0-9]+)/index.html',
                team['href']).group(1)
            team_stored.put()

        return team_stored
def to_team(json_dict: dict) -> Team:
    """
    Converts json dictionary to Team object
    :param json_dict:
    :return: Team
    """
    if json_dict is None:
        return None

    team_link = json_dict['_links']['self']['href']
    team_id = team_link[team_link.rfind('/') + 1:]

    result = Team(team_id, json_dict['name'], json_dict['shortName'],
                  json_dict['squadMarketValue'], json_dict['crestUrl'])

    return result
Beispiel #19
0
def create_team(name, coach_id, activities_last_updated):
    """Create and return a team."""

    team = Team(
        name=name,
        coach_id=coach_id,
        activities_last_updated=activities_last_updated,
    )
    # logo=logo,
    # team_banner_img=team_banner_img,
    # team_color=team_color,

    db.session.add(team)
    db.session.commit()

    return team
Beispiel #20
0
def load_Team():
    """Load teams info from team.csv into database."""

    print "teams"

    Team.query.delete()

    for row in open("seed_data/team"):
        row = row.strip()
        items = row.split(",")

        team = Team(team_id=items[0], team_name=items[1], team_size=items[2])

        db.session.add(team)

    db.session.commit()
Beispiel #21
0
    def create_team(self, name, team_id=None):
        """
        Adds a new team to the database

        :type name: str
        :param name: Name of the team
        """

        if not team_id:
            team_id = convert_name_to_id(name)

        if not self.team_exists(team_id):
            new_team = Team(id=team_id,
                            name=name)

            self.session.add(new_team)
            self.session.flush()
        return team_id
Beispiel #22
0
def seed_teams():

    with open("data/seed-teams.json") as f:
        team_data = json.loads(f.read())

    for team in team_data:

        team = Team(
            name=team["name"],
            coach_id=team["coach_id"],
            logo=team["logo"],
            team_banner_img=team["team_banner_img"],
            team_color=team["team_color"],
            activities_last_updated=team["activities_last_updated"],
        )

        db.session.add(team)
        db.session.commit()
Beispiel #23
0
def calc_best_n_teams(n):
    time_start = time.time()

    counter = 1
    all_combinations = itertools.permutations(C.OG, 5)
    score_total = 0
    teams = []
    for i in all_combinations:
        counter += 1
        if counter % 10000 == 0:  # Print every 1000 combinations
            print("Evaluated " + str(counter) + " combinations")
            if len(teams) > 0:
                print("Current Average " + str(score_total / len(teams))
                      )  # Average over time... Should only improve
                print("Current Best\n" + teams[0].to_string())

        # Create a set with the permutation.
        team = T.Team(C.players[i[0]], C.players[i[1]], C.players[i[2]],
                      C.players[i[3]], C.players[i[4]])

        score = get_score(team)

        if len(teams) < n:
            teams.append(team)
            score_total += score

        else:
            teams.sort(key=get_score, reverse=True)
            last_place = get_score(teams[-1])
            if last_place < score:
                # Pop Lowest score and replace with a new score...
                s = teams.pop()
                score_total -= last_place
                teams.append(team)
                score_total += score
            elif last_place == score:
                # Append to the end.
                score_total += score
                teams.append(team)

    teams.sort(key=get_score, reverse=True)
    print("Time Taken " + str(time.time() - time_start) + "s")
    return teams
Beispiel #24
0
def round():
    msg = request.form['text']
    commands = msg.split(' ')
    team_id = request.form['team_id']
    team = db.session.query(Team).filter(Team.team_id == team_id).one_or_none()
    team = Team(team_id) if team is None else team
    team_contents = team.get_contents()
    round = team_contents.get('round', 0)
    if commands[0] == 'start':
        round = 1
    elif commands[0] == 'end':
        round = 0
    elif len(commands[0]) == 0:
        round += 1
    else:
        round = get_int(commands[0], 1)
    team_contents['round'] = round
    team.set_contents(team_contents)
    db.session.add(team)
    db.session.commit()
    if commands[0] == 'end':
        characters = db.session.query(Character).all()
        for character in characters:
            contents = character.get_contents()
            if 'last_init' in contents:
                del (contents['last_init'])
                character.set_contents(contents)
                db.session.add(character)
        if 'tmp_inits' in team_contents:
            del (team_contents['tmp_inits'])
            team.set_contents(team_contents)
            db.session.add(team)
        db.session.commit()
        return make_response('*Rounds cleared!*')

    attachments = [{'title': f'Round {round}', 'color': '#f48704'}]
    attachments += stat(True)
    raw_data = {'response_type': 'in_channel', 'attachments': attachments}
    encoded = json.dumps(raw_data)
    resp = Response(encoded, content_type='application/json')
    return resp
Beispiel #25
0
def write_data():
    """Write trial user data"""

    athlete1 = Athlete(a_fname="Brian",
                       a_lname="Bestie",
                       a_phone="+17196440060",
                       a_email="*****@*****.**",
                       team_id=1,
                       language="de")
    team1 = Team(team_name="Affy",
                 coach_fname="Kari",
                 coach_lname="Bestova",
                 coach_phone="+18595823016",
                 coach_email="*****@*****.**",
                 password=bcrypt.hashpw('sugar', bcrypt.gensalt()))

    # db.session.add_all([coach1])
    # db.session.commit()
    db.session.add_all([team1])
    db.session.commit()
    db.session.add_all([athlete1])
    db.session.commit()
Beispiel #26
0
def register_team_process():
    """Registration processing page"""

    # member = request.form.get('coach')
    fname = request.form.get('firstname')
    lname = request.form.get('lastname')
    phone = request.form.get('phone')
    email = request.form.get('email')
    team = request.form.get('team-name')
    password = request.form.get('password')

    hashed_pass = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

    new_coach = Team(team_name=team, coach_fname=fname, coach_lname=lname,
                      coach_phone=phone, coach_email=email, password=hashed_pass)
    db.session.add(new_coach)
    db.session.commit()

    session['name'] = new_coach.coach_fname
    session['id'] = new_coach.team_id

    return render_template('teamboard.html', team=team)
Beispiel #27
0
    def GET(self,playerName,currentTeam):
        try:
            connection = functions.Worker()
            currentTeamObject = Team()                                  
            currentTeamObject.SetTeamName(currentTeam)
            teamDB = connection.FindTeam(currentTeamObject)
            members = []
            for member in teamDB['Members']:
                if(members.__contains__(member)):continue
                else: members.append(member)

        except:
            template = jinja_environment.get_template('templates/manageateam.html')
            return template.render({'the_title': 'Manage A Team.',
                                    'playerTagHeader': playerName,
                                    'errorMatch': ("Unexpected error:", sys.exc_info()[1]),
                                    'team' : currentTeam,
                                    'members' : members})
                                       
        template = jinja_environment.get_template('templates/manageateam.html')
        return template.render({'the_title': 'Manage A Team.',
                                'playerTagHeader' : playerName,
                                'team' : currentTeam,
                                'members' : members})
Beispiel #28
0
         ('Florida', 'East', 6, first), ('Butler', 'East', 10, first),
         ('Virginia', 'South', 1, first), ('Creighton', 'South', 8, first),
         ('Davidson', 'South', 12, first), ('Arizona', 'South', 4, first),
         ('Miami', 'South', 6, first), ('Wright State', 'South', 14, first),
         ('Texas', 'South', 10, first), ('Georgia St.', 'South', 15, first),
         ('TXSO', 'West', 16, play_in), ('Missouri', 'West', 8, first),
         ('S. Dakota St.', 'West', 12, first),
         ('UNC-Greens.', 'West', 13, first), ('SDSU', 'West', 11, first),
         ('Montana', 'West', 14, first), ('Providence', 'West', 10, first),
         ('Lipscomb', 'West', 15, first), ('Penn', 'Midwest', 16, first),
         ('NC State', 'Midwest', 9, first), ('NM State', 'Midwest', 12, first),
         ('Charleston', 'Midwest', 13, first), ('TCU', 'Midwest', 6, first),
         ('Bucknell', 'Midwest', 14, first),
         ('Oklahoma', 'Midwest', 10, first), ('Iona', 'Midwest', 15, first),
         ('Radford', 'East', 16, play_in), ('Virginia Tech', 'East', 8, first),
         ('Murray St.', 'East', 12, first), ('Wichita St.', 'East', 4, first),
         ('St. Bon.', 'East', 11, play_in), ('SF Austin', 'East', 14, first),
         ('Arkansas', 'East', 7, first), ('CSU-Full.', 'East', 15, first),
         ('NC Central', 'West', 16, play_in),
         ('Arizona St.', 'Midwest', 11, play_in),
         ('Long Island', 'East', 16, play_in), ('UCLA', 'East', 11, play_in)]

for college in teams:
    Team(team=college[0],
         seed=college[2],
         region=college[1],
         advanced_to_round=college[3],
         price=0,
         money_award=0,
         owner='TBD')
Beispiel #29
0
def init():
    print(request.form)
    msg = request.form['text']

    username = request.form['user_name']
    user_id = request.form['user_id']
    team_id = request.form['team_id']
    commands = msg.split(' ')

    character = get_character(username)
    contents = character.get_contents()
    contents['user_id'] = user_id
    if 'user_id' not in contents:
        name = character.name
    else:
        name = f'<@{contents["user_id"]}|{character.name}>'

    if len(commands[0]) == 0 or commands[0] == 'roll' or commands[0][0] in (
            '+', '-'):
        if len(commands[0]) > 0 and commands[0][0] in ('+', '-'):
            init_mod = get_int(commands[0], 0)
        else:
            init_mod = int(contents.get('init_mod', 0))
        title = '{} rolls 1d20 {}'.format(name, modifier(init_mod))
        roll = random.randint(1, 20)
        last_init = roll + init_mod
        fields = [{
            'title': 'Rolls',
            'value': f'{roll}',
            'short': True
        }, {
            'title': 'Result',
            'value': f'{last_init}',
            'short': True
        }]
        contents['last_init'] = last_init
        set_and_commit(character, contents)
        color = get_color(roll / 20)
        return make_response(fields, title, color=color)

    if len(commands) > 1 and commands[0] == 'mod':
        init_mod = get_int(commands[1], 0)
        contents['init_mod'] = init_mod
        set_and_commit(character, contents)
        fields = [{'value': signed(init_mod)}]
        return make_response(fields, f'{name}\'s Initiative modifier')

    if commands[0] == 'set':
        if len(commands) == 2:
            last_init = get_int(commands[1], 0)
            contents['last_init'] = last_init
            set_and_commit(character, contents)
            fields = [{'value': str(last_init)}]
        elif len(commands) > 2:

            team = db.session.query(Team).filter(
                Team.team_id == team_id).one_or_none()
            team = Team(team_id) if team is None else team
            team_contents = team.get_contents()

            tmp_inits = team_contents.get('tmp_inits', {})

            last_init = get_int(commands[1], 0)
            target = ' '.join(commands[2:])
            if target.startswith('@'):
                target = target[1:]

            name = character.name
            name = f'{target}({name})'
            tmp_inits[name] = last_init

            team_contents['tmp_inits'] = tmp_inits
            team.set_contents(team_contents)
            db.session.add(team)
            db.session.commit()

            fields = [{'value': str(last_init)}]

        return make_response(fields, f'{name}\'s Initiative value')

    if commands[0] in ('party', 'all'):
        characters = db.session.query(Character).all()

        team = db.session.query(Team).filter(
            Team.team_id == team_id).one_or_none()
        team = Team(team_id) if team is None else team
        team_contents = team.get_contents()

        tmp_inits = team_contents.get('tmp_inits', {})
        log.info('tmp_inits: {}'.format(str(tmp_inits)))

        char_inits = []
        for character in characters:
            contents = character.get_contents()
            if 'last_init' in contents:
                last_init = int(contents['last_init'])
                if 'user_id' not in contents:
                    name = character.name
                else:
                    name = f'<@{contents["user_id"]}|{character.name}>'
                char_inits.append((name, last_init))
        for tmp_char in tmp_inits:
            char_inits.append((tmp_char, tmp_inits[tmp_char]))

        sorted_inits = sorted(char_inits, key=lambda tup: tup[1], reverse=True)

        merged_inits = [f'{name} ({init})' for name, init in sorted_inits]
        formatted_inits = ' > '.join(merged_inits)

        fields = [{'value': formatted_inits}]
        return make_response(fields, 'Round initiatives')
    if commands[0] in ('CLEAR', 'REMOVE'):
        if 'last_init' in contents:
            del (contents['last_init'])
            character.set_contents(contents)
            db.session.add(character)
        db.session.commit()
        return make_response('Your initiative is removed')

    if commands[0] in ('ALLCLEAR', 'ALLREMOVE', 'CLEARALL', 'REMOVEALL'):
        characters = db.session.query(Character).all()
        for character in characters:
            contents = character.get_contents()
            if 'last_init' in contents:
                del (contents['last_init'])
                character.set_contents(contents)
                db.session.add(character)
        db.session.commit()
        return make_response('All initiatives are removed')

    return process_unknown(username)
Beispiel #30
0
def stat(dict_form=False):
    # msg = request.form['text']
    attachments = []
    characters = db.session.query(Character).all()
    if not dict_form:
        team_id = request.form['team_id']
        team = db.session.query(Team).filter(
            Team.team_id == team_id).one_or_none()
        team = Team(team_id) if team is None else team
        contents = team.get_contents()
        round = contents.get('round', 1)
        if round > 0:
            attachments = [{'title': f'Round {round}', 'color': '#f48704'}]

    # read hp
    ratios = []
    fields = []
    for character in characters:
        contents = character.get_contents()
        if 'hp' in contents:
            hp = str(contents['hp'])
            max_hp = str(contents.get('max_hp', hp))
            name = character.name
            field = {'title': name, 'value': f'{hp}/{max_hp}', 'short': True}
            score = int(hp) / int(max_hp) if int(max_hp) != 0 else 1.0
            ratios.append(score)
            fields.append(field)
    score = sum(ratios) / len(ratios) if len(ratios) > 0 else 0

    attach_hp = {
        'title': 'Party HP',
        'fields': fields,
        'color': get_color(score)
    }

    attachments.append(attach_hp)

    # read initiatives
    characters = db.session.query(Character).all()

    char_inits = []
    for character in characters:
        contents = character.get_contents()
        if 'last_init' in contents:
            last_init = int(contents['last_init'])
            if 'user_id' not in contents:
                name = character.name
            else:
                name = f'<@{contents["user_id"]}|{character.name}>'
            char_inits.append((name, last_init))
    sorted_inits = sorted(char_inits, key=lambda tup: tup[1], reverse=True)

    merged_inits = [f'{name} ({init})' for name, init in sorted_inits]
    formatted_inits = ' > '.join(merged_inits)

    fields = [{'value': formatted_inits}]

    if len(formatted_inits) > 0:
        attach_init = {
            'title': 'Round initiatives',
            'fields': fields,
            'color': BLUE
        }

        attachments.append(attach_init)
    if dict_form:
        return attachments

    raw_data = {'response_type': 'in_channel', 'attachments': attachments}
    encoded = json.dumps(raw_data)
    log.info(encoded)
    resp = Response(encoded, content_type='application/json')
    return resp