Esempio n. 1
0
 def initLeague(self,leagueFile):
     if LeagueConsts.LeagueConstDB.select().count() == 0:
         lg = LeagueConsts.LeagueConstDB()
         league = League()
         league.loadTeams(leagueFile)
         lg.minRating = league.minRating
         lg.maxRating = league.maxRating
         lg.minRatingP = league.minPotential
         lg.maxRatingP = league.maxPotential
         lg.save()
Esempio n. 2
0
    def __init__(self, f, fout=None, attrs=None, averages=None):
        self.__data = pd.read_csv(f)
        self.__league = League(f)
        self.__attrs = None
        self.__averages = None
        self.__av = False

        if attrs is not None and averages is not None:
            self.__attrs = attrs
            self.__averages = averages
            self.__av = True
        self.__write_data_in_csv(fout)
	def post(self):
		user = users.get_current_user()
		if user:
			league = League()
			jsonBody = json.loads(self.request.body)
			league.name = jsonBody['name']
			print "name=", jsonBody['name']
			league.commissioner = user
			league.put()
			print "json=",json.dumps(league, cls=LeagueEncoder)
			self.response.write(json.dumps(league, cls=LeagueEncoder))
		else:
			self.redirect('/')
Esempio n. 4
0
    def get_league(self, league_id):
        r = requests.get(self._get_league_base_url + str(league_id))
        league_json = r.json()
        league_name = league_json["name"]

        # Retrieve the list of users
        users = self.get_users_in_league(league_id)

        # Retrieve the rosters from the server
        r = requests.get(self._get_league_base_url + str(league_id) +
                         "/rosters")
        teams = []
        for roster in r.json():
            # Build the player list for each team
            players = []
            for player in roster["players"]:
                players.append(self.get_player(player))

            # If there is no owner (because the team is abandoned) then they're not in
            # users, so we need to add a dummy owner to allow the code to continue
            #
            # TODO: This likely could be refined better than "unknown"
            try:
                owner = users[roster["owner_id"]]
            except KeyError:
                owner = User({"display_name": "unknown", "user_id": "unknown"})

            teams.append(Team(owner, players))

        return League(league_name, teams)
Esempio n. 5
0
def test_all_tied_input(monkeypatch, capsys):
    """Test output when all teams have equal points"""

    monkeypatch.setattr('sys.stdin', open('./input_files/ties.txt'))
    league = League()
    league.get_matches()
    league.fill_league()
    league.print_table()
    captured_stdout, captured_stderr = capsys.readouterr()
    assert captured_stdout.strip() == '1. FC Awesome, 2 pts\n1. FC Wackapodamus, 2 pts\n1. Grouches, 2 pts\n1. Lions, 2 pts\n1. Snakes, 2 pts\n1. Tarantulas, 2 pts'
Esempio n. 6
0
def test_another_league(monkeypatch, capsys):
    """Test output from a different set of league/game data"""

    monkeypatch.setattr('sys.stdin', open('./input_files/another-test.txt'))
    league = League()
    league.get_matches()
    league.fill_league()
    league.print_table()
    captured_stdout, captured_stderr = capsys.readouterr()
    assert captured_stdout.strip() == '1. Man Utd, 9 pts\n2. Arsenal, 3 pts\n3. Chelsea, 1 pts\n3. Man City, 1 pts'
Esempio n. 7
0
def test_empty_input(monkeypatch, capsys):
    """Test when receiving input from an empty file"""

    monkeypatch.setattr('sys.stdin', open('./input_files/empty.txt'))
    league = League()
    league.get_matches()
    league.fill_league()
    league.print_table()
    captured_stdout, captured_stderr = capsys.readouterr()
    assert captured_stdout.strip() == ''
	def get(self):
		user = users.get_current_user()
		if user:
			leagueQuery = League.query(League.commissioner == user)
			leagues = leagueQuery.fetch()
			print "json=",json.dumps(leagues, cls=LeagueEncoder)
			self.response.write(json.dumps(leagues, cls=LeagueEncoder))
		else:
			self.redirect('/')
Esempio n. 9
0
class TestLeague (unittest.TestCase) :

	teams = ['Team1', 'Team2', 'Team3', 'Team4', 'Team5', 'Team6', 'Team7', 'Team8']
	positions = {'qb': 1, 'rb': 2, 'wr': 3, 'te': 1, 'def': 1}

	def setUp(self):
		self.league = League(self.teams, self.positions)

	def test_init(self):
		self.assertEquals(self.teams, self.league.teams)
		self.assertEquals(self.positions, self.league.positions)

	def test_getNumPlayersToFill(self):
		self.assertEquals(8, self.league.getNumPlayersToFill('qb'))
		self.assertEquals(16, self.league.getNumPlayersToFill('rb'))
		self.assertEquals(24, self.league.getNumPlayersToFill('wr'))
		self.assertEquals(8, self.league.getNumPlayersToFill('te'))
		self.assertEquals(8, self.league.getNumPlayersToFill('def'))
 def get(self):
     user = users.get_current_user()
     if user:
         leagueQuery = League.query(League.commissioner == user)
         leagues = leagueQuery.fetch()
         print "json=", json.dumps(leagues, cls=LeagueEncoder)
         self.response.write(json.dumps(leagues, cls=LeagueEncoder))
     else:
         self.redirect('/')
Esempio n. 11
0
def test_sample_input(monkeypatch, capsys):
    """Test sample text given in challenge prompt"""

    monkeypatch.setattr('sys.stdin', open('./input_files/sample-input.txt'))
    league = League()
    league.get_matches()
    league.fill_league()
    league.print_table()
    captured_stdout, captured_stderr = capsys.readouterr()

    assert captured_stdout.strip() == '1. Tarantulas, 6 pts\n2. Lions, 5 pts\n3. FC Awesome, 1 pts\n3. Snakes, 1 pts\n5. Grouches, 0 pts'
Esempio n. 12
0
def Main():
    # set up our data

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

    # set up 6 teams
    teams = [
        Team('Milan'),
        Team('Juve'),
        Team('Inter'),
        Team('Roma'),
        Team('Napoli'),
        Team('Lazio')
    ]

    for team in teams:
        for player_num in range(11):
            # give them 11 starting players
            selected_player = random.choice(players)
            team.players.append(selected_player)
            # restriction for players, to play for one team only
            players.remove(selected_player)

    # we have a single league
    first_league = League('Calcio Serie A', teams, players)

    # create the manager
    manager = TeamManager(random.choice(teams), first_league)

    print('Season begins!')
    for i in range(10):
        manager.manage()
        first_league.play_round()
    print('Season ends!')
Esempio n. 13
0
    def get_competition_by_id(self, cid):
        ret = self.db.run_query('get_competition_by_id', (cid, ))[0]
        ctype = ret['type']

        if ctype == 'league':
            c = League(cid, ret['name'], ret['ownerId'], 'league')

        if ret['finished'] == 1:
            c.set_data('finished', True)

        c.set_data('current_stage', ret['current_stage'])
 def post(self):
     user = users.get_current_user()
     if user:
         league = League()
         jsonBody = json.loads(self.request.body)
         league.name = jsonBody['name']
         print "name=", jsonBody['name']
         league.commissioner = user
         league.put()
         print "json=", json.dumps(league, cls=LeagueEncoder)
         self.response.write(json.dumps(league, cls=LeagueEncoder))
     else:
         self.redirect('/')
Esempio n. 15
0
from sklearn.cross_validation import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import GaussianNB

from Data import Data
from League import League

if __name__ == '__main__':

    f = open('./output.csv', 'w')

    i = 2007
    while i <= 2017:
        print('./datasets/SP1' + str(i) + '.csv')
        l = League('./datasets/SP1' + str(i) + '.csv')

        if i == 2007:
            names = ','.join(l.get_attr_names()[0]) + ',' + ','.join(
                l.get_attr_names()[1])
            f.write(names + '\n')

        j = 0
        if j != 2017:
            n = 38
        else:
            n = 9

        while j < n:
            for team in l.get_jornada_full(j):
                team_as_string = (str(team[0]).strip('[]') + ', ' +
                                  str(team[1]).strip('[]')).replace(' ', '')
Esempio n. 16
0
from Game import Game
from Player import Player
import config

db = pymysql.connect(host=config.host,
                     port=config.port,
                     user=config.user,
                     database=config.database,
                     password=config.password)
cur = db.cursor(pymysql.cursors.DictCursor)

sql = "CALL get_batter_by_name('Kris', 'Bryant');"

cur.execute(sql)

league = League(db)
'''
bats = []
pitches = []
for row in cur:
    id = row['teamID']
    bat = Bat(id, db)
    bat.set_power_rating(league.b_hr, league.b_slg)
    bat.set_contact_rating(league.b_ba, league.b_obp, league.b_h)
    bat.set_scoring_rating(league.b_hr, league.b_rbi, league.b_r)
    bat.set_overall_rating()
    bats.append(bat)
    print(id + " Power: " + str(int(round(bat.power, 0))) + " Contact: " + str(int(round(bat.contact, 0)))
          + " Scoring: " + str(int(round(bat.scoring, 0))) + " Overall: " + str(int(round(bat.overall, 0))))

    pitch = Pitch(id, db)
Esempio n. 17
0
	def setUp(self):
		self.league = League(self.teams, self.positions)
class Controller(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "Command: "
        self.league = League()

    def do_create(self, line):
        """
        -- Create --
        Creates a new League
        To create new league, type "create league_name" then enter

        The roster for a starting league has 10 slots. In
        addition to adding characters to your roster, you
        may also select special perks to further
        customize your league. Most of the characters
        and perks will fill 1 to 3 slots. You are not
        required to fill all your slots, but players are
        encouraged to include 4 to 6 characters in their
        first leagues. Sample characters and leagues are
        included for those wanting to jump straight into
        the action.


        """
        self.league.start_create(line)

    def do_leader(self, line):
        """
        -- Leader (Level 4) --
        Each league must include one
        (and only one) Leader. Leaders are the central
        characters around which the rest of the league
        forms. These are extraordinary and legendary
        individuals, or at least legends-in-the-making.
        Leaders possess truly amazing skills and may
        select from the greatest range of abilities. Unlike
        all other characters, Leaders do not subtract
        from your roster slots - they're free!

        type "leader <attributes>" to create leader followed \
by the attributes and skills
        e.g leader Kim Jong-un, d10, 3d8, 3d10, 3d10, 2d8, 3d10, \
2d10, Sharp, Deadeye, Agile
        """
        self.league.add_leader(line)

    def do_sidekick(self, line):
        """
        -- SideKick (Level 3) --
        A sidekick is the stalwart
        companion and closest colleague of the league's
        leader. Sidekicks are exceptional characters,
        experts in their fields, and possess superior skills.
        Not every leader will have a sidekick, but if you
        choose to include one in your league, they fill 3
        roster slots. A league may not normally have
        more than one sidekick, unless they have the
        Company of Heroes perk.

        type "sidekick <attributes>" to create sidekick followed \
by the attributes and skills
        eg sidekick Mr. Wang, d8, 3d8, 3d8, 3d8, 2d6, 2d6, 2d6, Sharp, Deadeye
        """
        self.league.add_sidekick(line)

    def do_ally(self, line):
        """
        -- Ally (Level 2) --
        Allies have the training and
        experience to make them a valuable part of any
        league. Leagues may include many allies, and it is
        common for them to be the most numerous type
        of character in a league. Unlike followers, allies
        have the opportunity to roll Health and Recovery
        checks. An ally takes 2 roster slots.

        type "ally <attributes>" to create ally followed \
by the attributes and skills
        eg ally Rob, d6, 2d6, 2d6, 1d6, 1d6, 1d6, 1d6, animal
        """
        self.league.add_ally(line)

    def do_follower(self, line):
        """
        -- Follower (Level 1) --
        Although Followers are the
        least skilled characters, with leadership and luck
        they may prove to be quite useful. A follower fills
        only 1 slot on the league roster.

        type "follower <attributes>" to create follower followed \
by the attributes and skills
        eg follower Wolfeschlegelsteinhausenbergerdorff, d6*, 1d6, 1d6, 1d6, \
1d6, 1d6, 1d6, animal
        """
        self.league.add_follower(line)

    def do_exit(self, line):
        """
        -- Exit --
        Exits the game
        """
        return True

    def do_save(self, name):
        """
        -- Save --
        Saves the game.

        type "save <file_name>"
        """
        try:
            if name == "":
                raise InvalidInput("Please enter a name of the "
                                   "file. eg. save <file_name>")
            data = [self.league]
            with open(name + ".pickle", "wb") as file:
                pickle.dump(data, file)
            print("File has been saved as " + name + ".pickle")
        except InvalidInput as err:
            print(err)

    def do_load(self, f_name):
        """
        -- Load --
        Load a League

        type "load <filename>"
        """
        try:
            if f_name == "":
                raise InvalidInput("Please enter the name of the "
                                   "file. eg. load <file_name>")
            if os.path.exists(f_name + ".pickle") is False:
                raise InvalidInput("The file \"" + f_name +
                                   "\" does not exist")
            with open(f_name + ".pickle", "rb") as file:
                data = pickle.load(file)
            self.league = data[0]
            print("File loaded from " + f_name +
                  ".pickle...")
        except InvalidInput as err:
            print(err)

    def do_display(self, line):
        """
        -- Display --
        displays the League

        type "display" to display the league
        """
        print(str(self.league.leader))
        print("")
        if len(self.league.sidekick_members) > 0:
            for key, value in self.league.sidekick_members.items():
                print(value)
        if len(self.league.ally_members) > 0:
            for key, value in self.league.ally_members.items():
                print(value)
        if len(self.league.follower_members) > 0:
            for key, value in self.league.follower_members.items():
                print(value)

    def do_restart(self, line):
        """
        -- Restart --
        Reinitialize the League

        type "restart" to start over again
        """
        self.league.leader = Character.Leader
        self.league.name = ""
        self.league.limit = 10
        self.league.league_slot = 0
        self.league.sidekick_count = 1
        self.league.ally_count = 1
        self.league.follower_count = 1
        self.league.sidekick_members = {}
        self.league.ally_members = {}
        self.league.follower_members = {}
        self.league.has_leader = False
        self.league.league_status = ""
        self.league.is_creating_league = False
        self.league.league_information()

    def preloop(self):
        """
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, "\
"3d10, 2d10, Sharp, Deadeye, Agile")
        'Invalid Action: You must enter the name of the League first \
before you can start creating characters!!!(type create <league_name>)'
        >>> league.add_sidekick("James, d10, 3d8, 3d10, 3d10, 2d8, "\
"3d10, 2d10, Sharp, Deadeye, Agile")
        'Invalid Action: You must enter the name of the League first \
before you can start creating characters!!!(type create <league_name>)'
        >>> league.add_ally("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Deadeye, Agile")
        'Invalid Action: You must enter the name of the League first \
before you can start creating characters!!!(type create <league_name>)'
        >>> league.add_follower("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Deadeye, Agile")
        'Invalid Action: You must enter the name of the League first \
before you can start creating characters!!!(type create <league_name>)'
        >>> league.start_create("Alpha")
        ------------------------------ Create League -----------------\
-------------
        Type <character_role> followed by the attributes and skills \
using the format and order below:
        name, health, brawl, shoot, dodge, might, finesse, cunning, \
1st_Skill, 2nd_Skill, 3rd_Skill
        (eg leader Kim Jong-un, d10, 3d8, 3d10, 3d10, 2d8, 3d10, \
2d10, Sharp, Deadeye, Agile)
        Your League's name, is Alpha
        <BLANKLINE>
        >>> league.add_sidekick("James, d8, 3d8, 3d8, 3d8, 2d6, "\
"2d6, 2d6, Sharp, Deadeye")
        'Invalid Action: Please create a leader first, you have \
not created a leader yet!!!'
        >>> league.add_ally("James, d6, 2d6, 2d6, 1d6, 1d6, 1d6, "\
"1d6, animal")
        'Invalid Action: Please create a leader first, you have not \
created a leader yet!!!'
        >>> league.add_follower("James, d6*, 1d6, 1d6, 1d6, 1d6, "\
"1d6, 1d6, animal")
        'Invalid Action: Please create a leader first, you have not \
created a leader yet!!!'
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Agile")
        Please enter 3 abilities, you entered 2
        'Invalid Input: leader abilities'
        <BLANKLINE>
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, "\
"3d10, 2d10, Sharp, Agile, Animal, Clever")
        Please enter 3 abilities, you entered 4
        'Invalid Input: leader abilities'
        <BLANKLINE>
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Agile, Agile")
        'Invalid Action: Please no duplicates "Agile"'
        <BLANKLINE>
        >>> league.add_leader("James, d8, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Deadeye, Agile")
        'Invalid Input: Leader health must be d10 not d8'
        Failed to create leader, Please try again
        <BLANKLINE>
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Deadeye, Agile")
        You have 10 slots left to use, You have a leader
        <BLANKLINE>
        You have successfully added a leader
        >>> league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, "\
"2d10, Sharp, Deadeye, Agile")
        'Invalid Action: You already created a leader named "James", \
please create other character'
        >>> league.add_sidekick("James, d8, 3d8, 3d8, 3d8, 2d6, 2d6, "\
"2d6, Sharp")
        Please enter 2 abilities, you entered 1
        'Invalid Input: sidekick abilities'
        <BLANKLINE>
        >>> league.add_sidekick("James, d8, 3d8, 3d8, 3d8, 2d6, 2d6, "\
"2d6, Sharp, Agile, Animal")
        Please enter 2 abilities, you entered 3
        'Invalid Input: sidekick abilities'
        <BLANKLINE>
        >>> league.add_sidekick("James, d8, 3d8, 3d8, 3d8, 2d6, "\
"2d6, 2d6")
        You entered nothing!!!
        'Invalid Input: sidekick abilities'
        <BLANKLINE>
        >>> league.add_follower("James, d6*, 1d6, 1d6, 1d6, 1d6, "\
"1d6, 1d6")
        You entered nothing!!!
        'Invalid Input: follower abilities'
        <BLANKLINE>
        """
        self.league.league_information()

    def postloop(self):
        print("Thank you for for playing Pulp Alley")
Esempio n. 19
0
"""
league_builder.py
@Author - Kellen Rice
Taking in a text file, or plain text from stdin create a soccer league
table and print the results.
v. 0.0.1
"""

from League import League

league = League()
league.get_matches()
league.fill_league()
league.print_table()
Esempio n. 20
0
    def checkInit(self):
        #if player table does not exist, create it
#        Stats.create_table(True)
        Player.create_table(True)
        League.create_table(True)
Esempio n. 21
0
    def initFromString(self, dataString, headerDict, constants):
        dataString = dataString.replace('-','0')
        fieldArray = dataString.split(',')
        self.Position = fieldArray[headerDict['POS']]
        theName = unicode(fieldArray[headerDict['Name']], errors="ignore")
        self.Name = theName.replace('0','-')
        self.Team = unicode(fieldArray[headerDict['TM']], errors="ignore").encode("ascii", "ignore")
        self.Level = fieldArray[headerDict['Lev']]
        self.DOB = fieldArray[headerDict['DOB']]
        self.Age=fieldArray[headerDict['Age']]
        self.Bats = fieldArray[headerDict['B']]
        self.Throws = fieldArray[headerDict['T']]
        self.Overall = fieldArray[headerDict['OVR']].split()[0]
        self.Potential = fieldArray[headerDict['POT']].split()[0]
        self.Leadership = self.personalityToNumber(fieldArray[headerDict['LEA']])
        self.WorkEthic = self.personalityToNumber(fieldArray[headerDict['WE']])
        self.Intelligence = self.personalityToNumber(fieldArray[headerDict['INT']])
        self.CON = int(fieldArray[headerDict['CON']])
        self.GAP = int(fieldArray[headerDict['GAP']])
        self.POW = int(fieldArray[headerDict['POW']])
        self.EYE = int(fieldArray[headerDict['EYE']])
        self.Ks = int(fieldArray[headerDict['Ks']])
        self.CONvL = fieldArray[headerDict['CON vL']]
        self.GAPvL = fieldArray[headerDict['GAP vL']]
        self.POWvL = fieldArray[headerDict['POW vL']]
        self.EYEvL = fieldArray[headerDict['EYE vL']]
        self.KvL = fieldArray[headerDict['K vL']]
        self.CONvR = fieldArray[headerDict['CON vR']]
        self.GAPvR = fieldArray[headerDict['GAP vR']]
        self.POWvR = fieldArray[headerDict['POW vR']]
        self.EYEvR = fieldArray[headerDict['EYE vR']]
        self.KvR = fieldArray[headerDict['K vR']]
        self.CONP = fieldArray[headerDict['CON P']]
        self.GAPP = fieldArray[headerDict['GAP P']]
        self.POWP = fieldArray[headerDict['POW P']]
        self.EYEP = fieldArray[headerDict['EYE P']]
        self.KP = fieldArray[headerDict['K P']]
        self.STU = fieldArray[headerDict['STU']]
        self.MOV = fieldArray[headerDict['MOV']]
        self.CONT = fieldArray[headerDict['CONa']]
        self.STUvL = fieldArray[headerDict['STU vL']]
        self.MOVvL = fieldArray[headerDict['MOV vL']]
        self.CONTvL = fieldArray[headerDict['CON vLa']]
        self.STUvR = fieldArray[headerDict['STU vR']]
        self.MOVvR = fieldArray[headerDict['MOV vR']]
        self.CONTvR = fieldArray[headerDict['CON vRa']]
        self.STUP = fieldArray[headerDict['STU P']]
        self.MOVP = fieldArray[headerDict['MOV P']]
        self.CONTP = fieldArray[headerDict['CON Pa']]
        self.STM = fieldArray[headerDict['STM']]
        self.GF = fieldArray[headerDict['G/F']]
        self.IFRNG = fieldArray[headerDict['IF RNG']]
        self.IFARM = fieldArray[headerDict['IF ARM']]
        self.TDP = fieldArray[headerDict['TDP']]
        self.IFERR = fieldArray[headerDict['IF ERR']]
        self.OFRNG = fieldArray[headerDict['OF RNG']]
        self.OFARM = fieldArray[headerDict['OF ARM']]
        self.OFERR = fieldArray[headerDict['OF ERR']]
        self.CARM = fieldArray[headerDict['C ARM']]
        self.CABI = fieldArray[headerDict['C ABI']]
        self.P = fieldArray[headerDict['P']]
        self.C = fieldArray[headerDict['C']]
        self.B1 = fieldArray[headerDict['1B']]
        self.B2 = fieldArray[headerDict['2B']]
        self.B3 = fieldArray[headerDict['3B']]
        self.SS = fieldArray[headerDict['SS']]
        self.LF = fieldArray[headerDict['LF']]
        self.CF = fieldArray[headerDict['CF']]
        self.RF = fieldArray[headerDict['RF']]
        self.SPE = int(fieldArray[headerDict['SPE']])
        self.STE = fieldArray[headerDict['STE']]
        self.RUN = fieldArray[headerDict['RUN']]

        self.calcStats(constants)

        fullTeam = unicode(fieldArray[headerDict['TM']], errors="ignore").encode("ascii", "ignore")

        if (self.Team and self.Team != '0' and self.Level):
            franchise = League.findFranchise(self.Team, self.Level, fullTeam)
            if franchise:
                self.franchise = franchise
            else:
                print "missing franchse: " + self.Team + "," + self.Level
                self.franchise = self.Team
        else:
            pass
Esempio n. 22
0
File: match.py Progetto: euand/elo
                        dest="league",
                        required=False,
                        default=DEFAULT_LEAGUE)

    match_info = vars(parser.parse_args())
    match_info['time'] = datetime.now().strftime("%Y-%m-%d %H:%M")
    match_info['home_player'] = match_info['home_player'].lower()
    match_info['away_player'] = match_info['away_player'].lower()

    league_path = LEAGUE_PATH.format(match_info['league'])

    if not path.exists(league_path):
        mkdir(league_path)

    match_path = path.join(league_path, 'matches.json')
    player_scores_path = path.join(league_path, 'player_scores.json')

    with open(match_path, 'a+') as f:
        f.write(json.dumps(match_info) + '\n')

    league = League()
    if path.exists(player_scores_path):
        league.load_json(player_scores_path)
    league.match(match_info)
    league.save(player_scores_path)

    print('Match recorded: \n\t{} vs. {} \n\t{}-{} \n\t{}'.format(
        match_info['home_player'], match_info['away_player'],
        match_info['home_score'], match_info['away_score'],
        match_info['league']))
Esempio n. 23
0
from config.foos_config import DEFAULT_LEAGUE_INPUT_FILES
from config.webhook_config import NOTIFIERS

import json

from League import League

leagues = {}
league_notifiers = {}

for league_name in DEFAULT_LEAGUE_INPUT_FILES:
    try:
        with open(DEFAULT_LEAGUE_INPUT_FILES[league_name]['input_file']) as original_results:
            # { league_name: LeagueObject }
            leagues.setdefault(league_name, League.from_results_csv(original_results, static_league=DEFAULT_LEAGUE_INPUT_FILES[league_name]['static']))
    except IOError:
        pass

for notifier in NOTIFIERS:
    for league_name in leagues:
        if league_name in notifier['leagues']:
            league_notifiers.setdefault(league_name, [])
            league_notifiers[league_name].append((notifier['game_notifier'], notifier['league_notifier']))

# This would be a little more elegant with a database at this point but MVP!!!
def save_league(league_name):
    leagues[league_name].export_to_csv(elos=False, file_name='results/' + league_name + ".csv")
    # pass

class LeagueListHandler(tornado.web.RequestHandler):
 def __init__(self):
     cmd.Cmd.__init__(self)
     self.prompt = "Command: "
     self.league = League()
Esempio n. 25
0
class Data(object):
    def __init__(self, f, fout=None, attrs=None, averages=None):
        self.__data = pd.read_csv(f)
        self.__league = League(f)
        self.__attrs = None
        self.__averages = None
        self.__av = False

        if attrs is not None and averages is not None:
            self.__attrs = attrs
            self.__averages = averages
            self.__av = True
        self.__write_data_in_csv(fout)

    def __write_data_in_csv(self, fout):
        teams = []
        matches = {}

        for index, row in self.__data.iterrows():
            teams.append(row['HomeTeam'])

        teams = sorted(set(teams))

        for team in teams:
            matches[team] = self.__data[(self.__data.HomeTeam == team)][['Div', 'Date', 'HomeTeam', 'AwayTeam', 'FTR']] #  | (self.__data.AwayTeam == team)

        columns_dt = ['Div', 'Date', 'HomeTeam', 'AwayTeam', 'FTR']

        if not self.__av:
            columns = self.__league.get_match_day(0).columns.values.tolist()
        else:
            columns = self.__league.get_match_day_with_weighted_average(n=0, attrs=self.__attrs, averages=self.__averages).columns.values.tolist()

        home_columns = []
        away_columns = []
        print (columns)
        for column in columns:
            home_columns.append('HT' + column)
            away_columns.append('AT' + column)

        columns_dt = columns_dt + home_columns
        columns_dt = columns_dt + away_columns

        new_df = pd.DataFrame(columns=columns_dt)

        j = 0
        for team in teams:
            i = 0
            while i < len(matches[team]):

                if not self.__av:
                    if i == 0:
                        aux = self.__league.get_match_day(0).loc[:,self.__league.get_match_day(0).columns != 'Team']
                        match_day = self.__league.get_match_day(0)
                        aux *= 0
                        match_day.loc[:,self.__league.get_match_day(0).columns != 'Team'] = aux
                    else:
                        match_day = self.__league.get_match_day(i-1)
                else:
                    if i == 0:
                        aux = self.__league.get_match_day_with_weighted_average(n=0, attrs=self.__attrs, averages=self.__averages).loc[:,self.__league.get_match_day_with_weighted_average(n=0, attrs=self.__attrs, averages=self.__averages).columns != 'Team']
                        match_day = self.__league.get_match_day_with_weighted_average(n=0, attrs=self.__attrs, averages=self.__averages)
                        aux *= 0
                        match_day.loc[:,self.__league.get_match_day_with_weighted_average(n=0, attrs=self.__attrs, averages=self.__averages).columns != 'Team'] = aux
                    else:
                        match_day = self.__league.get_match_day_with_weighted_average(n=i-1, attrs=self.__attrs, averages=self.__averages)

                new_columns = []
                for column in columns:
                    new_columns.append('HT' + column)

                match_day.columns = new_columns
                home_team_data = match_day[match_day.HTTeam == matches[team].HomeTeam.values[i]]
            
                result = pd.merge(matches[team].iloc[[i]], home_team_data, left_on='HomeTeam', right_on='HTTeam')

                new_columns = []
                for column in columns:
                    new_columns.append('AT' + column)

                match_day.columns = new_columns
                away_team_data = match_day[match_day.ATTeam == matches[team].AwayTeam.values[i]]

                result = pd.merge(result, away_team_data, left_on='AwayTeam', right_on='ATTeam')

                new_df.loc[j] = result.loc[0]
                j += 1
                i += 1
        
        new_df.to_csv(fout, index=False)
Esempio n. 26
0
players += [
    Player("Milo", [
        "Quinn Koch", "William Fernholz", "Susana", "Milo Moses",
        "Beck Tompkins", "Kai Kumar", "Nick"
    ])
]

#Files for the data
files = []
files += [["Ed_Sias_Frosh-Soph_Boys", False]]
files += [["Ed_Sias_Frosh-Soph_Girls", False]]
files += [["Ed_Sias_Varsity_Girls", True]]
files += [["Ed_Sias_Varsity_Boys", True]]
files += [["Ed_Sias_Frosh_Boys", False]]

#Declaring league
L = League(players)

#Adding races to league
for file in files:
    race = Race(file[0], file[1])
    L.scoreAdd(race)

#Printing points
print(L)

#Graphing
L.graph(
    ["Ed_Sias_Frosh-Soph_Boys", "Ed_Sias_Varsity_Boys", "Ed_Sias_Frosh_Boys"])
class MainTest(unittest.TestCase):
    global league
    league = League()

    def setUp(self):
        initialized()

    def create_leader(self):
        league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, " +
                          "2d10, Sharp, Deadeye, Agile")

    def tearDown(self):
        pass

    def test_01_create_league_no_name(self):
        """
        Try to create league with no name
        error raised "Please enter the name, you entered nothing!!"
        """
        self.assertRaises(InvalidInput, league.start_create(""))

    def test_02_create_character_before_league(self):
        """
        Try to create character before league
        error raised "You must enter the name of the League first \
        before you can start creating characters!!!(type create <league_name>)"
        """
        self.assertRaises(InvalidAction,
                          league.add_leader("James, d10, 3d8, 3d10, 3d10, " +
                                            "2d8, 3d10, 2d10"))
        self.assertRaises(InvalidAction,
                          league.add_sidekick("James, d10, 3d8, 3d10, 3d10, " +
                                              "2d8, 3d10, 2d10"))
        self.assertRaises(InvalidAction,
                          league.add_ally("James, d10, 3d8, 3d10, 3d10, " +
                                          "2d8, 3d10, 2d10"))
        self.assertRaises(InvalidAction,
                          league.add_follower("James, d10, 3d8, 3d10, 3d10, " +
                                              "2d8, 3d10, 2d10"))

    def test_03_create_other_character_before_leader(self):
        """
        Try to create other character before league
        error raised "Please create a leader first, you have \
        not created a leader yet!!!"
        """
        league.start_create("Alpha")
        self.assertRaises(InvalidAction,
                          league.add_sidekick("James, d10, 3d8, " +
                                              "3d10, 3d10, 2d8, 3d10, 2d10"))
        self.assertRaises(InvalidAction,
                          league.add_ally("James, d10, 3d8, 3d10, " +
                                          "3d10, 2d8, 3d10, 2d10"))
        self.assertRaises(InvalidAction,
                          league.add_follower("James, d10, 3d8, 3d10, " +
                                              "3d10, 2d8, 3d10, 2d10"))

    def test_07_create_character_with_missing_skills(self):
        """
        try to create character with missing skills
        error raised Please enter 3 abilities, you entered 1
            'Invalid Input: Please Enter a valid input for abilities'

            Please enter 3 abilities, you entered 2
            'Invalid Input: Please Enter a valid input for abilities'
        """
        league.start_create("Alpha")
        self.assertRaises(InvalidInput,
                          league.add_leader("James, d10, 3d8, 3d10, 3d10, " +
                                            "2d8, 3d10, 2d10, Sharp"))
        self.assertRaises(InvalidInput,
                          league.add_leader("James, d10, 3d8, 3d10, 3d10, " +
                                            "2d8, 3d10, 2d10, Sharp, Deadeye"))

    def test_08_invalid_dice_input(self):
        """
        invalid dice
        """
        word = "Sharp, Deadeye, Agile"
        league.start_create("Alpha")
        self.assertRaises(InvalidInput,
                          league.add_leader("leader James, ddd12, 3d8, " +
                                            "3d10, " +
                                            "3d10, 2d8, 3d10, 2d10, " +
                                            word))
        self.assertRaises(InvalidInput,
                          league.add_leader("leader James, d10, sdf12, " +
                                            "3d10, " +
                                            "3d10, 2d8, 3d10, 2d10, " +
                                            word))
        self.assertRaises(InvalidInput,
                          league.add_leader("leader James, d10, 3d8, 3d10, " +
                                            "3d10, " +
                                            "fdfkdsk34, 3d10, 2d10, " +
                                            word))

    def test_09_invalid_skill_input(self):
        """
        invalid skills
        """
        league.start_create("Alpha")
        word = "James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, 2d10, "
        self.assertRaises(InvalidInput,
                          league.add_leader(word + "sadf, Deadeye, Agile"))
        self.assertRaises(InvalidInput,
                          league.add_leader(word + "Sharp, fd4g4, Agile"))
        self.assertRaises(InvalidInput,
                          league.add_leader(word + "Sharp, Deadeye, sdf"))

    def test_10_skill_duplicates(self):
        league.start_create("Alpha")
        self.assertRaises(InvalidInput,
                          league.add_leader("James, d10, 3d8, 3d10, 3d10, " +
                                            "2d8, 3d10, 2d10, Sharp, " +
                                            "Agile, Agile"))

    def test_11_skill_excess_skills(self):
        league.start_create("Alpha")
        self.assertRaises(InvalidInput,
                          league.add_leader("James, d10, 3d8, 3d10, 3d10, " +
                                            "2d8, 3d10, 2d10, Sharp, "
                                            "Deadeye, Agile, Animal"))

    def test_12_set_level_3_2_skills_to_follower(self):
        league.start_create("Alpha")
        league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, " +
                          "3d10, 2d10, Sharp, Deadeye, Agile")
        self.assertRaises(InvalidInput,
                          league.add_follower("James, d6*, 1d6, " +
                                              "1d6, 1d6, 1d6, 1d6, 1d6, " +
                                              "Hardened Veteran"))

    def test_13_set_dice_rule(self):
        """
        try and create a leader without following the dice rules
        """
        self.assertRaises(InvalidInput,
                          league.add_leader("James, d10, 2d10, 3d10, " +
                                            "3d10, 2d8, 3d10, 2d10, " +
                                            "Sharp, Deadeye, Agile"))

    def test_14_try_create_two_leaders(self):

        # 'Invalid Action: You already created a leader named \
        # "James", please create other character'

        league.start_create("Alpha")
        league.add_leader("James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, " +
                          "2d10, Sharp, Deadeye, Agile")
        self.assertRaises(InvalidAction,
                          league.add_leader("James, d10, 3d8, 3d10, " +
                                            "3d10, 2d8, 3d10, 2d10, Sharp, " +
                                            "Deadeye, Agile"))

    def create_character_with_missing_attributes(self, role, add_char, *args):
        league.start_create("Alpha")
        if role != "leader":
            self.create_leader()
        word = ""
        count = 0
        for x in args:
            if count == 0:
                self.assertRaises(InvalidInput, add_char(word))
            else:
                word += ", " + x
                self.assertRaises(InvalidInput, add_char(word))
            count += 1

    def test_15_create_leader_with_missing_attributes(self):
        self.create_character_with_missing_attributes("leader",
                                                      league.add_leader,
                                                      "James", "d8", "3d8",
                                                      "3d8",
                                                      "3d8", "2d8", "2d8")

    def test_16_create_sidekick_with_missing_attributes(self):
        self.create_character_with_missing_attributes("sidekick",
                                                      league.add_sidekick,
                                                      "James",
                                                      "d8", "3d8", "3d8",
                                                      "3d8",
                                                      "2d8", "2d8")

    def test_17_create_ally_with_missing_attributes(self):
        self.create_character_with_missing_attributes("ally",
                                                      league.add_ally,
                                                      "James",
                                                      "d8", "3d8", "3d8",
                                                      "3d8",
                                                      "2d8", "2d8")

    def test_18_create_follower_with_missing_attributes(self):
        self.create_character_with_missing_attributes("ally",
                                                      league.add_follower,
                                                      "James",
                                                      "d8", "3d8", "3d8",
                                                      "3d8",
                                                      "2d8", "2d8")

    def bonus_die(self, role, add_char, attr):
        league.start_create("Alpha")
        if role != "leader":
            self.create_leader()
        add_char(attr)

    def test_19_bonus_die_leader(self):
        word = "James, d10, 3d8, 3d10, 3d10, 2d8, 3d10, 2d10, "
        self.bonus_die("leader", league.add_leader, word + "Agile, Fierce,"
                                                           "Clever")
        self.assertTrue(league.leader.dodge == "4d10")
        self.assertTrue(league.leader.brawl == "4d8")
        self.assertTrue(league.leader.cunning == "3d10")
        initialized()
        self.bonus_die("leader", league.add_leader, word + "Animal, Mighty,"
                                                           "Savvy")
        self.assertTrue(league.leader.shoot == "--")
        self.assertTrue(league.leader.might == "3d8")
        self.assertTrue(league.leader.finesse == "5d10")
        initialized()
        self.bonus_die("leader", league.add_leader, word + "marksman,"
                                                           "Fierce, Clever")
        self.assertTrue(league.leader.shoot == "4d10")

    def test_20_bonus_die_sidekick(self):
        word = "James, d8, 3d8, 3d8, 3d8, 2d6, 2d6, 2d6, "
        self.bonus_die("sidekick", league.add_sidekick, word + "Agile,"
                                                               "Animal")
        self.assertTrue(league.sidekick_members["sidekick1"].shoot == "--")
        self.assertTrue(league.sidekick_members["sidekick1"].dodge == "5d8")
        self.assertTrue(league.sidekick_members["sidekick1"].finesse == "3d6")
        initialized()
        self.bonus_die("sidekick", league.add_sidekick, word + "Clever,"
                                                               "Fierce")
        self.assertTrue(league.sidekick_members["sidekick1"].cunning == "3d6")
        self.assertTrue(league.sidekick_members["sidekick1"].brawl == "4d8")
        initialized()
        self.bonus_die("sidekick", league.add_sidekick, word + "marksman,"
                                                               "mighty")
        self.assertTrue(league.sidekick_members["sidekick1"].shoot == "4d8")
        self.assertTrue(league.sidekick_members["sidekick1"].might == "3d6")
        initialized()
        self.bonus_die("sidekick", league.add_sidekick, word + "savvy, mighty")
        self.assertTrue(league.sidekick_members["sidekick1"].finesse == "3d6")

    def test_21_bonus_die_ally(self):
        word = "James, d6, 2d6, 2d6, 1d6, 1d6, 1d6, 1d6, "
        for x in Ability.Ability.level1:
            self.bonus_die("sidekick", league.add_ally, word + str(x))
            if x == "Animal":
                self.assertTrue(league.ally_members["ally1"].shoot == "--")
            elif x == "Agile":
                self.assertTrue(league.ally_members["ally1"].dodge == "2d6")
            elif x == "Clever":
                self.assertTrue(league.ally_members["ally1"].cunning == "2d6")
            elif x == "Fierce":
                self.assertTrue(league.ally_members["ally1"].brawl == "3d6")
            elif x == "Marksman":
                self.assertTrue(league.ally_members["ally1"].shoot == "3d6")
            elif x == "Mighty":
                self.assertTrue(league.ally_members["ally1"].might == "2d6")
            elif x == "Savvy":
                self.assertTrue(league.ally_members["ally1"].finesse == "2d6")
            initialized()

    def test_22_bonus_die_follower(self):
        word = "James, d6*, 1d6, 1d6, 1d6, 1d6, 1d6, 1d6, "
        for x in Ability.Ability.level1:
            self.bonus_die("follower", league.add_follower, word + str(x))
            if x == "Animal":
                self.assertTrue(league.follower_members["follower1"].shoot ==
                                "--")
            elif x == "Agile":
                self.assertTrue(league.follower_members["follower1"].dodge ==
                                "2d6")
            elif x == "Clever":
                self.assertTrue(league.follower_members["follower1"].cunning ==
                                "2d6")
            elif x == "Fierce":
                self.assertTrue(league.follower_members["follower1"].brawl ==
                                "2d6")
            elif x == "Marksman":
                self.assertTrue(league.follower_members["follower1"].shoot ==
                                "2d6")
            elif x == "Mighty":
                self.assertTrue(league.follower_members["follower1"].might ==
                                "2d6")
            elif x == "Savvy":
                self.assertTrue(league.follower_members["follower1"].finesse ==
                                "2d6")
            initialized()

    def test_23load(self):
        pass
        # happy day
        Controller.do_load(league, "avengers")
        self.assertEqual(league.league.leader.name, "James")
        self.assertEqual(league.league.leader.health, "d10")
        self.assertEqual(league.league.leader.brawl, "3d8")
        self.assertEqual(league.league.leader.shoot, "3d10")
        self.assertEqual(league.league.leader.dodge, "4d10")
        self.assertEqual(league.league.leader.might, "2d8")
        self.assertEqual(league.league.leader.finesse, "3d10")

        #bad day
        self.assertRaises(InvalidInput, Controller.do_load(league,
                                                           "asd$%^&*("))
        self.assertRaises(InvalidInput, Controller.do_load(league, ""))

        #alternative, load it again
        Controller.do_load(league, "avengers")
        self.assertEqual(str(league.league.leader),
                         "+-------+------+-------+------+------+------+------+--------+--------+\n"
                         "|       |name  |health |brawl |shoot |dodge |might |finesse |cunning |\n"
                         "+-------+------+-------+------+------+------+------+--------+--------+\n"
                         "|Leader |James |d10    |3d8   |3d10  |4d10  |2d8   |3d10    |2d10    |\n"
                         "+-------+------+-------+------+------+------+------+--------+--------+\n"
                         "Sharp: Once per turn, this character may re-roll one Shoot or Finesse die.\n"
                         "Deadeye: This character is not limited to shooting the closest enemy\n"
                         "Agile: This character's Dodge is increased by +1 die.")