async def init(self): for p in self.p_list: self.players[p.id] = p await p.on_match_selected(self.match.proxy) # print(f"{p.name}, matches: {p.stats.nb_matches_played}") # ctx = ContextWrapper.user(p.id) # try: # await disp.MATCH_DM_PING.send(ctx, match.id, match.channel.name) # except discord.errors.Forbidden: # log.warning(f"Player id:[{p.id}], name:[{p.name}] is refusing DMs") # Open match channel await roles.modify_match_channel(self.match.channel, view=True) await disp.LB_MATCH_STARTING.send( ContextWrapper.channel(cfg.channels["lobby"]), self.match.channel.id) players_ping = " ".join(p.mention for p in self.players.values()) await disp.MATCH_INIT.send(self.match.channel, players_ping) # Initialize teams self.match.teams[0] = Team(0, f"Team 1", self.match.proxy) self.match.teams[1] = Team(1, f"Team 2", self.match.proxy) await self.info() self.auto_captain.start() await disp.CAP_AUTO_ANNOUNCE.send(self.match.channel)
def loadTeams(): global teams teams = {} teamsPage = reddit.getWikiPage(globals.CONFIG_SUBREDDIT, "teams") requirements = { 'tag': "[a-z]+", 'name': "[\w -]+", } for teamLine in teamsPage.splitlines(): items = teamLine.split('|') if len(items) < 5: log.warning("Could not parse team line: {}".format(teamLine)) continue offense = parseOffense(items[2].lower()) if offense is None: log.warning("Invalid offense type for team {}: {}".format( items[0], items[2])) continue defense = parseDefense(items[3].lower()) if defense is None: log.warning("Invalid defense type for team {}: {}".format( items[0], items[2])) continue team = Team(tag=items[0], name=items[1], offense=offense, defense=defense) for requirement in requirements: if not validateItem(getattr(team, requirement), requirements[requirement]): log.debug("Could not validate team on {}: {}".format( requirement, team)) continue for coach in items[4].lower().split(','): coach = coach.strip() team.coaches.append(coach) teams[team.tag] = team coach1 = "watchful1" team1 = Team(tag="team1", name="Team 1", offense=OffenseType.OPTION, defense=DefenseType.THREE_FOUR) team1.coaches.append(coach1) teams[team1.tag] = team1 coach2 = "watchful12" team2 = Team(tag="team2", name="Team 2", offense=OffenseType.SPREAD, defense=DefenseType.FOUR_THREE) team2.coaches.append(coach2) teams[team2.tag] = team2
def load_file(file, sheet="Sheet1"): team_manager = TeamManager() # load excel sheet into an iterable object wb = load_workbook(filename=file, read_only=True) ws = wb.active # loop through every row for row in ws.iter_rows(min_row=2): teamA = row[0].value # Name of Team A scoreA = row[1].value # Team A's Score scoreB = row[2].value # Team B's Score teamB = row[3].value # Name of Team B TeamA = team_manager.get_team(teamA) TeamB = team_manager.get_team(teamB) # if a team with the given name wasn't found in the list than create the team if not TeamA: TeamA = Team(teamA) if not TeamB: TeamB = Team(teamB) Match = Game(TeamA, TeamB, scoreA, scoreB) TeamA.add_game(Match) TeamB.add_game(Match) team_manager.add_team(TeamA) team_manager.add_team(TeamB) return team_manager
def write_file(teams, filename): wb = Workbook() ws = wb.active ws["A1"] = "Rank" ws["B1"] = "Team" ws["C1"] = "Score" rank = 1 previous = Team("Empty") for i, team in enumerate(teams, start=2): rank_pos = "A" + str(i) team_pos = "B" + str(i) score_pos = "C" + str(i) if previous.points == team.points: ws[rank_pos] = rank - 1 else: ws[rank_pos] = rank ws[team_pos] = team.get_name() ws[score_pos] = "%.2f" % team.get_points() rank += 1 previous = team wb.save(filename)
def parse_teams(csv_filename): with open(csv_filename, newline='') as fd: data = fd.read() csvreader = csv.reader(StringIO(data), delimiter=';') teams = {} event_title = '' for row in csvreader: if row[0] == 'event_title': event_title = row[1] continue member = Member() if len(row) >= first_cp_column: member.first_name = '' member.last_name = row[fields_order['name']].title() member.bib = row[fields_order['bib']] print(member.bib, member.last_name) member.team_bib = member.bib member.team_name = '' member.points = row[fields_order['points']] member.time = str_to_time(row[fields_order['time']]) start_time = str_to_time(row[fields_order['start_time']]) prev_time = start_time for i in range(first_cp_column, len(row), 2): cp = Checkpoint() cp.id = row[i] if cp.id: cp.id = int(cp.id) cp.points = cp.id // 10 abs_time = prev_time if row[i + 1]: abs_time = str_to_time(row[i + 1]) cp.split = abs_time - prev_time prev_time = abs_time cp.time = abs_time - start_time member.sum += cp.points member.route.append(cp) if len(member.route) < 1: return start = Startpoint() member.route.insert(0, start) finish = Finishpoint() finish.time = member.time nCps = len(member.route) for i in range(nCps): finish.split = member.time - member.route[nCps - 1 - i].time if finish.split > timedelta(): break member.route.append(finish) bib = member.team_bib if bib not in teams: teams[bib] = Team() teams[bib].members.append(member) return teams, event_title
def processYear(year, all_teams): matches = utils.loadMatches(year) teams = {} try: teams_1yr = utils.loadTeams(year-1) except Exception: teams_1yr = None try: teams_2yr = utils.loadTeams(year-2) except Exception: teams_2yr = None for match in matches: for alliance in [match.red, match.blue]: for team in alliance: if team not in teams: if year == 2002: teams[team] = Team(team, 1500) else: if teams_1yr is not None and team in teams_1yr: team_1yr = teams_1yr[team].get_rating_max() else: team_1yr = elo.new_rating() if teams_2yr is not None and team in teams_2yr: team_2yr = teams_2yr[team].get_rating_max() else: team_2yr = elo.new_rating() teams[team] = Team(team, elo.existing_rating(team_1yr, team_2yr)) for match in matches: elo.update_rating(year, teams, match) utils.saveProcessedMatches(year, matches) utils.saveTeams(year, teams) for team in teams: all_teams.add(team)
def prob_predictions(lid, tid, tid_venue, oid, oid_venue): if tid_venue == oid_venue: raise ValueError("Team venue and opponent venue cannot be the same!") engine = connect_to_db(lid) if engine: league = League(lid, engine) team = Team(tid, engine, league, tid_venue) opponent = Team(oid, engine, league, oid_venue) team.set_opposition(opponent) opponent.set_opposition(team) # team.plot_xgf() # opponent.plot_xgf() results_dict = get_result_prob(team, opponent) return results_dict
def main(league): """ Populates home and away league tables. Uses classes League() and Team(). :param league: league with home and away tables to be populated """ engine = connect_to_db(league) if engine: league = League(league, engine) for team in league.teams: print() for venue in ['HOME', 'AWAY']: print(team, venue) team_instance = Team(team, engine, league, venue) stats = team_instance.get_stats() cols = [ 'team', 'mp', 'w', 'd', 'l', 'gf', 'ga', 'gd', 'points' ] df = pd.DataFrame([[ team, stats.Games.values.sum(), stats.W.values.sum(), stats.D.values.sum(), stats.L.values.sum(), stats.GF.values.sum(), stats.GA.values.sum(), (stats.GF.values.sum() - stats.GA.values.sum()), (3 * stats.W.values.sum() + stats.D.values.sum()) ]], columns=cols) print(df) table_name = venue.lower() + "_league_table" connection = engine.connect() df.to_sql(con=connection, name=table_name, if_exists='append', index=False) connection.close()
def loadTeams(): global teams teams = [] teamLines = teamString.splitlines() for x in range(teamLines.__len__()): items = teamLines[x].split('|') style = parseStyle(items[2]) name = items[0] coach = items[1] emoji = items[3] teams.append(Team()) teams[-1].name = name teams[-1].coach = coach teams[-1].playStyle = style teams[-1].emoji = emoji
async def veto(self, ctx: cmds.Context, team1: Union[Role, Member, Team], team2: Union[Role, Member, Team], gametype='2v2', bestof=3): """Start a veto between two teams.""" teams = [] for i, team in enumerate([team1, team2]): if not isinstance(team, Team): teams.append(Team(team)) else: teams.append(team) veto_menu = menus.VetoMenu(self.bot, Match(teams[0], teams[1], gametype, bestof)) await veto_menu.run(ctx) await get5.commands.generate_config(veto_menu.match) await self.startmatch(ctx)
def parse_sportorg_group(race_obj, group): print('Parse splits for:', group['name']) teams = {} print('Parse splits for members: ', end='') for person in race_obj['persons']: if person['group_id'] == group['id']: member = parse_member_splits(race_obj, person) if member: bib = member.team_bib if bib not in teams: teams[bib] = Team() teams[bib].members.append(member) print('') teams_list = [] for bib in teams: team = teams[bib] nMembers = len(team.members) member = team.members[nMembers - 1] team.bib = bib team.points = int(member.points) team.time = member.time team.route = member.route team.sum = member.sum team.group = group['name'] team_name = team.members[0].team_name team.team_name = team_name for m in team.members: if m.team_name != team_name: team.team_name += ' - ' + m.team_name teams_list.append(team) teams_list.sort(reverse=False, key=operator.attrgetter('time')) teams_list.sort(reverse=True, key=operator.attrgetter('points')) for i in range(len(teams_list)): teams_list[i].place = i + 1 return teams_list
def parse_SFR_splits_table(table_element, group): print('Parse splits for:', group) teams = dict() print('Parse splits for members: ', end='') for e in list(table_element): if e.tag == 'tr': member = parse_member_splits(e) if member: bib = member.team_bib if teams.get(bib) is None: teams[bib] = Team() teams[bib].members.append(member) print('') teams_list = list() for bib in teams: team = teams[bib] nMembers = len(team.members) member = team.members[nMembers - 1] team.bib = bib team.points = int(member.points) team.time = member.time team.route = member.route team.sum = member.sum team.group = group team_name = team.members[0].team_name team.team_name = team_name for m in team.members: if m.team_name != team_name: team.team_name += ' - ' + m.team_name teams_list.append(team) teams_list.sort(reverse=False, key=operator.attrgetter('time')) teams_list.sort(reverse=True, key=operator.attrgetter('points')) for i in range(len(teams_list)): teams_list[i].place = i + 1 return teams_list
def match_predict(home_identifier, away_identifier, league_name): """ Predict goals scored in match using Poisson distribution based on historical data for current season :param home_identifier: home team :param away_identifier: away team :param league_name: league containing home and away team :return: predicted goals in match """ print() engine = connect_to_db(str(league_name)) league = League(league_name, engine) home_team = " ".join(home_identifier.split(" ")[:-1]) away_team = " ".join(away_identifier.split(" ")[:-1]) home = Team(home_team, engine, league, 'HOME') away = Team(away_team, engine, league, 'AWAY') home.plot_gf() home.plot_ga() print(home.get_stats()) away.plot_gf() away.plot_ga() print(away.get_stats())
from game import * from classes import Team, Game try: x = int(input("How many games do you want to simulate?\n(Enter a positive integer)\n\n")) except: print("Incorrect input. Simulating for 10 games instead:") x = 10 teamAwins = 0 teamBwins = 0 for i in range(x): TeamA = Team(100.6, 3655, 1657, 1238, 466, 418, 1338, 43, 0) TeamB = Team(97.3, 3760, 1724, 1097, 405, 445, 1542, 45, 1) game_pos = int(TeamA.pos+TeamB.pos) the_Game = Game(0, 0, game_pos, 0, 0) game = play(i+1, the_Game, TeamA, TeamB) print(game) if the_Game.scoreA > the_Game.scoreB: teamAwins += 1 elif the_Game.scoreB > the_Game.scoreA: teamBwins += 1 print("Total result in wins (" + str(x) + " games played): Team A " + str(teamAwins) + ":" + str(teamBwins) + " Team B")
def main(): print_in_frame = printing(print) clear() # parameters affecting the difficulty start_money = 7 number_of_islands = 10 # initialization of a player and team player = Player(money=start_money) team = Team() game = Game(player, team) game.greet_player() transition() game.ask_name() clear() game.choose_difficulty_level() clear() game.print_introduction() transition() win, lose, ext = False, False, False n_current_island = 1 while not (win or lose or ext): game.initialize_islands() print_in_frame(player.inform, 'На очереди остров ' + str(n_current_island) + '.', sep='\n') transition() # oracle go_oracle = game.ask_about_oracle() clear() if go_oracle == '1': game.talk_with_oracle() if player.money < 1: lose = True break transition() # tavern game.action_in_tavern() transition() # strike print_in_frame(team.inform, 'Вперед, на остров!', sep='\n') transition() game.try_get_chest() # check if the game should be continued print_in_frame(EXIT_QUESTION) ext_ans = get_correct_answer('1', '2') clear() if ext_ans == '2': ext = True # check win or lose team.reset_command() if player.money < 1: lose = True elif game.n_current_island == number_of_islands + 1: win = True # game over with open('records.txt', 'a') as f_out: today = datetime.datetime.today() f_out.write( today.strftime("%d-%m-%Y %H:%M") + ' | ' + 'Player: ' + game.player_name + ', ' + 'coins: ' + str(player.money) + ', islands passed: ' + str(n_current_island - 1) + '\n') print(player.inform) if win: print_in_frame(WINNING) elif lose: print_in_frame(LOSING) else: print('Конец игры.')
from sqlalchemy.orm import sessionmaker all_games = requests.get('http://worldcup.sfg.io/matches').json() engine = create_engine('sqlite:///games.db') Session = sessionmaker(bind=engine) session = Session() all_games_tuples = [(game['venue'], game['home_team_country'], game['away_team_country'], game['winner']) for game in all_games] h_teams = set([t[1] for t in all_games_tuples]) a_teams = set([t[2] for t in all_games_tuples]) teams = h_teams.union(a_teams) team_objects = [Team(country=t) for t in teams] session.add_all(team_objects) session.commit() all_game_objects = [] all_stats = [] for game in all_games: h_team = session.query(Team).filter( Team.country == game['home_team_statistics']['country']).one() a_team = session.query(Team).filter( Team.country == game['away_team_statistics']['country']).one() game_object = Game(venue=game['venue'], winner=game['winner']) all_game_objects.append(game_object) h_name = game['home_team']['country']
players = get_all_used_players( FantasyPremierLeagueManager(config['managers'][manager]), 1, 38) for player in players: player_list.append(PremierLeaguePlayer(player).web_name) result[manager] = {'players': player_list, 'total': len(player_list)} return result def update_all_files(): data.fetch_all_latest_info() if __name__ == '__main__': # update_all_files() erwin = FantasyPremierLeagueManager(config["managers"]["erwin"]) niels = FantasyPremierLeagueManager(config['managers']['niels']) bale = PremierLeaguePlayer(543) team1 = Team(14) team2 = Team(20) schuppebekske = League(435851) een_fixture = Fixture(200) manchester_united = Team(team_short_name="MUN") mun_mci = get_fixture(manchester_united, Team(team_short_name="MCI")) # print(mun_mci.away_team) # print(een_fixture.yellow_cards) # print(get_captaincy_points_per_manager(36, 36)) # print(get_extra_captaincy_points_between_gws(niels, 1, 36)) print(get_all_used_players_per_manager())
def team_creator(directory, csvs, teams): for csv in csvs: with open(directory + csv, 'r') as table: numberOfRows = int(table.readline()) for _ in range(numberOfRows): teams.append(Team(table.readline()))
def team_generator(name_list, team_name): player_list = player_converter(name_list) team = Team(player_list, team_name) return team