Exemplo n.º 1
0
def main():
    p1 = player.Player('Kyle Lowry', 1, floor=70, ceiling=80)
    p2 = player.Player('DeMar DeRozan', 2, floor=70, ceiling=80)
    p3 = player.Player('James Johnson', 3, floor=70, ceiling=80)
    p4 = player.Player('Amir Johnson', 4, floor=70, ceiling=80)
    p5 = player.Player('Jonas Valanciunas', 5, floor=70, ceiling=80)
    p6 = player.Player('Lou Williams', 1, floor=70, ceiling=80)
    p7 = player.Player('Terrence Ross', 2, floor=70, ceiling=80)
    p8 = player.Player('Bruno Caboclo', 3, floor=70, ceiling=80)
    p9 = player.Player('Patrick Patterson', 4, floor=70, ceiling=80)
    p10 = player.Player('Chuck Hayes', 5, floor=70, ceiling=80)

    p11 = player.Player('Sam Baskerville', 1, floor=70, ceiling=80)
    p12 = player.Player('Brendan Tracey', 2, floor=70, ceiling=80)
    p13 = player.Player('Connor Petterson', 3, floor=70, ceiling=80)
    p14 = player.Player('Dan Fettes', 4, floor=90, ceiling=100)
    p15 = player.Player('Rick Nydam', 5, floor=70, ceiling=80)
    p16 = player.Player('James Tran', 1, floor=70, ceiling=80)
    p17 = player.Player('Brett Mitchell', 2, floor=70, ceiling=80)
    p18 = player.Player('David Teichrobe', 3, floor=70, ceiling=80)
    p19 = player.Player('Mike North', 4, floor=70, ceiling=80)
    p20 = player.Player('Logan Earnst', 5, floor=70, ceiling=80)

    t1 = team.Team('Toronto Raptors',
                   [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10])
    t2 = team.Team('Simcoe Sabres',
                   [p11, p12, p13, p14, p15, p16, p17, p18, p19, p20])

    sim_game(t1, t2, pbp=False)
Exemplo n.º 2
0
def simulate_week(wkNum, numGames, already_played=True, inc="",cor=""):
    with open('./data/week'+str(wkNum), 'r+') as ifile:
         matches = json.load(ifile)
         matches = map(str,matches)


    c = 0.0
    t = float(len(matches))/2
    i = 0
    while i < range(len(matches)):
        if i >= 31:
          break
    
        W = str(matches[i])
        L = str(matches[i+1])
        if W=='WSH':
           W='WAS'
        elif L=='WSH':
           L='WAS'
        team_1 = team.Team(W, './data/2013_nfl_pbp_through_wk_12.csv', numgames=None)
        team_2 = team.Team(L,'./data/2013_nfl_pbp_through_wk_12.csv', numgames=None )
        res =simulate_games(team_1, team_2, num_games=numGames)
        if already_played:
           inc = "Incorrect: "
           cor = "Correct: "
        if res[team_1.team_name] >= res[team_2.team_name]:
           print cor + W +" beats "+ L +" "+str(100*team_wins[W]/float(numGames)) +" percent of the time"
        else:
           print inc + L +" beats "+ W +" "+str(100*team_wins[L]/float(numGames)) +" percent of the time" 
           

           c+=1
        i=i+2
    if len(cor) > 1:
      print str(float(t-c)/t) + " Correct"
Exemplo n.º 3
0
    def setUp(self):
        self.teams = []

        self.teams.append(team.Team("Team A"))
        self.teams.append(team.Team("Team B"))
        self.teams.append(team.Team("Team C"))
        self.teams.append(team.Team("Team D"))
        self.teams.append(team.Team("Team E"))

        self.schedule = ss.round_robin_schedule(5)
Exemplo n.º 4
0
    def __init__(self):
        """Constructor Function

        Aqcuires and assembles all matches into match objects"""
        self.matches = []
        self.database_name = "scouting_system"
        self.db = database.Database("localhost", 27017)
        comp_matches = self.db.find_documents("scouting_system", "matches")
        for comp_match in comp_matches:
            self.matches.append(
                match.Match(
                    comp_match["team_number"],
                    comp_match["num_balls"],
                    comp_match["alliance_color"],
                    comp_match["match_num"],
                ))
        self.teams = []
        teams = self.db.find_documents("scouting_system", "teams", {})
        for comp_team in teams:
            self.teams.append(
                team.Team(
                    comp_team["team_number"],
                    comp_team["team_name"],
                    comp_team["rookie_year"],
                ))
Exemplo n.º 5
0
    def __init__(self):
        def_team_name = "teamtest0"
        self._team_name = def_team_name
        def_mode_name = "roundrobin"
        self._mode_name = def_mode_name
        self._port_names = []
        self._old_active_hwaddr = None

        self._parse_cmdline()

        if self._team_name == def_team_name:
            print "Using default team name \"%s\"" % def_team_name

        if self._mode_name == def_mode_name:
            print "Using default mode \"%s\"" % def_mode_name

        print "Team name is \"%s\"" % self._team_name
        self._t = team.Team(self._team_name, create=True, destroy=True)

        self._t.set_mode_name(self._mode_name)
        for port_name in self._port_names:
            self._t.port_add(port_name)

        if self._mode_name == "activebackup":
            self._port_change_handler_ab = team.TeamChangeHandler(
                self._port_change_handler_ab_func, None, team.TEAM_PORT_CHANGE)
            self._t.change_handler_register(self._port_change_handler_ab)

        self._port_change_handler = team.TeamChangeHandler(
            self._port_change_handler_func, None, team.TEAM_PORT_CHANGE)
        self._t.change_handler_register(self._port_change_handler)

        self._option_change_handler = team.TeamChangeHandler(
            self._option_change_handler_func, None, team.TEAM_OPTION_CHANGE)
        self._t.change_handler_register(self._option_change_handler)
Exemplo n.º 6
0
 def setUp(self):
     HuntUser.objects.all().delete()
     Landmark.objects.all().delete()
     Game.objects.all().delete()
     game = Game(name="game", running=False)
     game.save()
     lm = Landmark(name="dummy",
                   clue="dummy",
                   question="dummy",
                   answer="dummy",
                   order_num=-1)
     lm.save()
     self.maker = gamemaker.GameMaker()
     self.maker.make_team(["team1", "password1"])
     self.t = team.Team()
     lm1 = Landmark(name="landmark1",
                    clue="clue1",
                    question="question1",
                    answer="answer1",
                    order_num=-1)
     lm2 = Landmark(name="landmark2",
                    clue="clue2",
                    question="question2",
                    answer="answer2",
                    order_num=-1)
     lm1.save()
     lm2.save()
Exemplo n.º 7
0
def checkLebron():
  pid = 2544
  tid = 1610612748
  paceAd = 1.0325473383
  P = player.Player(pid, tid, paceAd)
  assert(P.isFreeAgent == False)
  assert(P.name == "LeBron James")
  checkDouble(P.tp, 1.5)
  checkDouble(P.mp, 37.7)
  checkDouble(P.ast, 6.3)
  checkDouble(P.fg, 10)
  checkDouble(P.tov, 3.5)
  checkDouble(P.fga, 17.6)
  checkDouble(P.fta, 7.6) 
  checkDouble(P.ft, 5.7)
  checkDouble(P.stl, 1.6)
  checkDouble(P.orb, 1.1)
  checkDouble(P.blk, 0.3)
  checkDouble(P.pf, 1.6)
  checkDouble(P.pts, 27.1)
  checkDouble(P.trb, 6.9)
  checkDouble(P.drb, 5.9)
  L = league.season1314averages()
  T = team.Team(tid, [], paceAd)
  print "Stats correct, PER =", P.getPER(L)
  print "Intangibles =", P.getIntangiblesScore()
  print "Age =", P.age
Exemplo n.º 8
0
def assemble_team():
    "Make a balanced team"
    newest_team = team.Team()
    cycle_count = 0
    cycle_limit = 1000
    while not newest_team.is_full():
        newest_player = curr_game_players[random.randint(0, len(curr_game_players) - 1)]

        if cycle_count >= cycle_limit * 0.8:
            if newest_team.is_valid_player_addition(newest_player, True):
                newest_team.add_player(newest_player)
                print("Subideal addition: %s (%s)" % (newest_player.get_hero().get_name(), newest_player.get_name()))
                remove_player_from_region_pool(newest_player)
            else:
                print("Unaccounted for case.")
        else:
            if newest_team.is_valid_player_addition(newest_player):
                newest_team.add_player(newest_player)
                remove_player_from_region_pool(newest_player)

        cycle_count += 1
        if cycle_count >= cycle_limit:
            print("Assemble_team with Ideal Conditions taking too long.\n")
            print(get_unassigned_players_roles())
            # del newest_team
            return

    return newest_team
Exemplo n.º 9
0
    def on_open(self):
        file = filedialog.askopenfilename(filetypes=(("JSON Files",
                                                      "*.json"), ))
        if file:
            try:
                with open(file) as data_file:
                    json_data = json.load(data_file)

                print(json_data)
                self.teams = {}
                for tm in json_data:
                    self.teams[tm] = team.Team(json_data[tm]['name'],
                                               int(json_data[tm]['played']),
                                               int(json_data[tm]['won']),
                                               int(json_data[tm]['draw']),
                                               int(json_data[tm]['lost']),
                                               int(json_data[tm]['gscored']),
                                               int(json_data[tm]['gconceded']),
                                               int(json_data[tm]['gdiff']),
                                               int(json_data[tm]['points']))

                print(self.teams)
                self.populate_table()
            except:  # <- naked except is a bad idea
                msgbox.showerror("Open Source File",
                                 "Failed to read file\n'%s'" % file)
            return
        return
Exemplo n.º 10
0
async def startgame(ctx):
    global players, teams
    if len(players) < 1:
        await ctx.send("Not enough players. %d players in: %s (four required)" % (len(players), str(players)))
        return
    else:
        teams = []
        random.shuffle(players)
        teams.append(team.Team(players=players[:len(players)//2]))
        teams.append(team.Team(players=players[len(players)//2:]))
        for p in players:
            if p.dm_channel == None:
                await p.create_dm()
        
        for t in teams:
            await t.send_welcome_messages()
Exemplo n.º 11
0
def getSeasonStats(ncaaTourneyTeams):
    """
    Use regular season results and RPI rankings to create a 
    dictionary where key is the team's ID and the value is a 
    Team object. Team objects contain yearly avg stats for each 
    team in various categories.
    """
    teams = {}
    names = getTeamNames()
    unfiltRanks = pd.read_csv("data/MasseyOrdinals_Prelim2018.csv")
    rankings = unfiltRanks[(unfiltRanks["SystemName"] == "RPI")
                           & (unfiltRanks["RankingDayNum"] == 133)]
    regSeasonResults = pd.read_csv("data/RegularSeasonDetailedResults.csv")
    for index, row in regSeasonResults.iterrows():
        season = row["Season"]
        dayNum = row["DayNum"]
        wTeamId = row["WTeamID"]
        lTeamId = row["LTeamID"]
        customWId = str(wTeamId) + "_" + str(season)
        customLId = str(lTeamId) + "_" + str(season)
        wRPI = None
        lRPI = None
        try:
            wRPI = rankings[(rankings["Season"] == season) & (
                rankings["TeamID"] == wTeamId)].iloc[0]["OrdinalRank"]
            lRPI = rankings[(rankings["Season"] == season) & (
                rankings["TeamID"] == lTeamId)].iloc[0]["OrdinalRank"]
        except Exception as e:
            pass
            # print str(lTeamId) + " " + str(season) + " not found"

        if customWId not in teams:
            teams[customWId] = team.Team(customWId)
        if customLId not in teams:
            teams[customLId] = team.Team(customLId)
        wTeam = teams[customWId]
        wTeam.RPI = wRPI
        wTeam.name = names[wTeamId]
        wTeam.updateStats(row, True)
        if customLId in ncaaTourneyTeams:
            wTeam.winsVsTourney += 1
        lTeam = teams[customLId]
        lTeam.name = names[lTeamId]
        lTeam.RPI = lRPI
        lTeam.updateStats(row, False)
    return teams
Exemplo n.º 12
0
 def load_data_text(self):
     f = open("leagues.txt", "r")
     for line in f:
         teamname, players = line.rstrip().split(":")
         newteam = team.Team(teamname)
         self.teams.append(newteam)
         for player in players:
             newteam.players.append(player)
Exemplo n.º 13
0
def results():
    if request.method == 'GET':
        return redirect(url_for('index'))
    else:
        form = list(request.form)
        my_team = team.Team()
        my_team.add_pokemon(form)
        session["team"] = my_team.get_names()
        return render_template('results.html', data=my_team)
 def __init__(self):
     self.teams = {
         _team: team.Team(_team, utils.games)
         for _team in utils.teams
     }
     self.team_locks = {team: prwlock.RWLock() for team in utils.teams}
     self.game_locks = {game: prwlock.RWLock() for game in utils.games}
     if not os.path.exists(data_dir):
         os.makedirs(data_dir)
     self.number_of_requests = 0
Exemplo n.º 15
0
    def on_append(self):
        text_add_teams = self.text_box_add_teams.get("1.0", tk.END).rstrip()
        text_add_teams = text_add_teams.replace(', ', ',')
        team_names = re.split(',', text_add_teams)
        for name in team_names:
            tm = team.Team(name)
            self.teams[name] = tm

        self.text_box_add_teams.delete("1.0", END)
        return
Exemplo n.º 16
0
def main():
    main_clock = pygame.time.Clock()
    gui = interface.Interface()
    teama = team.Team('a', gui.map)
    teamb = team.Team('b', gui.map)
    teamc = team.Team('c', gui.map)
    teams = [teamc, teama, teamb]
    gui.linkteams((teama, teamb, teamc))
    while True:
        gui.map.clean()
        for i in teams:
            i.draw(gui.map.image)
            i.update()
        gui.draw()
        gui.map.scroll(pygame.mouse.get_pos())
        teama.collisions(teamb, teamc)
        teamb.collisions(teama, teamc)
        teama.conquest(teamc)
        teamb.conquest(teamc)
        gui.help(pygame.mouse.get_pos())
        if gui.map.cameraistopleft():
            teams = [teamc, teama, teamb]
        else:
            teams = [teamc, teamb, teama]
        for eventos in pygame.event.get():
            if eventos.type == QUIT:
                terminate()
            elif eventos.type == MOUSEBUTTONDOWN:
                if eventos.button == 1:
                    gui.managementclick(pygame.mouse.get_pos(), 1)
                elif eventos.button == 3:
                    gui.managementclick(pygame.mouse.get_pos(), 2)
            elif eventos.type == KEYDOWN:
                print(eventos.key)
                if eventos.key == 127:
                    teama.supr()
                elif eventos.key == 282:
                    gui.revealmap()
        #teama.automata(teamb, teamc)
        teamb.automata(teama, teamc)
        pygame.display.flip()
        main_clock.tick(60)
Exemplo n.º 17
0
 def addTeam(self,
             number,
             qs,
             firstSort,
             secondSort,
             thirdSort,
             fourthSort=0,
             fifthSort=0):
     self.teams.append(
         team.Team(number, qs, firstSort, secondSort, thirdSort, fourthSort,
                   fifthSort))
Exemplo n.º 18
0
    def setUp(self):
        # We need to remove old dump to ensure that we are writing to a clean
        # file
        if os.path.isfile("testing.ssd"):
            os.remove("testing.ssd")

        self.teams = []

        self.teams.append(team.Team("Team A"))
        self.teams.append(team.Team("Team B"))
        self.teams.append(team.Team("Team C"))
        self.teams.append(team.Team("Team D"))
        self.teams.append(team.Team("Team E"))

        self.schedule = ss.round_robin_schedule(5)

        self.state = {}
        self.state['teams'] = self.teams
        self.state['schedule'] = self.schedule
        self.state['current_week'] = 0
Exemplo n.º 19
0
    def to_team(self, team_key):
        """Construct a Team object from a League

        :param team_key: Team key of the new Team object to construct
        :type team_key: str
        :return: Fully constructed object
        :rtype: Team
        """
        tm = team.Team(self.sc, team_key)
        tm.inject_yhandler(self.yhandler)
        return tm
Exemplo n.º 20
0
 def _update_teams(self):
     """Updates the team list"""
     self.teams = []
     teams = self.db.find_documents("scouting_system", "teams", {})
     for comp_team in teams:
         self.teams.append(
             team.Team(
                 comp_team["team_number"],
                 comp_team["team_name"],
                 comp_team["rookie_year"],
             ))
Exemplo n.º 21
0
def game():
    if request.method == 'GET':
        return redirect('teamSelect')
    else:
        data = dict(request.form)
        bot_bool = 0
        if 'bot' in data.keys():
            bot_bool = 1
        t1 = mongo.db.teams.find_one({'_id': ObjectId(data['team1'])})['team']
        t2 = mongo.db.teams.find_one({'_id': ObjectId(data['team2'])})['team']
        team1 = team.Team()
        team2 = team.Team()
        team1.add_pokemon(t1)
        team2.add_pokemon(t2)
        teams = {
            'team1': team1.get_team(),
            'team2': team2.get_team(),
            'typing': team1.get_array(),
            'bot': bot_bool
        }
        return render_template('game.html', data=teams)
Exemplo n.º 22
0
 def setUp(self):
     dummy_landmark = Landmark(name="dummy",
                               clue="dummy",
                               question="dummy",
                               answer="dummy",
                               order_num=-1)
     dummy_landmark.save()
     team1 = HuntUser(name="team1",
                      password="******",
                      current_landmark=dummy_landmark)
     team1.save()
     self.t = team.Team()
Exemplo n.º 23
0
    def test_team_set_up_2(self) -> None:
        """Init team with players and coach"""
        players: List[team.Player] = [
            team.Player('N1', 1),
            team.Player('N2', 2),
            team.Player('N3', 3)
        ]
        coach: team.Coach = team.Coach('Coach')
        t: team.Team = team.Team(players, coach)

        self.assertIsNotNone(t.players)
        self.assertIsNotNone(t.coach)
        self.assertIs(len(t.players), 3)
Exemplo n.º 24
0
    def __init__(self, team1, team2, pitchers1, pitchers2):
        self.inning = 1
        self.homeScore = 0
        self.awayScore = 0
        self.outs = 0
        self.bases = [0, 0, 0]
        self.display = baseDisplay.baseDisplay(team1, team2)

        #set avergae players
        response = requests.get(
            "http://lookup-service-prod.mlb.com/json/named.team_hitting_season_leader_master.bam?season=2019&sort_order=%27desc%27&sort_column=%27avg%27&game_type=%27R%27&sport_code=%27mlb%27&recSP=1&recPP=50"
        )
        data = response.json(
        )["team_hitting_season_leader_master"]["queryResults"]["row"]
        for te in data:
            bat.Batter.average_batter["strikeout_avg"] += int(te["so"])
            bat.Batter.average_batter["flyout_avg"] += int(te["ao"])
            bat.Batter.average_batter["groundout_avg"] += int(te["go"])
            bat.Batter.average_batter["hbp_avg"] += int(te["hbp"])
            bat.Batter.average_batter["double_avg"] += int(te["d"])
            bat.Batter.average_batter["triple_avg"] += int(te["t"])
            bat.Batter.average_batter["hr_avg"] += int(te["hr"])
            bat.Batter.average_batter["single_avg"] += (int(te["h"]) -
                                                        int(te["d"]) -
                                                        int(te["t"]) -
                                                        int(te["hr"]))
            bat.Batter.average_batter["bb_avg"] += int(te["bb"])
            bat.Batter.league_pa += (int(te["so"]) + int(te["ao"]) +
                                     int(te["go"]) + int(te["hbp"]) +
                                     int(te["h"]) + int(te["bb"]))

        for stat in bat.Batter.average_batter:
            bat.Batter.average_batter[stat] /= float(bat.Batter.league_pa)

        self.home = team.Team(team1, pitchers1)
        self.away = team.Team(team2, pitchers2)

        self.home.setOpponent(self.away)
        self.away.setOpponent(self.home)
Exemplo n.º 25
0
def main():
    intro()
    selectedteam = brosleague.teams[0]

    while True:
        menu(selectedteam)
        option = input("Pick one: ")
        if option in ['a', 'A']:
            selectedteam.print_roster()
        if option in ['b', 'B']:
            selectedteam.add_player()
        if option in ['c', 'C']:
            selectedteam.cut_player()
        if option in ['d', 'D']:
            print("Modify which player?")
            for i, player in enumerate(selectedteam.players):
                print(f"{i+1}. {player.name}")
            ch = int(input("Your choice: "))
            player = selectedteam.players[ch - 1]
            player.modify()
        if option in ['e', 'E']:
            print("batting practice goes here")
        if option in ['f', 'F']:
            print("trade players")
        if option in ['g', 'G']:
            selectedteam.go_to_store()
        if option in ['h', 'H']:
            for i, t in enumerate(brosleague.teams):
                print(f"{i+1}. {t.name}")
            inter = int(input("Select which team? "))
            selectedteam = brosleague.teams[inter - 1]
        if option in ['i', 'I']:
            teamname = input("Enter new team name: ")
            brosleague.teams.append(team.Team(teamname))
        if option in ['j', 'J']:
            for i, t in enumerate(brosleague.teams):
                print(f"{i+1}. {t.name}")
            delete_team = int(input("Delete which team? "))
            del brosleague.teams[delete_team - 1]
        if option in ['k', 'k']:
            brosleague.add_players()
            save_data()
        if option in ['q', 'Q']:
            yn = input("Now quitting...Save changes? (y/n) ")
            if yn in ['y', 'Y', 'yes', 'YES', "Yes"]:
                save_data()
            break
        if option in ['s', 'S']:
            save_data()
        if option in ['z', 'Z']:
            playgame()
Exemplo n.º 26
0
    def load(self, loadRosters=False):
        """
		Calls MLB.com server and loads all team information

		Arguments:
		loadRosters : If true, rosters will automatically be loaded (more HTTP requests!)
		"""
        f = Fetcher(Fetcher.MLB_LEAGUE_URL)

        for item in f.fetch():
            t = team.Team(item)
            if loadRosters:
                t.loadRoster()
            self.teams[t['team_code']] = t
Exemplo n.º 27
0
 def team_info(self, team_number):
     self._update_teams()
     """Displays info about a team"""
     team_dict = self.db.find_documents("scouting_system", "teams",
                                        {"team_number": team_number})
     if team_dict != []:
         team_dict = team_dict[0]
         user_team = team.Team(
             team_dict["team_number"],
             team_dict["team_name"],
             team_dict["rookie_year"],
         )
         return user_team.get_info()
     return f"Could not find team: {team_number}"
Exemplo n.º 28
0
 def setUp(self):
     Landmark.objects.all().delete()
     dummy_landmark = Landmark(name="dummy",
                               clue="dummy",
                               question="dummy",
                               answer="dummy",
                               order_num=-1)
     dummy_landmark.save()
     team1 = HuntUser(name="team1",
                      password="******",
                      current_landmark=dummy_landmark)
     team1.save()
     Game.objects.all().delete()
     self.game = Game(name="game", running=False)
     self.game.save()
     self.t = team.Team()
     self.maker = gamemaker.GameMaker()
Exemplo n.º 29
0
	def save_team_games(self, games, team_id, coach, season, grade):
		t = team.Team(key_name=str(team_id))
		t.teamId = str(team_id)
		for val in self.schoolNames:
			if coach.find(val) > -1:
				t.school = val
				coach = coach[len(val)+1:]
				coach = coach.strip()
				t.coach = coach
				logging.info("School = %s, Coach = %s" % (t.school, t.coach))
				t.season = season
				t.grade = grade
				t.year = 2015
				t.schedule = self.jsonify_games(games, team_id)
				if t.school is not None and t.grade is not None:
					t.put()
				break
Exemplo n.º 30
0
 def setUp(self):
     dummy_landmark = Landmark(name="dummy",
                               clue="dummy",
                               question="dummy",
                               answer="dummy",
                               order_num=-1)
     dummy_landmark.save()
     Game.objects.all().delete()
     game = Game(name="game", running=False)
     game.save()
     self.maker = gamemaker.GameMaker()
     self.maker.make_team(["team1", "password1"])
     self.maker.make_team(["team2", "password1"])
     self.maker.add_landmark(["landmark1", "clue1", "q1", "a1"])
     self.maker.add_landmark(["landmark2", "clue2", "q2", "a2"])
     self.maker.create_game(["landmark1", "landmark2"])
     self.t = team.Team()