Пример #1
0
    def get_scores(self):
        teams = []

        # ensure we're using the right database
        self.cursor.execute("USE " + self.config.DATABASE_NAME + ";")

        # Execute query
        query = """SELECT services.teamId, checks.serviceId, COUNT(checks.id)
                   FROM checks INNER JOIN services ON checks.serviceId = services.id
                   WHERE result = 1 GROUP BY serviceId;"""
        self.cursor.execute(query)

        for (team_id, service_id, count) in self.cursor:
            team_exists = False
            for team in teams:
                if team.id == team_id:
                    team.add_to_score(count)
                    team_exists = True

            if not team_exists:
                new_team = Team(team_id)
                new_team.add_to_score(count)
                teams.append(new_team)

        self.cursor.close()
        self.connection.close()

        return teams
Пример #2
0
def main():
    teamId = 0
    for team in NBA:
        response = urllib2.urlopen(
            'http://www.espn.com/nba/team/stats/_/name/' + team)
        html = response.read()

        # initialize BeautifulSoup
        soup = BeautifulSoup(html, 'html.parser')
        team = Team()

        # set unique Id then increment for the following team's Id
        scrapeID(team, teamId)
        teamId += 1

        # scrape all data from espn and place into team object
        scrapeName(team, soup)
        scrapeStats(team, soup)

        team.setFGP(scrapeFGP(team, soup))

        # write to a database
        conn = sqlite3.connect('../Database/databaseofTeams.db')
        c = conn.cursor()

        writeTeam(team, c)

        conn.commit()
        conn.close()
Пример #3
0
    def scrapeMatchFromRow(self, row):
        data = row.findAll('td')

        homeClub, homeLevel = getClubAndLevelFromTeamName(data[1].text)
        awayClub, awayLevel = getClubAndLevelFromTeamName(data[2].text)
        homeTeam = Team(homeClub, homeLevel)
        awayTeam = Team(awayClub, awayLevel)

        startDate = data[0].text
        startDate = datetime.strptime(startDate, '%d-%m-%Y').date()
        startTime = data[4].text
        startTime = datetime.strptime(startTime, '%H:%M').time()

        try:
            meetingTime = data[3].text
            meetingTime = datetime.strptime(meetingTime, '%H:%M').time()
        except:
            meetingTime = startTime

        meetingDateTime = datetime.combine(startDate, meetingTime)
        startDateTime = datetime.combine(startDate, startTime)
        endDateTime = startDateTime + MATCH_DURATION
        # Assume that returning takes the same amount of time as the time between meeting and start of the match.
        returnedDateTime = endDateTime + (startDateTime - meetingDateTime)

        referee = Referee("Not Scheduled", "", "", "", "", "", [])
        match = Match(homeTeam, awayTeam, meetingDateTime, startDateTime,
                      endDateTime, returnedDateTime, referee)
        return match
Пример #4
0
def GetAllGames(all_game_lists, all_games_finished):
    index = 'A'
    games_list = []
    for item in all_game_lists:
        team_vs = GetOneElementByClass(item, 'div', 'team_vs')
        team_details_div = GetElementsByClass(team_vs, 'div', 'txt')

        team_score_a = GetOneElementByClass(team_details_div[0], 'span', 'num')
        team_score_b = GetOneElementByClass(team_details_div[1], 'span', 'num')

        team_score_a = GetTextOfItem(team_score_a, '0')
        team_score_b = GetTextOfItem(team_score_b, '0')

        team_name_a = GetTextOfItem(team_details_div[0].find('a'))
        team_name_b = GetTextOfItem(team_details_div[1].find('a'))

        team_a = Team(name=team_name_a, score=team_score_a)
        team_b = Team(name=team_name_b, score=team_score_b)

        team_vs_time = GetOneElementByClass(team_vs, 'span', 'b')
        team_vs_time = GetTextOfItem(team_vs_time, '      未开始')

        games_list.append(Game(index, team_a, team_b, team_vs_time))

        index = chr(ord(index) + 1)
    return games_list
Пример #5
0
    def __init__(self, filename):
        team1, team2, ball = [], [], []
        checkIndex = -1

        with open(filename, 'r') as file:  # Copy the data from the file to temporary list
            for line in file:
                if checkIndex >= 0:
                    if checkIndex % self._numOfPlayers < teamSize:
                        team1.append(line[:-1])
                    elif (self._numOfPlayers - 1) > (checkIndex % self._numOfPlayers) >= teamSize:
                        team2.append(line[:-1])
                    else:
                        ball.append(line[:-1])
                else:
                    self._numOfPlayers = int(line[:-1])
                    teamSize = (self._numOfPlayers - 1) / 2
                    teamSize = int(teamSize)

                checkIndex += 1

        if team1.__len__() == 0 or team2.__len__() == 0 or ball.__len__() == 0:
            print("failed open file")
            return None

        self._objects = []
        self._objects.append(Team(Color.FIRST_TEAM, teamSize, team1))
        self._objects.append(Team(Color.SEC_TEAM, teamSize, team2))
        self._objects.append(Ball(Color.BALL, ball))
Пример #6
0
    def __init__(self, date, day, home_team_id, vis_team_id, time, league, db):
        self.date = date
        self.day = day
        self.vis_team_id = vis_team_id
        self.home_team_id = home_team_id
        self.time = time
        self.league = league

        self.vis_bat = Bat(vis_team_id, db)
        self.vis_pitch = Pitch(vis_team_id, db)
        self.vis_team = Team(vis_team_id, db, self.vis_bat, self.vis_pitch,
                             league)

        self.home_bat = Bat(home_team_id, db)
        self.home_pitch = Pitch(home_team_id, db)
        self.home_team = Team(home_team_id, db, self.home_bat, self.home_pitch,
                              league)

        self.h_pow_v_vs_pow, self.h_cont_v_vs_cont, \
        self.h_scor_v_vs_scor, self.h_b_over_b_p_over, \
        self.h_vs_pow_v_pow, self.h_vs_cont_v_cont, \
        self.h_vs_scor_v_scor, self.h_p_over_v_b_over = Utils.compare_teams(self.home_team, self.vis_team)
        self.total = Utils.compare_teams(self.home_team, self.vis_team)
        self.favorite, self.moneyline = Utils.get_moneyline(
            self.home_team, self.vis_team)
Пример #7
0
    def __init__(self, awayTeam, homeTeam, awayBatters, homeBatters, awayPitcher, homePitcher, date):
        con = MemoryDB.get_con()
        cur = con.cursor()

        cur.execute("select distinct(game) from batter where team=? and season=? and date=?",
                    (awayTeam, ENV.YEAR, date))
        row = cur.fetchone()
        if row is not None:
            awayGameNum = row[0]
        else:
            raise LookupError("Game num not found for away team {}".format(awayTeam))
        cur.execute("select distinct(game) from batter where team=? and season=? and date=?",
                    (homeTeam, ENV.YEAR, date))
        row = cur.fetchone()
        if row is not None:
            homeGameNum = row[0]
        else:
            raise LookupError("Game num not found for home team {}".format(homeTeam))
        print("game nums: {}|{}".format(awayGameNum, homeGameNum))

        cur.execute("select pf from parkfactor where team='" + awayTeam + "' and year=2012")
        awayPF = cur.fetchone()[0]
        cur.execute("select pf from parkfactor where team='" + homeTeam + "' and year=2012")
        homePF = cur.fetchone()[0]

        self.away = Team(awayTeam, awayGameNum, awayPF, awayBatters, awayPitcher)
        self.home = Team(homeTeam, homeGameNum, homePF, homeBatters, homePitcher)

        self.inning = Inning()
        self.bases = Bases()

        self.leagueAvg = self.get_league_avg(homeGameNum)
Пример #8
0
    def __init__(self):
        pygame.init()

        self.screen = pygame.display.set_mode((self.screen_w, self.screen_h))
        self.fps_clock = pygame.time.Clock()

        # 2D array containing arrays, to store object in the secotrs and optimise collisions
        self.sectors = [[[]
                         for j in range(ceil(self.screen_h / self.sector_size))
                         ]
                        for i in range(ceil(self.screen_w / self.sector_size))]

        # create goals
        screen_margin = (self.screen_h - self.pitch_h) / 2
        self.goal_left = Goal(self, self.pitch_color_1,
                              (self.screen_w - self.pitch_w) / 2,
                              screen_margin + self.pitch_h * 6 / 16,
                              screen_margin + self.pitch_h * 10 / 16, 50, -1)
        self.goal_right = Goal(
            self, self.pitch_color_2,
            self.pitch_w + (self.screen_w - self.pitch_w) / 2,
            screen_margin + self.pitch_h * 6 / 16,
            screen_margin + self.pitch_h * 10 / 16, 50, 0)

        self.team_right = Team(self, self.team1_color, self.goal_right, 1)
        self.team_left = Team(self, self.team2_color, self.goal_left, -1)

        self.start_time = pygame.time.get_ticks()
Пример #9
0
    def generate_n_teams(self, n):
        oprs = []

        for i in range(1, n + 1):
            t = Team(i, -1)
            self.teams.append(t)

        # if more than 32 teams, use worlds-like distribution
        if (n > 32):
            oprs = np.random.normal(150, 55, n)
        # if 32 > n > 24, use state-like distribution
        elif (n > 24):
            oprs = np.random.normal(125, 55, n)
        # else for smaller tournaments, use qual-like distribution
        else:
            oprs = np.random.normal(100, 55, n)

        oprs.sort()
        o = 0
        for t in reversed(self.teams):
            temp = int(oprs[o])

            # min opr is 10, max is 450
            if temp < 10: temp = 10
            if temp > 450: temp = 450

            t.opr = temp
            o += 1
Пример #10
0
    def player_team(self, player):

        home = [
            self.home_boxscore['teamId']
            for stat in self.home_boxscore['playerstats']
            if stat['player']['playerId'] == player.id
        ]

        away = [
            self.away_boxscore['teamId']
            for stat in self.away_boxscore['playerstats']
            if stat['player']['playerId'] == player.id
        ]

        if home != [] and away == []:
            return Team(home[0])
        elif home == [] and away != []:
            return Team(away[0])
        elif home == [] and away == []:
            raise GameDataError(
                'No such player in this game: {}'.format(player))
        elif home != [] and away != []:
            raise GameDataError(
                'Same player {} on two different teams! Something is terribly wrong!'
                .format(player))
Пример #11
0
def test_team_remove_unlisted():
    # Test that if no results found return 0
    team = Team("One")
    jodie = Hero("Jodie Foster")
    team.add_hero(jodie)
    code = team.remove_hero("Athena")
    assert code == 0
Пример #12
0
    def load_game(self, file_name):
        self.players = []
        current_team_name = None
        current_team_obj = None
        with open(file_name, "r") as f:
            first_line = f.readline()
            if first_line[0] == "M":
                self.map_name = first_line.split(":")[1].rstrip()

                self.world = World(self.map_name)
                print("creating map from " + self.map_name)
                self.set_color_prefs(Game.default_prefs)
            for line in f:
                # print(line[0])
                if line[0] == "t":
                    current_team_name = line.split("-")[1].split("@")[0]
                    host, port = line.split("-")[1].split("@")[1].split(":")
                    port = int(port)
                    print("creating new team: " + current_team_name)
                    current_team_obj = Team(self.world, current_team_name)
                    self.add_player(Server_Facing_Networked_Player(self, current_team_obj, host, port))
                elif line[0] == "m":
                    loc = location(line.split("@")[1][:-1])
                    current_team_obj.create_mech(line[2:6], loc)
                elif line[0] == "s":
                    loc = location(line.split("@")[1][:-1])
                    self.world.create_station_at(loc, current_team_obj)
Пример #13
0
def pruning_test():
    # Setup Team Object
    team_edm = Team()
    lines = list()
    lines.append(Line(0, 1.701))
    lines.append(Line(1, 0.658))
    lines.append(Line(2, 0.299))
    lines.append(Line(3, 0.433))
    team_edm.set_team("EDM", lines=lines,
                      start_line_index=0)  # Edmonton Oilers

    path = Path()
    path.team = team_edm

    values_best = []
    for i in range(30):
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, i)
        values_best.append(num_visited)

    path.team[path.team.curr_line_index].toi = 0
    values_worst = []
    for i in range(30):
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, i)
        values_worst.append(num_visited)

    theoretical_values = [theoretical_nodes(i) for i in range(30)]
    print(theoretical_values)
    print(values_best)
    print(values_worst)
Пример #14
0
def rows_to_team(team_rows):
    team = Team()
    for i in range(1, len(team_rows)):
        columns = team_rows[i].findAll("td")
        popflash_id = get_popflash_id(columns)

        player = Player(popflash_id)
        try:
            s = str(columns[0].text.strip()[0])
            player.set_nick(columns[0].text.strip())
        # Captain gets cactus symbol in front of name. Remove this
        except UnicodeEncodeError:
            player.set_nick(columns[0].text.strip()[1:])

        player.set_kills(columns[1].text.strip())
        player.set_assists(columns[2].text.strip())
        player.set_deaths(columns[3].text.strip())
        player.set_flash_assists(columns[4].text.strip())
        player.set_adr(columns[5].text.strip())
        player.set_hltv_rating(columns[6].text.strip())
        player.set_hs_percentage(columns[7].text.strip())
        player.set_clutch_kills(columns[8].text.strip())
        player.set_bombs_planted(columns[9].text.strip())
        player.set_bombs_defused(columns[10].text.strip())

        img_url = get_user_image(popflash_id)
        player.set_img_url(img_url)

        team.add_player(player)

    return team
Пример #15
0
    def initializeTeam(self):
        """Create a new Team and add two new Learners with different atomic
        actions. These Learners are added to the Learner population, and the
        Team is added to both the Team and root Team populations.
        """

        # Create two new Learners with different atomic actions
        a1 = randint(0, Trainer.ATOMIC_ACTION_RANGE)
        a2 = randint(0, Trainer.ATOMIC_ACTION_RANGE)
        while a1 == a2:
            a2 = randint(0, Trainer.ATOMIC_ACTION_RANGE)

        l1 = Learner(action = a1)
        l2 = Learner(action = a2)

        # Create new Team
        team = Team()

        # Add Learners to Team
        team.addLearner(l1)
        team.addLearner(l2)

        # Add Learners to Learner population
        self.learner_pop.append(l1)
        self.learner_pop.append(l2)

        # Add Team to Team populations. Note that all new Teams are, by
        # definition, root teams
        self.team_pop.append(team)
Пример #16
0
class GameEngine:
	"""GameEngine class for demonstration"""

	"""Let us create a team and set its strategy,
	and make the teams play the game"""
	"""Create few strategies"""
	attack = AttackStrategy()
	defend = DefendStrategy()

	"""Create our teams"""
	france = Team("France")
	italy = Team("Italy")

	print "Setting the strategies.."
	"""Now let us set the strategies"""
	france.SetStrategy(attack)
	italy.SetStrategy(defend)

	"""Make the teams start the play"""
	france.PlayGame()
	italy.PlayGame()

	print "Changing the strategies.."
	"""Let us change the strategies"""
	france.SetStrategy(defend)
	italy.SetStrategy(attack)
	
	"""Make them play again"""
	france.PlayGame()
	italy.PlayGame()

	"""Wait for a key press"""
	print "Press any key to continue..."
	raw_input()
Пример #17
0
class Euchre():
    """Top-level view of the entire game"""
    def __init__(self):
        self.deck = Deck()
        self.players = []
        self.team1 = Team()
        self.team2 = Team()

    def add_players(self):
        """ Add the 4 players to the game and create teams """
        team1 = True
        names = ["T", "B", "M", "G"]
        for i in range(4):
            #name = input("Player {0}'s name?: ".format(i+1))
            newPlayer = Player(names[i])
            self.players.append(newPlayer)
            if team1:
                self.team1.add_player(newPlayer)
                newPlayer.set_team(1)
                team1 = False
            else:
                self.team2.add_player(newPlayer)
                newPlayer.set_team(2)
                team1 = True

    def start_game(self):
        """ Start the game """
        Game(self.players, self.deck).start()
Пример #18
0
    def read_json(self):
        game_df = pd.read_json(self.path_to_json)

        event = Game.load_event_by_num(game_df, self.event_num)
        self.event = Event(event)
        self.home_team = Team(event['home']['teamid'])
        self.guest_team = Team(event['visitor']['teamid'])
Пример #19
0
async def new_team(context):
    server = get_server(context)
    array = message_to_array(context.message.content)
    team_name = array[0]

    if get_team(team_name) is not None:
        await bot.say("This team name is already taken.")
        return

    role = await bot.create_role(server=server,
                                 name=team_name,
                                 hoist=True,
                                 mentionable=True)  # permissions, color
    valid_members, invalid_members = validate_members(server, array[1:])

    for member in valid_members:
        await bot.add_roles(server.get_member_named(member),
                            role)  # add each valid member to team

    if len(invalid_members) != 0:
        invalid_response = get_invalid_members_response(invalid_members)
        await bot.say(invalid_response)

    team = Team(name=team_name, role=role,
                members=valid_members)  # members=members)
    msg = ('New Team Created!\n' + team.to_s())

    global teams
    teams = teams + [team]

    await bot.say(msg)
Пример #20
0
def query_game_details(game_id):
    ou_site = "http://site.api.espn.com/apis/site/v2/sports/football/college-football/summary?event=" + game_id
    response = requests.get(ou_site, timeout=5)
    game_data = response.json()
    teams = game_data['header']['competitions'][0]['competitors']
    team1 = Team(teams[0])
    team2 = Team(teams[1])
    return team1, team2
Пример #21
0
 def __init__(self):
     self.pitch = Pitch()
     self.home_team = Team(True, pitch=self.pitch)
     self.away_team = Team(False, pitch=self.pitch)
     self.current_frame_number = 0
     self.flip5050()
     self.store_frame()
     self.current_frame.print_frame()
 def setUp(self) -> None:
     print("Entering team setup")
     self.brandon = Player("Brandon", "Ravens", 8)
     self.nick = Player("Nick", "Ravens", 9)
     self.hunter = Player("Hunter", "Ravens", 10)
     self.teamMates = [self.brandon, self.nick, self.hunter]
     self.owner = Owner("Jason hibbeler", "Ravens")
     self.newTeam = Team(self.teamMates, "Ravens", self.owner)
     self.newTeam.printTeam()
Пример #23
0
 def is_ahead_of(self, player2):
     if self.team.side == Protocol.SIDE_TOP:
         return self.get_front_location(Team.get_opponent(
             self.team.side)).y < player2.get_front_location(
                 Team.get_opponent(self.team.side)).y
     else:
         return self.get_front_location(Team.get_opponent(
             self.team.side)).y > player2.get_front_location(
                 Team.get_opponent(self.team.side)).y
Пример #24
0
 def __RandomizeTeams(self, numberOfTeams, teamSize):
     self.teams = []
     for teamNumber in range(numberOfTeams):
         team = Team(teamNumber + 1)
         while (team.GetCurrentTeamSize() != teamSize):
             x = random.randint(1,numberOfTeams * teamSize) - 1
             team.TryToAddTeamMember(self.allTeamMembersList[x])
         team.FinalizeTeam()
         self.teams.append(team)
Пример #25
0
def stats_mod(home_players, away_players):
    game_data_array = []
    calc_stats(home_players, 240)
    calc_stats(away_players, 240)

    game_data_array.extend(Team(home_players).export())
    game_data_array.extend(Team(away_players).export())

    return game_data_array
Пример #26
0
def main():
    """
    Sets up and processes team, EXAMPLE;
    :return: NONE
    """
    # Setup Team Object
    team_edm = Team()
    lines = list()
    lines.append(Line(0, 1.701))
    lines.append(Line(1, 0.658))
    lines.append(Line(2, 0.299))
    lines.append(Line(3, 0.433))
    team_edm.set_team("EDM", lines=lines,
                      start_line_index=0)  # Edmonton Oilers

    print(team_edm)

    # Setup Path Object
    path = Path()
    path.team = team_edm

    schedule = []
    num_intervals = PERIOD_LENGTH // INTERVAL
    start = time.time()
    for i in range(num_intervals - 1):

        max_depth = MAX_DEPTH
        if num_intervals - i < MAX_DEPTH:
            max_depth = num_intervals - i

        # start = time.time()
        # find optimal path from curr_line for the next (MAX_DEPTH * INTERVAL) seconds
        temp_path = path.copy()
        optimal_path, num_visited = process(team_edm[team_edm.curr_line_index],
                                            temp_path, 1, max_depth)

        # print("\n\n", path.team, "\n\n")
        path.team.update(optimal_path[1], INTERVAL)
        schedule.append(optimal_path[1].line_num)
        elapsed_time = time.time() - start

        t_nodes = theoretical_nodes(max_depth)

        # print("Optimal       ", optimal_path)
        #
        print("Progress:     {p:3.0f}% @ t: {e:5.2f}".format(
            p=i / (num_intervals - 1) * 100, e=elapsed_time))
        # print("Look Ahead:   ", LOOK_AHEAD)
        # print("Depth:        ", max_depth)
        # print("Visited:      ", num_visited)
        # print("Theoretical:  ", t_nodes)
        # print("Removal Rate: ", "{0:0.5f}".format((t_nodes - num_visited)/t_nodes))
        # print("Speed Up:     ", "{0:4.2f}".format(t_nodes/num_visited))
        #
        # print("\nTime:       ", elapsed_time)

    print(schedule)
 def __init__(self, team1_name, team2_name):
     self.team1_name = team1_name
     self.team2_name = team2_name
     self.team1 = Team(self.team1_name, random.choice(self.location))
     self.team2 = Team(self.team2_name, random.choice(self.location))
     self.team1_pass = Pass(self.team1_name, self.team2_name)
     self.team2_pass = Pass(self.team2_name, self.team1_name)
     self.team1_shot = Shoot(self.team1_name, self.team2_name)
     self.team2_shot = Shoot(self.team2_name, self.team1_name)
Пример #28
0
    def setup(self):
        #setup directory to save the images
        try:
            os.mkdir(self.imageDirName)
        except:
            print self.imageDirName + " subdirectory already exists. OK."

        #define teams which the agents can be a part of
        predator = Team("Predator", '#ff99ff')
        prey = Team("Prey", '#ffcc99')
        #Defining a couple of agents

        #predator and prey counts
        predatorCount = 5
        preyCount = 10
        displacement = array([0, 20, 0])

        #initial seed positions
        predatorPos = array([20, 0, 0])
        preyPos = array([0, 0, 0])

        #set seed for randomly placing predators
        random.seed(20)

        #initialize predators
        for i in range(0, predatorCount):
            brain = PredatorBrain()
            x = random.random() * 30
            y = random.random() * 30
            z = random.random() * 30
            newDisplacement = array([x, y, z])
            agent = Agent(predator, predatorPos, array([0, 0, 0]), brain, 5, 5,
                          5)
            self.world.addAgent(agent)
            predatorPos += newDisplacement

        #initialize prey
        for i in range(0, preyCount):
            brain = PreyBrain()
            agent = RestrictedAgent(prey, preyPos, array([0, 0, 0]), brain, 2,
                                    200, 2, 2)
            self.world.addAgent(agent)
            preyPos += displacement

#
#define a bunch of obstacles
        ob1Pos = array([-50, -50, -50])
        ob1 = Obstacle(ob1Pos, 30)

        ob2Pos = array([80, -50, -50])
        ob2 = Obstacle(ob2Pos, 20)

        originRef = Obstacle(array([0.1, 0.1, 0.1]), 10)

        #add obstacles to the world
        self.world.addObstacle(ob1)
        self.world.addObstacle(originRef)
Пример #29
0
class Match:

    home_team: Team = None
    away_team: Team = None

    pitch: Pitch = None

    current_frame: Frame = None
    stored_frames: FrameArray = []

    current_possession: bool = True

    current_frame_number: int = 0
    total_number_of_frames: int = 50

    def __init__(self):
        self.pitch = Pitch()
        self.home_team = Team(True, pitch=self.pitch)
        self.away_team = Team(False, pitch=self.pitch)
        self.current_frame_number = 0
        self.flip5050()
        self.store_frame()
        self.current_frame.print_frame()

    def flip5050(self):
        random_draw = np.random.rand()
        if random_draw <= 1.0 / 2.0:
            # toggle possession
            self.current_possession = not self.current_possession

    def random_flip(self):
        random_draw = np.random.rand()
        if random_draw < 1.0 / 50.0:
            # toggle possession
            self.current_possession = not self.current_possession

    def store_frame(self):
        frame = Frame(self.current_frame_number, pitch=self.pitch)
        frame.store_data(self.home_team, self.away_team,
                         self.current_possession)
        self.stored_frames.append(frame)
        self.current_frame = frame

    def update_team(self, frame: Frame):
        self.home_team.updateTeam(frame)
        self.away_team.updateTeam(frame)

    def tick(self):
        self.random_flip()
        self.update_team(self.current_frame)
        self.current_frame_number += 1
        self.store_frame()
        self.current_frame.print_frame()

    def start_sim(self):
        while (self.current_frame_number < self.total_number_of_frames - 1):
            self.tick()
Пример #30
0
 def updateTeamWLT(self, winningTeam: Team.Team, losingTeam: Team.Team, tyingTeam1: Team.Team, tyingTeam2: Team.Team):
     if (winningTeam is not None):
         winningTeam.addSimulatedWin()
     if (losingTeam is not None):
         losingTeam.addSimulatedLoss()
     if (tyingTeam1 is not None):
         tyingTeam1.addSimulatedTie
     if (tyingTeam2 is not None):
         tyingTeam2.addSimulatedTie
Пример #31
0
 def calculateWLT(self,weekIndex, team1: Team.Team, team2: Team.Team):
     team1Points = team1.getPointsForWeek(weekIndex)
     team2Points = team2.getPointsForWeek(weekIndex)
     if (team1Points > team2Points):
         self.updateTeamWLT(team1,team2, None, None)
     elif (team1Points < team2Points):
         self.updateTeamWLT(team2, team1, None, None)
     else:
         self.updateTeamWLT(None,None,team1,team2)
 def read_json(self):
     data_frame = pd.read_json(self.path_to_json)
     last_default_index = len(data_frame) - 1
     self.event_index = min(self.event_index, last_default_index)
     index = self.event_index
     print(Constant.MESSAGE + str(last_default_index))
     event = data_frame['events'][index]
     self.event = Event(event, self.path_to_json, self.event_index)
     self.home_team = Team(event['home']['teamid'])
     self.guest_team = Team(event['visitor']['teamid'])
Пример #33
0
    def test_calc_progress(self):
        current_time = datetime.datetime(2014, 1, 1, 0, 0, 0)
        team = Team("test_team", 10)
        module = Module("test_module", 800)
        module.calc_deadline(current_time, 10, 0)
        team.module = module

        while team.module and not team.module.completed:
            current_time += datetime.timedelta(hours=1)
            team.calc_progress(current_time)

        self.assertTrue(team.completed_modules and team.completed_modules[0] == module)
Пример #34
0
class Game:
    def __init__(self, awayTeam, homeTeam, awayBatters, homeBatters, awayPitcher, homePitcher, date):
        con = MemoryDB.get_con()
        cur = con.cursor()

        cur.execute("select distinct(game) from batter where team=? and season=? and date=?",
                    (awayTeam, ENV.YEAR, date))
        row = cur.fetchone()
        if row is not None:
            awayGameNum = row[0]
        else:
            raise LookupError("Game num not found for away team {}".format(awayTeam))
        cur.execute("select distinct(game) from batter where team=? and season=? and date=?",
                    (homeTeam, ENV.YEAR, date))
        row = cur.fetchone()
        if row is not None:
            homeGameNum = row[0]
        else:
            raise LookupError("Game num not found for home team {}".format(homeTeam))
        print("game nums: {}|{}".format(awayGameNum, homeGameNum))

        cur.execute("select pf from parkfactor where team='" + awayTeam + "' and year=2012")
        awayPF = cur.fetchone()[0]
        cur.execute("select pf from parkfactor where team='" + homeTeam + "' and year=2012")
        homePF = cur.fetchone()[0]

        self.away = Team(awayTeam, awayGameNum, awayPF, awayBatters, awayPitcher)
        self.home = Team(homeTeam, homeGameNum, homePF, homeBatters, homePitcher)

        self.inning = Inning()
        self.bases = Bases()

        self.leagueAvg = self.get_league_avg(homeGameNum)

    @staticmethod
    def get_league_avg(game_num, use_memory=True):
        con = MemoryDB.get_con(use_memory)
        cur = con.cursor()
        cur.execute(
            """select sum(hits),sum(doubles),sum(triples),sum(homeruns),sum(walks),sum(hit_by_pitch),
            sum(batters_faced) from pitcher where game < """ + str(game_num) + ";")
        stat = cur.fetchone()

        league_avg = []

        league_avg.append(float(stat[4]) / (stat[0] + stat[4]))  # Walks
        if (float(league_avg[0]) == 0):
            print("Walks league zero")
            exit()
        league_avg.append(float(stat[5]) / (stat[0] + stat[4]))  # HBP
        if (float(league_avg[1]) == 0):
            print("HBP league zero")
            exit()
        league_avg.append(float(float(stat[0] - stat[1] - stat[2] - stat[3]) / (stat[0] + stat[4])))  # Singles
        if (float(league_avg[2]) == 0):
            print("Single league zero")
            exit()
        league_avg.append(float((stat[1])) / (stat[0] + stat[4]))  # Doubles
        if (float(league_avg[3]) == 0):
            print("Doubles league zero")
            exit()
        league_avg.append(float((stat[2])) / (stat[0] + stat[4]))  # Triples
        if (float(league_avg[4]) == 0):
            print("Triples league zero")
            exit()
        league_avg.append(float((stat[3])) / (stat[0] + stat[4]))  # Homerun
        if (float(league_avg[5]) == 0):
            print("Homerun league zero")
            exit()
        league_avg.append(float(stat[0] + stat[4] + stat[5]) / stat[6])
        if (float(league_avg[6]) <= 0):
            print("OBP league zero")
            exit()
        return league_avg

    def simulateInning(self):
        self.bases.clearbases()
        if (PRINT_PLAY):
            if (self.inning.getHalf()):
                print("Simulating bottom of the ", self.inning.getInning(), " inning")
            else:
                print("Simulating top of the ", self.inning.getInning(), " inning")
        if (self.inning.getHalf()):
            batting = self.home
            pitching = self.away
        else:
            batting = self.away
            pitching = self.home
        while (self.inning.getOuts() < 3):
            if ( stratPlay(self.inning, self.bases, batting.getCurrentBatter()) != 5):
                result = atBat(batting.getCurrentBatter(), pitching.getCurrentPitcher(), self.leagueAvg,
                               batting.getPF())
            else:
                result = 5
            batting.getCurrentBatter().gameAtBat()
            if (result == 0):
                self.inning.addOut()
                if (self.inning.getOuts() < 3):
                    if (doublePlay(self.bases)):
                        self.inning.addOut()
                        if (PRINT_PLAY):
                            print(batting.getCurrentBatter().getName(), " grounded into double play")
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " is out")
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " is out")
            elif (result == 1):
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " hit a single")
                batting.addScore(self.bases.basesSingle())
                batting.getCurrentBatter().gameSingle()
            elif (result == 2):
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " hit a double")
                batting.addScore(self.bases.basesDouble())
                batting.getCurrentBatter().gameDouble()
            elif (result == 3):
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " hit a triple")
                batting.addScore(self.bases.basesTriple())
                batting.getCurrentBatter().gameTriple()
            elif (result == 4):
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " hit a homerun")
                batting.addScore(self.bases.basesHR())
                batting.getCurrentBatter().gameHR()
            elif (result == 5):
                if (PRINT_PLAY):
                    print(batting.getCurrentBatter().getName(), " walked")
                batting.addScore(self.bases.basesSingle())
                batting.getCurrentBatter().gameWalk()
            batting.nextBatter()


    def simulateGame(self):
        while (self.inning.nextInning(self.away.getScore(), self.home.getScore())):
            self.simulateInning()


    def printStats(self, team):
        if (team):
            team = self.home
        else:
            team = self.away
        for player in team.getPlayers():
            stats = player.getGameStats()
            print("Player: ", player.getName())
            print("At Bats: ", stats[0])
            print("SO: ", stats[1])
            print("Walks: ", stats[2])
            print("Hits: ", stats[3])
            print("1B: ", stats[4])
            print("2B: ", stats[5])
            print("3B: ", stats[6])
            print("HR: ", stats[7])

    def printScore(self):
        print("Away Score:", self.away.getScore())
        print("Home Score:", self.home.getScore())


    def reset(self):
        self.inning.reset()
        self.bases.clearbases()
        self.home.reset()
        self.away.reset()
Пример #35
0
def main():
    with open('staticchampion') as data_file:
        JSONStaticChamps = json.load(data_file)

    print "\nWhat up homie. Enter your region to get started"
    print "Type in one of the following regions or else the program wont work correctly:\n"
    print "NA EUW EUNE LAN BR KR LAS OCE TR RU PBE\n"

    #I first ask the user for three things, their region, summoner name, and API Key.
    #These are the only three things I need from them in order to get create my URL and grab their ID.

    region = (str)(raw_input('Type in one of the regions above: '))
    summonerName = (str)(raw_input('Type your Summoner Name here and DO NOT INCLUDE ANY SPACES: ').lower())
    summonerName = summonerName.replace(" ", "")
    APIKey = (str)("0ba28f0f-9064-45cc-9c7e-96970ca42bbb")

    #I send these three pieces off to my requestData function which will create the URL and give me back a JSON that has the ID for that specific summoner.
    #Once again, what requestData returns is a JSON.
    JSONUser = requestSummonerData(region, summonerName, APIKey)

    ID = JSONUser[summonerName]['id']
    ID = str(ID)

    #responseJSON2 = requestRecentMatches(region, ID, APIKey)
    #print responseJSON2['games'][0]['fellowPlayers']


    JSONCurrentMatch = requestCurrentMatch(region, ID, APIKey)
    print JSONCurrentMatch['gameQueueConfigId']



    playercount = 0
    IDPlayers = ""

    blueteam = Team("blue")
    redteam = Team("red")

    for item in JSONCurrentMatch["participants"]:
        if playercount == 9:
            IDPlayers += str(item['summonerId'])
        else:
            IDPlayers += str(item['summonerId']) + "%20,%20"

        playercount = playercount + 1


    IDPlayers =  str(IDPlayers)

    JSONRankedData = requestRankedData(region, IDPlayers, APIKey)

    time1= time.time()

    for item in JSONCurrentMatch["participants"]:
        ID = item['summonerId']
        ID = str(ID)

        JSONCurrentMatch = JSONRankedData[ID]
        ChampID = item['championId']
        ChampID = str(ChampID)

        player = Player(ID, item['summonerName'], JSONCurrentMatch[0]['entries'][0]['leaguePoints'], JSONStaticChamps['keys'][ChampID], JSONCurrentMatch[0]['tier'], JSONCurrentMatch[0]['entries'][0]['division'])


        print ID

        if item['teamId'] == 100:
            blueteam.addplayer(player)
        if item['teamId'] == 200:
            redteam.addplayer(player)



        #"http://ddragon.leagueoflegends.com/cdn/5.22.3/img/champion/" + responseJSON2['key'] + ".png"
        #print item['summonerName'], item['teamId'], responseJSON3['name'], responseJSON2[0]['tier'], responseJSON2[0]['entries'][0]['division'], responseJSON2[0]['entries'][0]['leaguePoints']

    blueside = blueteam.getplayer()
    redside = redteam.getplayer()
    print "blue" + "--------------------------------------------" + "red"


    count = 0
    while (count < 5):
        blueplayer = blueside[count]
        redplayer = redside[count]

        print blueplayer.champ, blueplayer.summonername, blueplayer.tier, blueplayer.division, blueplayer.lp,  "    vs    ", redplayer.champ, redplayer.summonername, redplayer.tier, redplayer.division, redplayer.lp
        count = count + 1
    time2 = time.time()

    print((time2 - time1))



    champID = (str)(raw_input('gimme the ID : '))

    time3 = time.time()
    threadLock = threading.Lock()
    threads = []

    # Create new threads
    thread1 = Analyzing(region, champID, APIKey)

    # Start new Threads
    thread1.start()

    # Add threads to thread list
    threads.append(thread1)

    # Wait for all threads to complete
    for t in threads:
        t.join()

    time4 = time.time()

    print((time4 - time3))
Пример #36
0
    def createTeam(self, teamName):
        #batting_players.append(([row["Name"].replace(" ", ""), row["Position"], float(row["H"]), float(row["IPR"]), float(row["O-Swing%"]), float(row["Z-Swing%"]), float(row["O-Contact%"]), float(row["Z-Contact%"]), float(row["1B%"]), float(row["2B%"]), float(row["3B%"]), float(row["HR%"]), float(row["FP"])]))
        team = Team()
        team.set_Team_Name(teamName)
        temp2 = 0

        if teamName == "Yankees":
            self.teamBatting = "static/teams/Yankees_batting.txt"
            self.teamPitching = "static/teams/Yankees_pitchers.txt"
        elif teamName == "Phillies":
            self.teamBatting = "static/teams/Phillies_batting.txt"
            self.teamPitching = "static/teams/Phillies_pitchers.txt"
        elif teamName == "Red_Sox":
            self.teamBatting = "static/teams/Red_Sox_batting.txt"
            self.teamPitching = "static/teams/Red_Sox_pitchers.txt"
        elif teamName == "Angels":
            self.teamBatting = "static/teams/Angels_batting.txt"
            self.teamPitching = "static/teams/Angels_pitchers.txt"
        elif teamName == "White_Sox":
            self.teamBatting = "static/teams/White_Sox_batting.txt"
            self.teamPitching = "static/teams/White_Sox_pitchers.txt"
        elif teamName == "Cubs":
            self.teamBatting = "static/teams/Cubs_batting.txt"
            self.teamPitching = "static/teams/Cubs_pitchers.txt"
        elif teamName == "Mets":
            self.teamBatting = "static/teams/Mets_batting.txt"
            self.teamPitching = "static/teams/Mets_pitchers.txt"
        elif teamName == "Giants":
            self.teamBatting = "static/teams/Giants_batting.txt"
            self.teamPitching = "static/teams/Giants_pitchers.txt"
        elif teamName == "Twins":
            self.teamBatting = "static/teams/Twins_batting.txt"
            self.teamPitching = "static/teams/Twins_pitchers.txt"
        elif teamName == "Tigers":
            self.teamBatting = "static/teams/Tigers_batting.txt"
            self.teamPitching = "static/teams/Tigers_pitchers.txt"
        elif teamName == "Cardinals":
            self.teamBatting = "static/teams/Cardinals_batting.txt"
            self.teamPitching = "static/teams/Cardinals_pitchers.txt"
        elif teamName == "Dodgers":
            self.teamBatting = "static/teams/Dodgers_batting.txt"
            self.teamPitching = "static/teams/Dodgers_pitchers.txt"
        elif teamName == "Rangers":
            self.teamBatting = "static/teams/Rangers_batting.txt"
            self.teamPitching = "static/teams/Rangers_pitchers.txt"
        elif teamName == "Rockies":
            self.teamBatting = "static/teams/Rockies_batting.txt"
            self.teamPitching = "static/teams/Rockies_pitchers.txt"
        elif teamName == "Braves":
            self.teamBatting = "static/teams/Braves_batting.txt"
            self.teamPitching = "static/teams/Braves_pitchers.txt"
        elif teamName == "Mariners":
            self.teamBatting = "static/teams/Mariners_batting.txt"
            self.teamPitching = "static/teams/Mariners_pitchers.txt"
        elif teamName == "Brewers":
            self.teamBatting = "static/teams/Brewers_batting.txt"
            self.teamPitching = "static/teams/Brewers_pitchers.txt"
        elif teamName == "Orioles":
            self.teamBatting = "static/teams/Orioles_batting.txt"
            self.teamPitching = "static/teams/Orioles_pitchers.txt"
        elif teamName == "Reds":
            self.teamBatting = "static/teams/Reds_batting.txt"
            self.teamPitching = "static/teams/Reds_pitchers.txt"
        elif teamName == "Astros":
            self.teamBatting = "static/teams/Astros_batting.txt"
            self.teamPitching = "static/teams/Astros_pitchers.txt"
        elif teamName == "Athletics":
            self.teamBatting = "static/teams/Athletics_batting.txt"
            self.teamPitching = "static/teams/Athletics_pitchers.txt"
        elif teamName == "Nationals":
            self.teamBatting = "static/teams/Nationals_batting.txt"
            self.teamPitching = "static/teams/Nationals_pitchers.txt"
        elif teamName == "Blue_Jays":
            self.teamBatting = "static/teams/Blue_Jays_batting.txt"
            self.teamPitching = "static/teams/Blue_Jays_pitchers.txt"
        elif teamName == "Marlins":
            self.teamBatting = "static/teams/Marlins_batting.txt"
            self.teamPitching = "static/teams/Marlins_pitchers.txt"
        elif teamName == "Diamondbacks":
            self.teamBatting = "static/teams/Diamondbacks_batting.txt"
            self.teamPitching = "static/teams/Diamondbacks_pitchers.txt"
        elif teamName == "Indians":
            self.teamBatting = "static/teams/Indians_batting.txt"
            self.teamPitching = "static/teams/Indians_pitchers.txt"
        elif teamName == "Padres":
            self.teamBatting = "static/teams/Padres_batting.txt"
            self.teamPitching = "static/teams/Padres_pitchers.txt"
        elif teamName == "Pirates":
            self.teamBatting = "static/teams/Pirates_batting.txt"
            self.teamPitching = "static/teams/Pirates_pitchers.txt"
        elif teamName == "Rays":
            self.teamBatting = "static/teams/Rays_batting.txt"
            self.teamPitching = "static/teams/Rays_pitchers.txt"
        elif teamName == "Royals":
            self.teamBatting = "static/teams/Royals_batting.txt"
            self.teamPitching = "static/teams/Royals_pitchers.txt"
        else:
            print "enter a valid team, capitalize"

        try:
            scanner = open(var + "/"+ self.teamBatting, "r")
            scanner2 = open(var + "/" + self.teamPitching, "r")
          

            for line in scanner:
                playerData = line.split()
                player = Player(playerData)
                team.add_Player(player)

            for line in scanner2:# find a better way!
                if temp2 < self.pitcherCount:
                    playerData = ["0"] * 13
                    pitcherData = line.split()
                    pitcher = Pitcher(playerData, pitcherData)
                    team.add_Player(pitcher)
                    temp2 = temp2 + 1

            team.config_Batting_Roster()
            team.config_Fielding_Roster()
            
            scanner.close()
            scanner2.close()

        except:
            print "Unexpected error"

        

        return team
Пример #37
0
if len(sys.argv)!=3:
		print "INVALID COMMAND! 2 files should be given as arguments in command-line."
		exit()
import csv
	
with open(sys.argv[1], 'rb') as inputFile:	
		Championship= TeamList(0, teams=[])
		ChampionshipList= TeamList(0, teams= [])
		reader= csv.reader(inputFile)
		for row in reader:
			if(len(row[1])>63 or len(row[2])>63):
				print "INVALID INPUT FILE! The name of the team must be smaller than 63 characters. "
				exit()
			operation= row[0]
			if operation == 'CONSULTA':
					newTeam= Team(row[2], 0, 0, False)
					searchType= row[1]
					posit1= ChampionshipList.nameSearch(newTeam)
					if(posit1== -1):
						newTeam.rank= Championship.numTeams +1
						ChampionshipList.teams.append(newTeam) 
						posit1=ChampionshipList.numTeams
					if searchType== 'RANKING':
						if newTeam.played:
							pos=Championship.rankSearch(newTeam)	
    						print "RANKING,%s,%d" %(newTeam.name, pos)
						else:
							print "RANKING,%s,%d" %(newTeam.name, newTeam1Team.rank)	
					elif searchType== 'PONTUACAO':
						print "PONTUACAO,%s,%d" %(newTeam.name, ChampionshipList.teams[posit1].points)
					else: 
Пример #38
0
#trackingTeam will stay true as long as the user wants to look up teams. Will be set to false when the user is done with the program
trackingTeam = True

while trackingTeam:
	#find out which team the user wants to track
	team = ""
	print("Which team to you want to track?")
	teamNumber = raw_input()
	#make sure the input is a valid team number (in this case that means no letters and less than five digits)
	while (not teamNumber.isdigit()) or (len(teamNumber) >= 5):
		#Continue asking for the team number until a valid team number is entered
		print("Invalid input. Try again")
		teamNumber = raw_input()
	print("")#Add a new line to make things look nice
	#Create the instance of the team
	team = Team(teamNumber)
	
	print(team.getNickname())
	print("Rookie Year: " + team.getRookieYear())
	print("Last competed in: " + team.getYearsParticipated()[-1])
	print("Won the Chairman's Award " + team.getNumChairmans() + " time[s]")
	print("Won Engineering Inspiration " + team.getNumEI() + " time[s]")
	print("Winner of an event " + team.getNumWins() + " time[s]")
	print("Finalist of an event " + team.getNumFinals() + " time[s]")
	print("Won " + team.getNumOtherAwards() + " other award[s]")
	
	
	#Ask the user if he/she wants to track another team
	print("\nDo you want to track another team? y/n")
	answer = str(raw_input())
	#if the input was anything other than 'y' or 'Y,' exit the loop