예제 #1
0
	def get(self):
		start_time = time.time()
		availSeasons = AvailableSeasons()
		for s in availSeasons.getSeasons():
			logging.info("Beginning data load for season %d" % s.season)
			teamIds = self.get_team_ids(s.season)
			stcharlesurl = "http://www.cycstcharles.com/schedule.php?team=%s&pfv=y&sort=date&month=999&year=999&season=%d"
			for team_id in teamIds:
				team_url = stcharlesurl % (team_id[1], s.season)
				self.fetch_team_schedule(team_url, team_id)
			logging.info("Finished loading schedule data. Elapsed time (in mins): " + str((time.time() - start_time)/60))

		if memcache.flush_all():
			logging.info("Flushed everything from memcache.")
		else:
			logging.error("Error trying to flush the memcache.")

		t = Team()
		seasons = []
		for team in t.getSeasons():
			season = Season(season=team.season)
			if season not in seasons:
				seasons.append(season)
		if not memcache.add('seasons', seasons):
			logging.error('memcache failed to set')
예제 #2
0
파일: game.py 프로젝트: vmgarcia/CSGOSim
def game(team_name1, team_name2):

  team_a = Team(team_name1, Sides.CT)
  team_b = Team(team_name2, Sides.T)
  for i in range(Constants.GAMES_TO_PLAY):
    pistol = True
    for j in range(30):
      gmap = Game_Map()

      env = simpy.Environment()
      if (j == 16):
        switch_sides(team_a, team_b)
        pistol = True

      if (team_a.side == Sides.CT):
        team_a.respawn_players(env, pistol)
        team_b.respawn_players(env, pistol)
      else:
        team_b.respawn_players(env, pistol)
        team_a.respawn_players(env, pistol)
      pistol = False



      gmap.spawn_team(team_a)
      gmap.spawn_team(team_b)
      env.run(env.process(round(team_a, team_b, env)))

      if (team_a.round_wins == 16 or team_b.round_wins == 16):
        break
    game_over(team_a, team_b)
  print team_a
  print team_b
  return [float(team_a.game_wins)/float(team_a.game_wins + team_b.game_wins)*100, 
    float(team_a.total_round_wins)/ float(team_a.total_round_wins + team_b.total_round_wins) * 100]
    def _load_metadata(self):
        fname = self._metadata_fname()
        with open(fname) as f:
            data=json.load(f)

        assert data['id'] == self._id, "metadata id is {0} but should be {1}".format(data['id'], self._id)
        self.team_l = Team.decode(data['team_l'])
        self.team_r = Team.decode(data['team_r'])
예제 #4
0
파일: main.py 프로젝트: macartur-UNB/BS
 def create_teams(self):
     self.team_red = Team(self, 'Red Team', 'red', team_red_POSITIONS, True)
     self.team_blue = Team(self, 'Blue Team', 'blue', team_blue_POSITIONS, False)
     self.current_team = self.team_red
     self.teams = (self.team_red, self.team_blue)
     
     self.team_red.add_listener('released', self.movement_started)
     self.team_blue.add_listener('released', self.movement_started)
예제 #5
0
 def post(self):
   from user_sn import User, send_welcome_msg
   from team import Team
   import logging
   t = Team(name=self.request.get("teamname"))
   t.put()
   u = User(email=self.request.get("tlemail"),name=self.request.get("teamleader"),team=t,team_leader_flag=True)
   u.put()
   send_welcome_msg(u)
예제 #6
0
파일: player.py 프로젝트: lotaku/board-game
 def teamCreate(self):
     newTeam = Team()
     newTeam.create(self)
     self.iscaption=1
     self.team=newTeam  # 是指向队伍实例吧.? S 那边只能 self.team=newTeam.name
     self.teamName=newTeam.name
     draw.drawTeamMember(newTeam)
     print "创建队伍:" ,self.team
     teamManager.add(newTeam)
     playerManager.add(self)
예제 #7
0
 def setUp(self):
     """
     set up data used in the tests.
     setUp is called before each test function execution.
     """        
     self.maxSnails = 3
     self.team1 = Team("team1")
     self.team2 = Team("team2")
     self.team1.setGravity(Direction.UP)
     self.team2.setGravity(Direction.DOWN)
    def games(self, request):
		t = Team()
		responseArray = []
		schedule = t.getGamesMultiTeams(request.team_ids)
		gamesArray = eval(schedule)
		for game in gamesArray:
			logging.info(game)
			responseGame = Games(game_date=game['game_date'][5:], time=game['time'], home=game['home'], away=game['away'], location=game['location'], game_id=game['id'], score=game['score'])
			responseArray.append(responseGame)
		return GamesMultiTeamResponse(games=responseArray)
예제 #9
0
def main():
    if "-c" in sys.argv:
        clean()
    val = load()
    t = Team(val)

    if "-r" in sys.argv:
        t.removeOut()

    t.build(budget)
예제 #10
0
 def build_teams(self):
     team_ids = set()
     for row in self.owner_rows:
         team_ids.add(row.get('id')[:-2])
     for id in team_ids:
         team = Team(id)
         this_team_element = self.owners_page_root.get_element_by_id(id + "-0")
         team.abbreviation = this_team_element[1].text_content()
         team.name = this_team_element[2].text_content()
         team.division = this_team_element[3].text_content()
         self.teams.add(team)
예제 #11
0
파일: player.py 프로젝트: lotaku/board-game
def gs2cOtherTeamCreate(player,packet):
    playerName = packet.unpackString()
    teamName= packet.unpackString()
    playerGeted = playerManager.getPlayerByName(playerName)
    newTeam = Team()
    newTeam.create(playerGeted)
    playerGeted.iscaption =1
    playerGeted.team=newTeam.name
    playerGeted.teamName=teamName
    teamManager.add(newTeam)
    playerManager.add(playerGeted)
예제 #12
0
	def npc_match(team1, team2, players, teams):
		team1Name = Team.return_name(teams[team1])
		team2Name = Team.return_name(teams[team2])		
		difference= CoreGame.mute_compare_players(team1, team2, players, team1Name, team2Name)
		winner = CoreGame.find_winner(0, 0, 0, difference)
		if winner == 0:
			Team.won_game(teams[team1])
			Team.lost_game(teams[team2])
		elif winner == 1:
			Team.lost_game(teams[team1])
			Team.won_game(teams[team2])
예제 #13
0
파일: game.py 프로젝트: jy19/CS478-Pokemon
def main():
    from argparse import ArgumentParser

    argparser = ArgumentParser()
    argparser.add_argument('team1')
    argparser.add_argument('team2')
    argparser.add_argument('--depth', type=int, default=2)
    argparser.add_argument('--gamestate', type=str)
    argparser.add_argument('--player', type=int, default=0)
    args = argparser.parse_args()
    pokedata = load_data("data")

    players = [None, None]
    # players[args.player] = HumanAgent()
    players[args.player] = PessimisticMinimaxAgent(2, pokedata, log_file="normal.txt")
    # players[1 - args.player] = PessimisticMinimaxAgent(2, pokedata, log_file="no_cache.txt", use_cache=False)
    # players[1 - args.player] = DumbAgent()
    players[1 - args.player] = HumanAgent()

    with open(args.team1) as f1, open(args.team2) as f2, open("data/poke2.json") as f3:
        data = json.loads(f3.read())
        poke_dict = Smogon.convert_to_dict(data)
        teams = [Team.make_team(f1.read(), poke_dict), Team.make_team(f2.read(), poke_dict)]

    gamestate = GameState(teams)
    if args.gamestate is not None:
        with open(args.gamestate, 'rb') as fp:
            gamestate = pickle.load(fp)
    with open('cur2.gs', 'wb') as fp:
        pickle.dump(gamestate, fp)
    gamestate.create_gamestate_arff(0)
    gamestate.print_readable_data(0)
    gamestate.print_readable_data(1)
    simulator = Simulator(pokedata)
    while not gamestate.is_over():
        print "=========================================================================================="
        print "Player 1 primary:", gamestate.get_team(0).primary(), gamestate.get_team(0).primary().status
        print "Player 2 primary:", gamestate.get_team(1).primary(), gamestate.get_team(1).primary().status
        print ""

        my_action = players[0].get_action(gamestate, 0)
        opp_action = players[1].get_action(gamestate, 1)
        gamestate = simulator.simulate(gamestate, [my_action, opp_action], 0, log=True)
    if gamestate.get_team(0).alive():
        print "You win!"
        print "Congrats to", gamestate.opp_team
        print "Sucks for", gamestate.my_team
    else:
        print "You lose!"
        print "Congrats to", gamestate.my_team
        print "Sucks for", gamestate.opp_team
    gamestate.turn += 1
예제 #14
0
    def write_schedule_swap_matrix(self, file='swapped schedules.csv'):
        data = {x.name: {x.name: 1} for x in self.teams}
        for tA, tB in itertools.combinations(self.teams, 2):
            A, B = tA.name, tB.name
            # swap the values
            self.schedule[A]['schedule'], self.schedule[B][
                'schedule'] = self.schedule[B]['schedule'], self.schedule[A][
                    'schedule']

            wA, wB = tA.expected_wins(
                tA.project_win_totals()[-1]), tB.expected_wins(
                    tB.project_win_totals()[-1])
            teamA = Team(name=A, schedule=self.schedule)

            data[A][B] = teamA.expected_wins(
                teamA.project_win_totals()[-1]) / wA

            teamB = Team(name=B, schedule=self.schedule)

            data[B][A] = teamB.expected_wins(
                teamB.project_win_totals()[-1]) / wB

            # unswap the values
            self.schedule[A]['schedule'], self.schedule[B][
                'schedule'] = self.schedule[B]['schedule'], self.schedule[A][
                    'schedule']

        with open(file, 'w+', newline='') as outfile:
            cw = csv.writer(outfile)
            cw.writerow(['', *sorted(list(data.keys()))])
            keys = sorted(list(data.keys()))
            for team in keys:
                row = [data[team][x] for x in keys]
                cw.writerow([team, *row])
예제 #15
0
    def test_get_max_tierce(self):
        p1, p2, p3, p4 = Player(name='ime1'), Player(name='ime2'),\
         Player(name='ime3'), Player(name='ime4')
        t1, t2 = Team('prqkor1', p1, p3), Team('prqkor2', p2, p4)
        p1.announcements = {BELOTE_TIERCE_STRING: [Card('9', 's')]}
        p2.announcements = {BELOTE_TIERCE_STRING: [Card('Q', 's')]}
        p3.announcements = {BELOTE_TIERCE_STRING: [Card('A', 's')]}
        p4.announcements = {BELOTE_TIERCE_STRING: [Card('K', 'c')]}

        t1.get_max_tierce()
        t2.get_max_tierce()

        self.assertEqual(t1.highest_tierce, Card('A', 's'))
        self.assertEqual(t2.highest_tierce, Card('K', 'c'))
예제 #16
0
def top_trading_cycles(teams, users):
    while teams:
        graph = {}
        for team in teams:
            for user in team.user_prefs(users):
                if (Team.team_with_user(teams, user)):
                    graph[team] = (Team.team_with_user(teams, user), user)
                    break
        cycles = detect_cycles(graph)
        for cycle in cycles:
            for team in cycle:
                team.take_user_from(graph[team][0], graph[team][1])
            for team in cycle:
                teams.pop(teams.index(team))
예제 #17
0
def get_team_dictionary(team_file_list, elo_scores):
    team_names = set()
    teams = {}
    #Set up Team set
    for i in team_file_list[:
                            12]:  #assumes all 8 teams appear in first 12 games. This number can be increased
        #to accomodate more games without negative side effects
        team_names.add(i['team1'])
        team_names.add(i['team2'])
    #translate Team set to team dictionary
    for i in team_names:  #add teams to dictionary keyed by their name
        teams[i] = Team(i)
        teams[i].elo = elo_scores[i]
    return teams
예제 #18
0
def main():
    # set up the data
    # set up 8 teams
    # only one manager per team
    # only one league

    players = []
    for i in range(100):
        players.append(generate_player())

    # more teams will be added later on
    teams = [
        Team('Toronto Raptors'),
        Team('Los Angeles Lakers'),
        Team('Houston Rockets'),
        Team("Golden State Warriors"),
        Team('Oklahoma City Thunder'),
        Team('Philadelphia 76ers'),
        Team('Portland Trail Blazers'),
        Team('Milwaukee Bucks')
    ]

    for team in teams:
        # give them 5 starting players
        for player_num in range(5):
            selected_player = random.choice(players)
            team.players.append(selected_player)
            players.remove(selected_player)

    # one league
    first_league = League('NBA')
    first_league.set_teams(teams)
예제 #19
0
 def season(self, request):
     theCache = memcache.get("seasons")
     if theCache is None:
         t = Team()
         seasons = []
         for team in t.getSeasons():
             season = Season(season=team.season)
             if season not in seasons:
                 seasons.append(season)
         if not memcache.add("seasons", seasons):
             logging.error("memcache failed to set")
         return SeasonResponse(seasons=seasons)
     else:
         return SeasonResponse(seasons=theCache)
	def test_team_validate_players_raises_exception_when_not_two_players(self):
		p1 = Player('Pesho')
		p2 = Player('Gosho')
		p3 = Player('Tosho')
		test_players = [p1, p2, p3]
		exc = None

		try:
			Team.validate_players(test_players)
		except Exception as err:
			exc = err

		self.assertIsNotNone(exc)
		self.assertEqual(str(exc), 'Only 2 players per team.')
예제 #21
0
 def season(self, request):
     theCache = memcache.get('seasons')
     if theCache is None:
         t = Team()
         seasons = []
         for team in t.getSeasons():
             season = Season(season=team.season)
             if season not in seasons:
                 seasons.append(season)
         if not memcache.add('seasons', seasons):
             logging.error('memcache failed to set')
         return SeasonResponse(seasons=seasons)
     else:
         return SeasonResponse(seasons=theCache)
def top_trading_cycles(teams,users):
    while teams:
        graph = {}
        for team in teams:
            for user in team.user_prefs(users):
                if(Team.team_with_user(teams,user)):
                    graph[team] = (Team.team_with_user(teams,user),user)
                    break
        cycles = detect_cycles(graph)
        for cycle in cycles:
            for team in cycle:
                team.take_user_from(graph[team][0],graph[team][1])
            for team in cycle:
                teams.pop(teams.index(team))
예제 #23
0
def test_team_attack_deaths():
    team_one = Team("One")
    jodie = Hero("Jodie Foster")
    aliens = Ability("Alien Friends", 10000)
    jodie.add_ability(aliens)
    team_one.add_hero(jodie)
    team_two = Team("Two")
    athena = Hero("Athena")
    socks = Armor("Socks", 10)
    athena.add_armor(socks)
    team_two.add_hero(athena)
    assert team_two.heroes[0].deaths == 0
    team_one.attack(team_two)
    assert team_two.heroes[0].deaths == 1
예제 #24
0
def unpack_team(team):
	new_team = Team()
	new_team.name = team['name']
	new_team.slug = team['slug']
	new_team.id = team['id']
	new_team.country = team['country']
	new_team.race = team['race']
	new_team.full_name = team['full_name']
	new_team.country = team['country']
	new_team.image_url = team['image_url']
	return new_team
예제 #25
0
    def build_team_one(self):
        '''
        Prompt the user to build team_one.
        '''
        # This method should allow a user to create team one.
        # Prompt the user for the number of Heroes on team one
        # call self.create_hero() for every hero that the user wants to add to team one.
        # Add the created hero to team one.
        numOfTeamMembers = int(input("How many members would you like on Team One?\n"))
        name = input("Team 1 Name: ")
        self.team_one = Team(name)

        for hero in range(numOfTeamMembers):
            hero = self.create_hero()
            self.team_one.add_hero(hero)
예제 #26
0
def simulate_match(team1, team2):
    # simulates match for the given teams
    team = [team1, team2]

    teams = []
    teams.append(Team(team[0], team[1]))
    teams.append(Team(team[1], team[0]))

    toss_result = toss(teams[0].teamname(), teams[1].teamname())

    simulate_inning(teams[toss_result[0]])
    simulate_inning(teams[(toss_result[0] + 1) % 2],
                    teams[toss_result[0]].getscore())

    return (toss_result, teams)
예제 #27
0
 def _generate_match_html(self, match):
     if isinstance(match, Match):
         if "TBD" in (match.team1_fullname, match.team2_fullname):
             return ""
         blue_team = Team.find(match.team1_fullname)
         red_team = Team.find(match.team2_fullname)
         start_time = match.start_time.strftime("%H%M: ")
     else:
         blue_team, red_team = match
         start_time = ""
     if not isinstance(match, Match) or match.games > 1:
         self.html += "<br/>"
     self._generate_game_html(blue_team, red_team, start_time)
     if not isinstance(match, Match) or match.games > 1:
         self._generate_game_html(red_team, blue_team, start_time)
def create_team(heroes=[]):
    teams = [
        "Orchids", "Red", "Blue", "Cheese Steaks", "Warriors", "49ers",
        "Marvel", "DC", "Rat Pack", "The Little Red Riding Hoods", "Team One",
        "Generic Team", "X-men", "Team Two", "Golden Champions",
        "Vegan Protectors", "The Cardinals", "Winky Bears", "Steelsmiths",
        "Boilermakers", "Nincompoops"
    ]
    name = teams[random.randint(0, len(teams) - 1)]
    team = Team(name)
    if len(heroes) > 0:
        for member in heroes:
            team.add_hero(member)

    return team
예제 #29
0
    def test_current_team_after_load(self):
        """
        Test Data.load_saved_team()
        """

        test_data_class = Data("test")
        test_data_class.team_data = [
            Team("test team 1", test_data_class.default_pokemon_list),
            Team("test team 2", test_data_class.default_pokemon_list)
        ]
        Data.select_saved_team = MagicMock(return_value="test team 2")
        test_data_class.load_saved_team()
        self.assertEqual(
            test_data_class.team_data[1], test_data_class.current_team,
            "test team 2 was not set to the current team attribute!")
예제 #30
0
 def run(self):
     matches = []
     b1, b2 = self.bot1(), self.bot1()
     b3, b4 = self.bot2(), self.bot2()
     T1 = Team(b1, b2, name="Bot 1")
     T2 = Team(b3, b4, name="Bot 2")
     for i in range(self.runterm):
         print('Match', i + 1, 'of', self.runterm)
         M = Map(False)
         G = Game(M, T1, T2)
         G.opt["Timelimit"] = self.timelimit
         matches.append(G.run())
         print()
         del M, G
     return matches
예제 #31
0
파일: dataparse.py 프로젝트: mivade/cfbrank
def parseSunCSV(filename, teamd={}):
    """Prase Sunshine Forecast data file."""
    if not isinstance(teamd, dict):
        raise RuntimeError("teamd must be a dictionary!")
    datafile = csv.reader(open(filename, 'r'))
    for i, row in enumerate(datafile):
        if i == 0 or len(row[2].split()) == 0:
            continue
        home, away = row[3], row[1]
        home_score, away_score = int(row[4]), int(row[2])
        ## if home == 'Texas' or away == 'Texas':
        ##     print home_score, home, "--", away, away_score
        ##     if home == 'Texas':
        ##         print home_score > away_score
        ##     else:
        ##         print away_score > home_score
        for school in [home, away]:
            if not teamd.has_key(school):
                FBS = school in sun_names
                teamd[school] = Team(school, "", FBS)
        home_won = home_score > away_score
        teamd[home].addOpponent(teamd[away], home_won)
        teamd[home].points_for += home_score
        teamd[home].points_against += away_score
        teamd[away].addOpponent(teamd[home], not home_won)
        teamd[away].points_for += away_score
        teamd[away].points_against += home_score
    return teamd
예제 #32
0
def _maketeams(team_numbers):
    f = open(ABS_DATA_DIR)

    teams = [Team(t, partner=i < 3) for i, t in enumerate(team_numbers)]

    for line in f:
        splitline = line.split(',')
        t = splitline[TEAM]
        if t in team_numbers:
            try:
                teams[team_numbers.index(t)].addline(splitline)
            except IndexError as e:
                printing.printf('Incomplete line in data: ',
                                style=printing.ERROR,
                                log=True,
                                logtag='Team.addline.error')
                printing.printf(line,
                                style=printing.YELLOW,
                                log=True,
                                logtag='Team.addline.error')
                log('Team.addline.error', str(e))
            except Exception as e:
                printing.printf('Unknown error in strategy request: ',
                                style=printing.ERROR,
                                log=True,
                                logtag='Team.addline.error')
                printing.printf(str(e),
                                style=printing.ERROR,
                                log=True,
                                logtag='Team.addline.error')
                printing.printf('On line: ' + line,
                                style=printing.YELLOW,
                                log=True,
                                logtag='Team.addline.error')
    return teams
	def test_team_str_representation_is_as_expected(self):
		p1 = Player('Pesho')
		p2 = Player('Gesho')
		
		test_team = Team('Team1',[p1, p2])

		self.assertEqual(str(team), 'Team1')
예제 #34
0
def getCurrentTeams(suppressOutput=True):

    teams = dict()
    glsoup = getSoupFromURL('https://www.basketball-reference.com/teams/',
                            suppressOutput)

    active_teams_table = glsoup.find(
        'table', id='teams_active')  # id for reg season table
    all_rows = active_teams_table.find_all("th",
                                           attrs={"data-stat": "franch_name"})
    active_teams = list()
    for row in all_rows:
        team = row.find("a")
        if team is None:
            continue
        active_teams.append(team)
    for team in active_teams:
        name = team.get_text()
        try:
            teams[name] = Team(
                name,
                'https://www.basketball-reference.com' + team.attrs['href'])
        except Exception as e:
            print("ERROR:", e)
    sleep(1)  # sleeping to be kind for requests

    return teams
예제 #35
0
def getAllTeams():
    session = getSession()
    try:
        r = getRequest()
        #conn.request("GET", "/mlb/v2/JSON/News?%s" % params, "{body}",
        #    headers) #response = conn.getresponse()
        if r != None:
            data = r.json()
            print(r.json())
            for item in data:
                theID = item['TeamID']
                query = session.query(Team).filter(
                    Team.TeamID == theID).scalar()
                thisTeam = Team(**{
                    k: v
                    for k, v in item.items() if k in Team.__table__.columns
                })
                if query is None:
                    ''
                    session.add(thisTeam)
                else:
                    query = session.merge(
                        thisTeam
                    )  #session.query(News).filter(News.NewsID == theID).update(newsItem)
                session.commit()
                print(thisTeam)
            #for key, value{j in item.items():
            #    print(str(key)+ ': '+ str(value))
    except Exception as e:
        print("[Errno {0}] ".format(e))
예제 #36
0
    def test_with_one_tierce(self):
        p1, p2, p3, p4 = Player(name='ime1'), Player(name='ime2'),\
         Player(name='ime3'), Player(name='ime4')
        t1, t2 = Team('prqkor1', p1, p3), Team('prqkor2', p2, p4)
        r = Round(1, t1, t2)
        p1.announcements = {BELOTE_TIERCE_STRING: [Card('9', 's')]}
        p2.announcements = {}
        p3.announcements = {}
        p4.announcements = {}

        r.check_tierce()

        self.assertEqual(p1.announcements[BELOTE_TIERCE_STRING], [Card('9', 's')])
        self.assertNotIn(BELOTE_TIERCE_STRING, p2.announcements.keys())
        self.assertNotIn(BELOTE_TIERCE_STRING, p3.announcements.keys())
        self.assertNotIn(BELOTE_TIERCE_STRING, p4.announcements.keys())
예제 #37
0
    def generate_fixture_list(self, teams: list, total_rounds):
        """Generate fixtures from a list of teams, and returns the fixtures
        as a list"""

        #adding a team to create the fixtures
        if len(teams) % 2 != 0:
            teams.append(Team(self.database, 0, 'Day Off'))
        n = len(teams)

        match = []
        fixtures_in_rounds = []
        for fixture in range(1, n):
            for i in range(round(n / 2)):
                match.append((teams[i], teams[n - 1 - i]))
            teams.insert(1, teams.pop())
            fixtures_in_rounds.append(match)
            match = []

        fixtures = []

        #changing the structure to a list of fixtures
        for rounds in fixtures_in_rounds:
            for game in rounds:
                if game[0].name != 'Day Off' and game[1].name != 'Day Off':
                    fixtures.append(game)

        #removing day off from the class teams list
        for index, team in enumerate(teams):
            if team.name == 'Day Off':
                teams.pop(index)

        return fixtures * total_rounds
예제 #38
0
def import_teams_from_json(file_name):
    with open(file_name) as json_file:
        data = json.load(json_file)
        for p in data['teams']:
            team_reference = p['team_id']
            team_reference = Team(p['team_id'], p['team_name'])
            teams_list.append(team_reference)
예제 #39
0
    def test_delete_team_from_team_data(self):
        """
        Test Data.delete_saved_team()
        """

        test_data_class = Data("test")
        test_data_class.team_data = [
            Team("test team 1", test_data_class.default_pokemon_list),
            Team("test team 2", test_data_class.default_pokemon_list)
        ]
        test_data_class.current_team = test_data_class.team_data[0]
        Data.select_saved_team = MagicMock(return_value="test team 1")
        test_data_class.delete_saved_team()
        self.assertEqual(len(test_data_class.team_data), 1)
        self.assertEqual(test_data_class.team_data[0].name, "test team 2")
        self.assertIsNone(test_data_class.current_team)
예제 #40
0
 def statistic2(self):
     self.ui.team1_result.hide()
     self.ui.team2_result.hide()
     self.get_teams()
     self.team2 = Team(self.team2)
     self.team2.make_graph()
     self.team2.calculate_predicted()
     plt.cla()
     ax = self.figure.add_subplot(111)
     ax.plot(self.team2.xs,
             self.team2.ys,
             label=self.team2.name,
             marker="o")
     ax.plot(self.team2.xs, self.team2.predicted, label="Trend")
     ax.legend()
     self.canvas.draw()
예제 #41
0
 def __init__(self, team_text, agent, username, pokedata, password=None,
              monitor_url=None, proxy=False, browser='phantomjs', predictor_name='PokeFrequencyPredictor',
              verbose=False, kernel_dir="kernel", kernel=False, lib_dir="lib"):
     self.logger = logging.getLogger("showdown")
     self.logger.setLevel(level=logging.INFO)
     self.agent = agent
     self.username = username
     self.password = password
     self.team_text = team_text
     self.predictor_name = predictor_name
     self.monitor_url = monitor_url
     self.battle_url = None
     self.pokedata = pokedata
     self.smogon_data = pokedata.smogon_data
     self.smogon_bw_data = pokedata.smogon_bw_data
     self.graph_move = pokedata.graph_move
     self.graph_poke = pokedata.graph_poke
     self.poke_moves = pokedata.poke_moves
     self.my_team = Team.make_team(team_text, self.smogon_data)
     self.opp_team = None
     self.simulator = Simulator(pokedata)
     arch = platform.architecture()
     self.lib_dir = Path(lib_dir) / OS_MAP[arch[0]][arch[1]]
     self.selenium = Selenium(proxy=proxy, browser=browser, lib_dir=self.lib_dir)
     self.verbose = verbose
     self.kernel_dir = Path(kernel_dir)
     self.kernel = kernel
     if self.kernel and not self.kernel_dir.exists():
         self.kernel_dir.mkdir()
     self.state = KernelState(self.kernel_dir / KERNEL_STATE, self.kernel)
     self.state.update_state("status", "idle")
     if self.verbose:
         self.logger.setLevel(level=logging.DEBUG)
예제 #42
0
    def create_team(self):
        '''Prompt user for team'''

        team_name = input("Team's name: ")
        tsmteam = True
        while tsmteam == True:
            response = input("Is this a tsm team? (y/n) ")
            if response == "y":
                team = TSM(team_name)
                x = 0
                while x > 2:
                    player = self.create_player()
                    team.add_player(player)
                    x += 1
                return team
            else:
                tsmteam = False

        team = Team(team_name)
        x = 0
        while x > 2:
            player = self.create_player()
            team.add_player(player)
            x += 1
        return team
예제 #43
0
    def test_save_team_data(self):
        """
        Test that team data is saved correctly
        """

        test_data_class = Data("test")
        test_data_class.team_data = [
            Team("test team", test_data_class.default_pokemon_list)
        ]
        test_data_class.save_all_teams()
        with open(project_path + "/json/test_data.json", "r") as f:
            saved_data = json.loads(f.read())

        self.assertIsInstance(saved_data, list,
                              "The team data didn't save as a list of teams!")
        self.assertIsInstance(
            saved_data[0], dict,
            "The element in the saved data list isn't a dictionary of attributes for the Team object!"
        )
        self.assertEqual(
            saved_data[0]["name"], test_data_class.team_data[0].name,
            "The saved team doesn't have the correct name attribute!")
        self.assertEqual(
            len(saved_data[0]), 2,
            "The dictionary of attributes doesn't have 2 key, value pairs!")
예제 #44
0
def kmeans_assignment(exper_data, users, max_size):
    assignments = []
    weights = w.find_weights(exper_data, max_size)
    # the reason why appending 0 here is for later exper_date transformation,
    # if stu did not bid the topic, the weight of that topic will be 0
    weights.append(0)
    exper_data = [[weights[int(data) - 1] for data in row]
                  for row in exper_data]
    count = 0  # count the # of stu who did not bid any topics
    stuff = []
    for i in range(len(exper_data)):
        if sum(exper_data[i]) == 0:
            stuff.append(users[i])
            count += 1
    print("{} student(s) who did not bid any topics.".format(count))
    for user in stuff:
        print(user.pid)  # print pid of users who did not bid any topics
    # The reason why adding the index to the end of each item in exper_data is that
    # it is used for identify the corresponding user after performing k-means clustering
    build_teams([exper_data[i] + [i] for i in range(len(exper_data))],
                assignments, max_size)
    teams = [
        Team([users[user[-1]] for user in group]) for group in assignments
    ]
    for team in teams:
        for other_team in team.team_prefs(teams):
            if team is not other_team and len(team.members) + len(
                    other_team.members) <= max_size:
                team.merge_with_team(teams.pop(teams.index(other_team)))
    return (teams, users)
예제 #45
0
 def get_team(self, team_id, team_name):
     for team in self.teams:
         if team.team_id == team_id:
             return team
     new_team = Team(team_id, team_name)
     self.teams.append(new_team)
     return new_team
예제 #46
0
    def generate_team_from_team_dict(self, team_dict: Dict[Any, Any]) -> Team:
        """
        Takes a dictionary of team data and creates a Team object out of it

        Parameters
        ----------
        team_dict: dict
            A dictionary of data that holds information about a certain Teams performance in one NBA game

        Returns
        -------
        Team
            The Team object converted from the dictionary of team data
        """
        name: str = team_dict['name']
        scores: Dict[GamePeriod, int] = dict()
        for period in team_dict['scores']:
            scores[convert_to_game_period(
                period)] = team_dict['scores'][period]
        totals: Dict[PlayerStatTypes, float] = dict()
        for stat_type in team_dict['totals']:
            converted_type: PlayerStatTypes = convert_to_player_stat_type(
                stat_type)
            if converted_type:
                totals[converted_type] = team_dict['totals'][stat_type]
        players = [
            self.generate_player_from_player_dict(team_dict['players'][player])
            for player in team_dict['players']
            if self.generate_player_from_player_dict(team_dict['players']
                                                     [player]) is not None
        ]
        return Team(name=name,
                    scores=scores,
                    team_stats=totals,
                    players=players)
예제 #47
0
def init_ratings(team_directory,teams):

    for team_id in teams:
        team_obj = Team(team_id)
        team_directory[team_id] = team_obj

    return team_directory
예제 #48
0
 def reset(self):
     self.state.update_state("status", "idle")
     self.logger.info("Resetting...")
     self.simulator.score = 0
     self.simulator.total = 0
     self.selenium.reset()
     self.opp_team = None
     self.my_team = Team.make_team(self.team_text, self.smogon_data)
예제 #49
0
 	def school(self, request):
		cacheKey = request.season
		if cacheKey is None:
			cacheKey = 'AllSchools'
		theCache = memcache.get(cacheKey)
		if theCache is None:
			t = Team()
			schools = []
			for team in t.getSchools(request.season):
				school = School(school=team.school)
				if school not in schools:
					schools.append(school)
			if not memcache.add(cacheKey, schools):
				logging.error('Unable to set cache')
			return SchoolResponse(schools=schools)
		else:
			return SchoolResponse(schools=theCache)
예제 #50
0
    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.teams= []
        self.team1 = Team("team1")
        self.team2 = Team("team2")
        pygame.init()
        self.team1.addSnails(2)
        self.team2.addSnails(3)

        self.teams.append(self.team1)
        self.teams.append(self.team2)

        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)
예제 #51
0
	def coach(self, request):
		cacheKey = 'AllCoaches'
		if (request.school is not None) and (request.season is None):
			cacheKey = request.school
		else:
			cacheKey = request.season + request.school
		theCache = memcache.get(cacheKey)
		if theCache is None:
			t = Team()
			coaches = []
			for team in t.getCoaches(request.school, request.season):
				coach = Coach(team_id=team.teamId, name=team.coach, school=team.school, grade=team.grade)
				coaches.append(coach)
			if not memcache.add(cacheKey, coaches):
				logging.error('Unable to set cache')
			return Coaches(coaches=coaches)
		else:
			return Coaches(coaches=theCache)
예제 #52
0
    def manages_team(self, team_or_team_name):
        # if it's a string get an internal representation
        if isinstance(team_or_team_name, basestring):
            if not Team.valid_team_name(team_or_team_name):
                # raise?
                return False
            else:
                team_or_team_name = Team(team_or_team_name)

        return self._manages_team(team_or_team_name)
예제 #53
0
class TestTimer(unittest.TestCase):
    """
    A test class for the Timer module.
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """
        self.teams= []
        self.team1 = Team("team1")
        self.team2 = Team("team2")
        pygame.init()
        self.team1.addSnails(2)
        self.team2.addSnails(3)

        self.teams.append(self.team1)
        self.teams.append(self.team2)

        self.turnManager = TurnManager()
        self.turnManager.setTeams(self.teams)

#    def testInitialized(self):
#        """
#        Test if init goes good
#        """
#        self.assertEqual(self.turnManager.teams, self.teams)
#        self.assertEqual(self.turnManager.teams[0], self.team1)
#        self.assertEqual(self.turnManager.teams[1], self.team2)
#
#        self.assertEqual(self.turnManager.status, TurnStatus.BREAK)
#        self.assertEqual(self.turnManager.startTime, Settings.TIMER_STARTTIME)
#        self.assertEqual(self.turnManager.size, Settings.TIMER_SIZE)
#        self.assertEqual(self.turnManager.position, Settings.TIMER_POSITION)
#        self.assertEqual(self.turnManager.font_size, Settings.TIMER_FONT_SIZE)

    def testSingleton(self):
        """
        Test if the singleton works
        """
        turnmanager2 = TurnManager()
        self.assertEqual(id(self.turnManager), id(turnmanager2))
예제 #54
0
 def get_team_info(self):
   with open('data/teams.csv') as csvfile:
     next(csvfile)
     teams = csv.DictReader(csvfile)
     for team in teams:
       new_team = Team(team['TDNA'], team['TSNA'])
       new_team._id = team['TGID']
       new_team.division = 'Div FBS' if team['LGID'] == '0' else 'FCS'
       new_team.wins = int(team['TSWI'])
       new_team.losses = int(team['TSLO'])
       new_team.bcs_rank = int(team['TBRK'])
       new_team.previous_bcs_rank = int(team['TBPR'])
       new_team.games = []
       self.data.teams.append(new_team)
예제 #55
0
    def inviteAnswerReply(self, answer, members, inviter, invitee):
        from player import localPlayer
        from team import Team
        from player_manager import playerManager
        from team_manager import teamManager
        from draw_ import draw

        if localPlayer.name is invitee.name:
            newTeam = Team()
            newTeam.create(inviter)
            for member in members:
                newTeam.add(member)
            #更新玩家和team 数据 idea-->定义一个“更新”类,用@classmethod?
            invitee.team = newTeam
            inviter.team = newTeam
            playerManager.add(inviter)
            playerManager.add(invitee)
            teamManager.add(newTeam)
            #画出队伍成员
            draw.disDrawTeamMember()
            draw.drawTeamMember(newTeam)
        elif localPlayer.name is inviter.name:
            inviter.team = teamManager.get(inviter)
            inviter.team.add(invitee)
            #更新玩家和team 数据
            playerManager.add(inviter)
            teamManager.add(inviter.team)
            #画出队伍成员
            draw.disDrawTeamMember()
            draw.drawTeamMember(inviter.team)
        else:# 其他队员
            localPlayer.team.add(invitee)
            #更新玩家和team 数据
            playerManager.add(localPlayer)
            teamManager.add(localPlayer.team)
            #画出队伍成员
            draw.disDrawTeamMember()
            draw.drawTeamMember(localPlayer.team)
예제 #56
0
class TestWeapon(unittest.TestCase):
    """
    A test class for the Weapon module.
    """

    def setUp(self):
        """
        set up data used in the tests.
        setUp is called before each test function execution.
        """        
        self.turnManager = TurnManager()
        self.teams = []
        
        self.team = Team("Akatsuki")
        self.team.addSnails(1)
        self.teams.append(self.team)
        
        self.turnManager.setTeams(self.teams)
        
        self.snail = None
        for snail in self.team.sprites():
            self.snail = snail
        
        self.weapon = Weapon("Canon", 20)
        self.weapon.ammo = 5
        
        
    def testInitialized(self):
        """
        Test if init goes good
        """
        self.assertEqual(self.weapon.name, "Canon")
        self.assertEqual(self.weapon.power, 20)
        self.assertEqual(self.weapon.ammo, 5)
        
    def testShoot(self):
        self.weapon.shoot()
        self.assertEqual(self.weapon.ammo, 4)
예제 #57
0
 def addTeam(self, name, numberOfSnails, gravity_direction):
     """
     Add a team to the game
     @param name: The name of the team
     @param numberOfSnails: The amount of snails the team has
     @param gravity_direction: The gravity direction of the team
     """
     team = Team(name)
     team.setGravity(gravity_direction)
     team.addSnails(numberOfSnails)
     team.setTeamImage((gravity_direction+1))
     self.teams.append(team)
예제 #58
0
 def _clone_teams(self, current_generation, teams_to_clone, teams_population, programs_population, bid_profiles):
     for team, parent_profile in zip(teams_to_clone, bid_profiles):
         clone = Team(current_generation, team.programs)
         programs_population = clone.mutate(programs_population)
         child_profile = clone.generate_profile()
         while parent_profile == child_profile:
             programs_population = clone.mutate(programs_population)
             child_profile = clone.generate_profile()
         while not self._team_has_different_bid_profile_overall(child_profile, bid_profiles):
             programs_population = clone.mutate(programs_population)
             child_profile = clone.generate_profile()
         teams_population.append(clone)
     return teams_population, programs_population
예제 #59
0
 def setUp(self):
     """
     set up data used in the tests.
     setUp is called before each test function execution.
     """        
     self.turnManager = TurnManager()
     self.teams = []
     
     self.team = Team("Akatsuki")
     self.team.addSnails(1)
     self.teams.append(self.team)
     
     self.turnManager.setTeams(self.teams)
     
     self.snail = None
     for snail in self.team.sprites():
         self.snail = snail
     
     self.weapon = Weapon("Canon", 20)
     self.weapon.ammo = 5
예제 #60
0
    def __init__(self, games, schoolA, schoolB, playersA, playersB):
        self.games = games
        teamA = Team(schoolA)
        teamB = Team(schoolB)

        for player in playersA.split(","): #splitting the names by the comma (in the input-Kevin:1,) and adding it to the player list
            teamA.add_player(player)

        for player in playersB.split(","): #same thing with the opponent
            teamB.add_player(player)


        self.teamA = teamA
        self.teamB = teamB
        self.playersA = playersA
        self.playersB = playersB