예제 #1
0
 def _player_list_to_lineup(self, players):
     player_dict = dict()
     for (player, slot) in players:
         cur_list = player_dict.get(slot, list())
         cur_list.append(player)
         player_dict[slot] = cur_list
     return Lineup(player_dict, self._slot_enum())
    def _cumulative_stats(self, lineup: Lineup):
        """
        Calculates an approximation of the final statistics of this lineup, assuming
        ideal management (setting lineups daily, etc.)
        :param Lineup lineup: the lineup to examine and use to calculate stats
        :return Stats: the accumulated, year-end total stats
        """
        total_stats = Stats({}, BaseballStat)
        for p in lineup.starters():
            total_stats += self._get_projection(p.name) or Stats({},
                                                                 BaseballStat)
        for p in lineup.benched():
            total_stats += self._get_projection(p.name) or Stats(
                {}, BaseballStat) * self.likelihood(p, lineup)

        return total_stats
예제 #3
0
def opt(opt_p, budget, desired, remove, n=None):
    if n:
        squad = Opt.transfer_simulation(opt_p, processed_data, n, budget,
                                        desired, remove)
    else:
        squad = Opt.wildcard_simulation(opt_p, processed_data, budget, desired,
                                        remove)

    if squad.prob.status == 1:
        player, subs = squad.extract_subs()
        old, new = squad.calculate_improvement()
        print('\n\nSubstitution simulation complete (', opt_p, '),', sep='')
        print('previous ',
              opt_p,
              ' - ',
              round(old, 1),
              '\n',
              'new ',
              opt_p,
              ' - ',
              round(new, 1),
              sep='')
        print('That\'s an improvement of -', round(new - old, 1))
        print('\nOptimal subs:')
        for p, s in zip(player, subs):
            print(p['web_name'], '>', s['web_name'])
        print('\nBest team/formation is as follows:')
        Lineup(squad.squad, param=opt_p).print_lineup()
    else:
        print(
            'Unable to find solution with specified parameters. Simulation status code:',
            squad.prob.status)
class Test(unittest.TestCase):
    rizzo = Player("Anthony Rizzo", None, None, 123, {BaseballSlot.FIRST},
                   None)
    goldschmidt = Player("Paul Goldschmidt", None, None, 456,
                         {BaseballSlot.FIRST}, None)

    empty_lineup = Lineup(dict(), BaseballSlot)
    basic_node = LineupSearchNode(empty_lineup, [rizzo], {BaseballSlot.FIRST})
    simple_settings = LineupSettings({BaseballSlot.FIRST: 1})

    two_firsts_left_node = LineupSearchNode(empty_lineup, [rizzo, goldschmidt],
                                            {BaseballSlot.FIRST})

    def test_successors_one_player(self):
        result = self.basic_node.successors(self.simple_settings)
        self.assertEqual(len(result), 1)
        successor = result[0]
        self.assertEqual(len(successor.players_left), 0)
        self.assertEqual(successor.lineup.starters(), {self.rizzo})

    def test_successors_two_players(self):
        result = self.two_firsts_left_node.successors(self.simple_settings)
        self.assertEqual(len(result), 2)
        s0 = result[0]
        s0rem = s0.players_left[0]
        s0first = s0.lineup.player_dict.get(BaseballSlot.FIRST)[0]
        s1 = result[1]
        s1rem = s1.players_left[0]
        s1first = s1.lineup.player_dict.get(BaseballSlot.FIRST)[0]

        self.assertEqual({s0rem, s1rem}, {self.rizzo, self.goldschmidt})
        self.assertNotEqual(s0rem, s0first)
        self.assertNotEqual(s1rem, s1first)
        self.assertEqual(s0rem, s1first)
예제 #5
0
 def player_list_to_lineup(players):
     player_dict = dict()
     for (player, slot) in players:
         cur_list = player_dict.get(slot, list())
         cur_list.append(player)
         player_dict[slot] = cur_list
     return Lineup(player_dict)
예제 #6
0
    def test_transitions_single_swap(self):
        carpenter_first_dict = self.empty_lineup_dict.copy()
        carpenter_first_dict[BaseballSlot.FIRST] = [PlayerTest.carpenter]
        cf_lineup = Lineup(carpenter_first_dict, BaseballSlot)

        carpenter_corner_inf_dict = self.empty_lineup_dict.copy()
        carpenter_corner_inf_dict[BaseballSlot.CORNER_INFIELD] = [
            PlayerTest.carpenter
        ]
        cci_lineup = Lineup(carpenter_corner_inf_dict, BaseballSlot)

        transitions = cf_lineup.transitions(cci_lineup)

        self.assertEqual(len(transitions), 1)
        self.assertTrue(
            LineupTransition(PlayerTest.carpenter, BaseballSlot.FIRST,
                             BaseballSlot.CORNER_INFIELD) in transitions)
예제 #7
0
    def test_transitions_swap_two_players(self):
        l1_dict = self.empty_lineup_dict.copy()
        l1_dict[BaseballSlot.BENCH] = [PlayerTest.merrifield]
        l1_dict[BaseballSlot.OUTFIELD] = [PlayerTest.yelich]
        l1 = Lineup(l1_dict, BaseballSlot)

        l2_dict = self.empty_lineup_dict.copy()
        l2_dict[BaseballSlot.OUTFIELD] = [PlayerTest.merrifield]
        l2_dict[BaseballSlot.BENCH] = [PlayerTest.yelich]
        l2 = Lineup(l2_dict, BaseballSlot)

        transitions = l1.transitions(l2)

        self.assertEqual(len(transitions), 2)
        self.assertTrue(
            LineupTransition(PlayerTest.merrifield, BaseballSlot.BENCH,
                             BaseballSlot.OUTFIELD) in transitions)
        self.assertTrue(
            LineupTransition(PlayerTest.yelich, BaseballSlot.OUTFIELD,
                             BaseballSlot.BENCH) in transitions)
예제 #8
0
    def optimize(self, n=1):
        logging.debug('start optimizer n = {}'.format(n))

        self.recursion_counter = 0

        lu = Lineup(site_name=constants.dk)
        pool = self.pool

        logging.debug('Pool /n' + repr(pool))

        opt = self.__recursive_step(pool, lu)

        return opt
예제 #9
0
    def from_dict(cls, dct):  # type: (dict) -> Headend
        """

        :param dct:
        :return:
        """
        headend = cls()

        headend.headend_id = dct.pop("headend")

        headend.type = dct.pop("transport")

        headend.location = dct.pop("location")

        headend.lineups = Lineup.from_iterable(dct.pop("lineups"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for Headend: %s", ", ".join(dct.keys()))

        return headend
예제 #10
0
    def from_dict(cls, dct):  # type: (dict) -> LineupMap
        """

        :param dct:
        :return:
        """
        lineup_map = cls()

        lineup_map.stations = Station.from_iterable(dct.pop("stations"))

        lineup_map.channels = Channel.from_iterable(dct.pop("map"))

        for channel in lineup_map.channels:
            channel.station = lineup_map.get_station(channel.station_id)

        lineup_map.lineup = Lineup.from_dict(dct.pop("metadata"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for LineupMap: %s", ", ".join(dct.keys()))

        return lineup_map
예제 #11
0
    def from_dict(cls, dct):  # type: (dict) -> Status
        """

        :param dct:
        :return:
        """
        status = cls()

        if "account" in dct:
            status.account = StatusAccount.from_dict(dct.pop("account"))

        if "lineups" in dct:
            status.lineups = Lineup.from_iterable(dct.pop("lineups"))

        if "lastDataUpdate" in dct:
            status.last_data_update = parse_datetime(dct.pop("lastDataUpdate"))

        if "notifications" in dct:
            status.notifications = dct.pop("notifications")

        if "systemStatus" in dct:
            if len(dct["systemStatus"]) != 0:
                status.system_status = StatusSystem.from_dict(
                    dct.pop("systemStatus")[0])

        if "serverID" in dct:
            status.server_id = dct.pop("serverID")

        if "code" in dct:
            status.code = dct.pop("code")

        if "datetime" in dct:
            status.datetime = parse_datetime(dct.pop("datetime"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for Status: %s",
                         ", ".join(dct.keys()))

        return status
예제 #12
0
    def from_dict(cls, dct):  # type: (dict) -> LineupMap
        """

        :param dct:
        :return:
        """
        lineup_map = cls()

        lineup_map.stations = Station.from_iterable(dct.pop("stations"))

        lineup_map.channels = Channel.from_iterable(dct.pop("map"))

        for channel in lineup_map.channels:
            channel.station = lineup_map.get_station(channel.station_id)

        lineup_map.lineup = Lineup.from_dict(dct.pop("metadata"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for LineupMap: %s",
                         ", ".join(dct.keys()))

        return lineup_map
예제 #13
0
    def from_dict(cls, dct):  # type: (dict) -> Status
        """

        :param dct:
        :return:
        """
        status = cls()

        if "account" in dct:
            status.account = StatusAccount.from_dict(dct.pop("account"))

        if "lineups" in dct:
            status.lineups = Lineup.from_iterable(dct.pop("lineups"))

        if "lastDataUpdate" in dct:
            status.last_data_update = parse_datetime(dct.pop("lastDataUpdate"))

        if "notifications" in dct:
            status.notifications = dct.pop("notifications")

        if "systemStatus" in dct:
            if len(dct["systemStatus"]) != 0:
                status.system_status = StatusSystem.from_dict(dct.pop("systemStatus")[0])

        if "serverID" in dct:
            status.server_id = dct.pop("serverID")

        if "code" in dct:
            status.code = dct.pop("code")

        if "datetime" in dct:
            status.datetime = parse_datetime(dct.pop("datetime"))

        if len(dct) != 0:
            logging.warn("Key(s) not processed for Status: %s", ", ".join(dct.keys()))

        return status
예제 #14
0
import constants
from dfs_site import DFS_Site
from lineup import Lineup
from player import Player
from pool import Pool
from optimizer import Dynamic_Optimizer

import unittest
import pandas as pd

import copy

small_projections = Pool('./small_projections.csv')

empty_lineup = Lineup()

optimizer1 = Dynamic_Optimizer(pool='./small_projections.csv')
optimizer2 = Dynamic_Optimizer(pool='./projections.csv')

test_stat_projections = {
    constants.pts: 10,
    constants.rbs: 1,
    constants.asts: 1,
    constants.stls: 1,
    constants.blks: 1,
    constants.tos: 1,
    constants.threes: 1,
    constants.dd: 0,
    constants.td: 0
}
예제 #15
0
    def starting_lineups(self):
        complete = False
        away_lineup = Lineup()
        home_lineup = Lineup()

        away_roster = PlayerList()
        home_roster = PlayerList()

        away_player_list = [p for p in self._away_html_player_list]
        home_player_list = [p for p in self._home_html_player_list]

        for player_list, roster, starting_lineup in ((away_player_list,
                                                      away_roster,
                                                      away_lineup),
                                                     (home_player_list,
                                                      home_roster,
                                                      home_lineup)):
            for p in player_list:
                if p.starter:
                    starting_lineup.update_player(p)
                roster.update_player(p)

        for lineup, which_lineup in [(home_lineup, "Home"),
                                     (away_lineup, "Away")]:
            try:
                if not lineup.is_complete(raise_reason=False):
                    options = lineup.find_complete_positions()
                    if len(options) == 1:
                        for player, position in zip(lineup, options[0]):
                            if player.position != position:
                                d = {
                                    "name": player.name,
                                    "to_p": position,
                                    "from_p": player.position
                                }
                                logger.warning(
                                    "Automatically Moving {name} to position {to_p} from position {from_p}"
                                    .format(**d))
                                player.position = position
                    elif len(options) > 1:
                        s = "\n".join([
                            p.name + " " + str(p.all_positions) for p in lineup
                        ])
                        logger.critical(
                            "Too many potential lineups to find the starting lineup \n"
                            + s)
                        self.critical_errors = True
                    else:
                        s = "\n".join([
                            p.name + " " + str(p.all_positions) for p in lineup
                        ])
                        logger.critical(
                            "Can not determine complete fielding lineup from \n"
                            + s)
                        self.critical_errors = True
                if not lineup.is_complete(
                        raise_reason=False) and not self.critical_errors:
                    s = "\n".join(
                        [p.name + " " + str(p.all_positions) for p in lineup])
                    logger.critical("lineup not complete \n" + s)
                    self.critical_errors = True

            except LineupError, e:
                logging.error(
                    str(e) + "\n" + which_lineup + "\n" + str(lineup))
예제 #16
0
 def home_lineup(self):
     lineup = Lineup()
     for p in self._home_roster_share:
         if p.starter:
             lineup.append(p)
     return lineup
예제 #17
0
def calculate_lineups(db, date_for_lineup, number_of_lineups, lineup_type="initial"):
    # Create lineups/entries for all combinations of top goalies (or chosen goalies) and top value/cost players
    # Write top lineups/entries to file
    if lineup_type == "initial":
        filename = "../resources/lineups/DKLineup_" + date_for_lineup.strftime("%Y%m%d-%H%M%S") + ".csv"
        header_row = ["C", "C", "W", "W", "W", "D", "D", "G", "UTIL"]
    elif lineup_type == "entry":
        filename = "../resources/lineups/DKEntries_" + date_for_lineup.strftime("%Y%m%d-%H%M%S") + ".csv"
        header_row = ["Entry ID", "Contest Name", "Contest ID", "Entry Fee", "C", "C", "W", "W", "W", "D", "D", "G",
                      "UTIL"]
    else:
        raise ValueError("Invalid entry for lineup_type.")

    with open(filename, "w") as csvfile:
        writer = csv.writer(csvfile, lineterminator='\n')
        writer.writerow(header_row)

        logging.debug("Starting creating lineups....")
        all_lineups = []

        logging.debug("Setting up players with ID and values....")
        players = get_player_data(db, date_for_lineup)
        if lineup_type == "entry":
            entries = get_entries(db, date_for_lineup)
        else:
            entries = None

        logging.debug("Finding starting goalies....")
        starting_goalies = get_starting_goalies(db, date_for_lineup)
        goalies = [item for item in players if item.get_name() in starting_goalies]
        logging.debug(goalies)
        if len(goalies) == 0:
            raise ValueError("Could not find any starting goalies.")

        # Sort list of players and remove any goalies and players with value less than 1.0 and weight 25 or under, or if not active
        # Choose one Util from the from of the list
        logging.debug("Finding skaters....")
        skaters = copy.deepcopy(players)
        active_players = get_all_active_player_ids(db)
        skaters = [item for item in skaters if
                   item.get_position() != "G" and
                   item.get_value() > 1.0 and
                   item.get_weight() > 25 and
                   item.get_player_id() != None and
                   item.get_player_id() in active_players]
        # for skater in skaters:
        #     logging.info(skater)
        #     logging.info(skater.get_player_id())

        limit = 500
        # for i in range(len(chosen_goalies)):
        # skaters = copy.deepcopy(players)
        # Use the following statements to check a specific player's value
        # ss_value = [item for item in skaters if item['nameAndId'] == 'Steven Stamkos (7723976)'][0]['value']
        # logging.debug("Steven Stamkos value: " + str(ss_value) + ", players length: " + str(len(players)))
        for i in range(number_of_lineups):
            # Find the chosen goalies
            # chosen_goalie = [item for item in players if item.get_name_and_id() == chosen_goalies[i]][0]

            # Add random noise in order to get varied results
            # unused_players_with_noise = unused_players
            for skater in skaters:
                skater.add_value(random.uniform(-0.25, 0.25))

            # Choose a Util based on the best value
            skaters = sorted(skaters, key=lambda tup: tup.get_value(), reverse=True)
            chosen_util = skaters[0]

            # Remove Util from skaters (will be returned after calculating the set)
            skaters = [item for item in skaters if item.get_name_and_id() != chosen_util.get_name_and_id()]

            # skaters = [item for item in unused_players if item['position'] != "G"]
            logging.info("Getting lineup with " + chosen_util.get_name_and_id() + " as Util.")

            calculated_set_of_players = calculate_sets_of_players(skaters, goalies, chosen_util, limit)
            calculated_set_of_players = sorted(calculated_set_of_players, key=lambda tup: tup[10], reverse=True)
            calculated_lineup = Lineup(db, calculated_set_of_players[0])
            logging.debug(calculated_lineup)

            # Add Util back in for next loop
            skaters.append(chosen_util)

            # Lower value of non-chosen players in selected set (C,W,D), as they've already been selected
            for skater in skaters:
                if skater.get_name_and_id() in calculated_set_of_players[0]:
                    logging.info("Lowering value of " + str(skater.get_name_and_id()) + " by 0.25.")
                    skater.add_value(-0.25)

            for goalie in goalies:
                if goalie.get_name_and_id() in calculated_set_of_players[0]:
                    logging.info("Lowering value of " + str(goalie.get_name_and_id()) + " by 0.25.")
                    goalie.add_value(-0.25)

            # Write top lineup to csv
            writer.writerow(calculated_set_of_players[0][:9])
            csvfile.flush()

            # Add found lineup to all lineups
            logging.info(calculated_lineup)
            all_lineups.append(calculated_lineup)

            # Remove goalie from players
            # players = [item for item in players if item.get_name_and_id() != chosen_goalie.get_name_and_id()]

        csvfile.close()

    # Sort final lineups, add to entries, and print
    all_lineups = sorted(all_lineups, key=lambda tup: tup.get_total_value(), reverse=True)
    for s in range(len(all_lineups)):
        if lineup_type == "entry":
            entries[s].set_lineup(all_lineups[s])
            logging.info(entries[s].get_list())
        else:
            logging.info(all_lineups[s].get_list())

    # Write all lineups to database
    for lineup in all_lineups:
        lineup.insert_lineup()

    with open("../resources/lineups/DKAllLineups_" + date_for_lineup.strftime("%Y%m%d-%H%M%S") + ".csv",
              "w") as csvfile:
        writer = csv.writer(csvfile, lineterminator='\n')
        writer.writerow(["C", "C", "W", "W", "W", "D", "D", "G", "UTIL", "Weight", "Value"])
        for s in range(len(all_lineups)):
            writer.writerow(all_lineups[s].get_list())

        csvfile.close()

    if lineup_type == "entry":
        with open("../resources/lineups/DKEntries_" + date_for_lineup.strftime("%Y%m%d-%H%M%S") + ".csv",
                  "w") as csvfile:
            writer = csv.writer(csvfile, lineterminator='\n')
            writer.writerow(
                ["Entry ID", "Contest Name", "Contest ID", "Entry Fee", "C", "C", "W", "W", "W", "D", "D", "G",
                 "UTIL"])  # , "Weight", "Value"])
            for s in range(len(entries)):
                writer.writerow(entries[s].get_list()[:13])

            csvfile.close()
예제 #18
0
class LineupTest(unittest.TestCase):
    empty_lineup_dict = {
        BaseballSlot.CATCHER: [],
        BaseballSlot.FIRST: [],
        BaseballSlot.SECOND: [],
        BaseballSlot.THIRD: [],
        BaseballSlot.SHORT: [],
        BaseballSlot.OUTFIELD: [],
        BaseballSlot.MIDDLE_INFIELD: [],
        BaseballSlot.CORNER_INFIELD: [],
        BaseballSlot.UTIL: [],
        BaseballSlot.PITCHER: [],
        BaseballSlot.BENCH: [],
        BaseballSlot.INJURED: [],
    }
    base_lineup_dict = {
        BaseballSlot.CATCHER: [PlayerTest.sanchez],
        BaseballSlot.FIRST: [PlayerTest.muncy],
        BaseballSlot.SECOND: [PlayerTest.merrifield],
        BaseballSlot.THIRD: [PlayerTest.carpenter],
        BaseballSlot.SHORT: [PlayerTest.segura],
        BaseballSlot.OUTFIELD: [
            PlayerTest.springer,
            PlayerTest.rosario,
            PlayerTest.braun,
            PlayerTest.santana,
            PlayerTest.choo,
        ],
        BaseballSlot.MIDDLE_INFIELD: [PlayerTest.cano],
        BaseballSlot.CORNER_INFIELD: [PlayerTest.rizzo],
        BaseballSlot.UTIL: [PlayerTest.cabrera],
        BaseballSlot.PITCHER: [
            PlayerTest.degrom,
            PlayerTest.kimbrel,
            PlayerTest.morton,
            PlayerTest.hill,
            PlayerTest.arrieta,
            PlayerTest.glasnow,
            PlayerTest.barnes,
            PlayerTest.stripling,
            PlayerTest.smith,
        ],
        BaseballSlot.BENCH:
        [PlayerTest.paddack, PlayerTest.yelich, PlayerTest.peraza],
        BaseballSlot.INJURED: [PlayerTest.olson, PlayerTest.jimenez],
    }

    simple_lineup = Lineup(base_lineup_dict, BaseballSlot)

    def test_possible_starters_one_slot(self):
        lineup_settings = LineupSettings({
            BaseballSlot.CATCHER: 0,
            BaseballSlot.FIRST: 1,
            BaseballSlot.SECOND: 0,
            BaseballSlot.THIRD: 0,
            BaseballSlot.SHORT: 0,
            BaseballSlot.MIDDLE_INFIELD: 0,
            BaseballSlot.CORNER_INFIELD: 0,
            BaseballSlot.OUTFIELD: 0,
            BaseballSlot.UTIL: 0,
            BaseballSlot.BENCH: 0,
            BaseballSlot.PITCHER: 0,
            BaseballSlot.INJURED: 0,
        })

        lineups = self.simple_lineup.possible_lineups(
            lineup_settings, BaseballSlot.hitting_slots())
        starters = set(map(Lineup.starters, lineups))
        self.assertEqual(len(starters), 4)
        self.assertTrue(frozenset({PlayerTest.rizzo}) in starters)
        self.assertTrue(frozenset({PlayerTest.muncy}) in starters)
        self.assertTrue(frozenset({PlayerTest.carpenter}) in starters)
        self.assertTrue(frozenset({PlayerTest.cabrera}) in starters)

    def test_possible_starters_two_slots_no_dups(self):
        lineup_settings = LineupSettings({
            BaseballSlot.CATCHER: 0,
            BaseballSlot.FIRST: 1,
            BaseballSlot.SECOND: 0,
            BaseballSlot.THIRD: 0,
            BaseballSlot.SHORT: 0,
            BaseballSlot.MIDDLE_INFIELD: 0,
            BaseballSlot.CORNER_INFIELD: 1,
            BaseballSlot.OUTFIELD: 0,
            BaseballSlot.UTIL: 0,
            BaseballSlot.BENCH: 0,
            BaseballSlot.PITCHER: 0,
            BaseballSlot.INJURED: 0,
        })

        lineups = self.simple_lineup.possible_lineups(
            lineup_settings, BaseballSlot.hitting_slots())
        starters = set(map(Lineup.starters, lineups))
        self.assertEqual(len(starters), 6)
        self.assertTrue(
            frozenset({PlayerTest.rizzo, PlayerTest.muncy}) in starters)
        self.assertTrue(
            frozenset({PlayerTest.rizzo, PlayerTest.carpenter}) in starters)
        self.assertTrue(
            frozenset({PlayerTest.rizzo, PlayerTest.cabrera}) in starters)
        self.assertTrue(
            frozenset({PlayerTest.carpenter, PlayerTest.muncy}) in starters)
        self.assertTrue(
            frozenset({PlayerTest.carpenter, PlayerTest.cabrera}) in starters)
        self.assertTrue(
            frozenset({PlayerTest.muncy, PlayerTest.cabrera}) in starters)

    def test_transitions_single_swap(self):
        carpenter_first_dict = self.empty_lineup_dict.copy()
        carpenter_first_dict[BaseballSlot.FIRST] = [PlayerTest.carpenter]
        cf_lineup = Lineup(carpenter_first_dict, BaseballSlot)

        carpenter_corner_inf_dict = self.empty_lineup_dict.copy()
        carpenter_corner_inf_dict[BaseballSlot.CORNER_INFIELD] = [
            PlayerTest.carpenter
        ]
        cci_lineup = Lineup(carpenter_corner_inf_dict, BaseballSlot)

        transitions = cf_lineup.transitions(cci_lineup)

        self.assertEqual(len(transitions), 1)
        self.assertTrue(
            LineupTransition(PlayerTest.carpenter, BaseballSlot.FIRST,
                             BaseballSlot.CORNER_INFIELD) in transitions)

    def test_transitions_swap_two_players(self):
        l1_dict = self.empty_lineup_dict.copy()
        l1_dict[BaseballSlot.BENCH] = [PlayerTest.merrifield]
        l1_dict[BaseballSlot.OUTFIELD] = [PlayerTest.yelich]
        l1 = Lineup(l1_dict, BaseballSlot)

        l2_dict = self.empty_lineup_dict.copy()
        l2_dict[BaseballSlot.OUTFIELD] = [PlayerTest.merrifield]
        l2_dict[BaseballSlot.BENCH] = [PlayerTest.yelich]
        l2 = Lineup(l2_dict, BaseballSlot)

        transitions = l1.transitions(l2)

        self.assertEqual(len(transitions), 2)
        self.assertTrue(
            LineupTransition(PlayerTest.merrifield, BaseballSlot.BENCH,
                             BaseballSlot.OUTFIELD) in transitions)
        self.assertTrue(
            LineupTransition(PlayerTest.yelich, BaseballSlot.OUTFIELD,
                             BaseballSlot.BENCH) in transitions)
예제 #19
0
class TestDraftState(TestCase):
    ls = LineupSettings({
        BaseballSlot.OUTFIELD: 2,
        BaseballSlot.SHORT: 1,
        BaseballSlot.PITCHER: 1,
        BaseballSlot.UTIL: 1,
        BaseballSlot.BENCH: 1,
    })
    l1 = Lineup(
        {
            BaseballSlot.OUTFIELD: [PlayerTest.yelich, PlayerTest.braun],
            BaseballSlot.UTIL: [PlayerTest.santana],
        },
        BaseballSlot,
    )
    l2 = Lineup(
        {
            BaseballSlot.PITCHER: [PlayerTest.degrom],
            BaseballSlot.SHORT: [PlayerTest.segura],
        },
        BaseballSlot,
    )
    l3 = Lineup(
        {BaseballSlot.OUTFIELD: [PlayerTest.springer, PlayerTest.rosario]},
        BaseballSlot)
    info = DraftGameInfo(3, 100, ls)
    state = DraftState(
        info,
        {
            PlayerTest.springer,
            PlayerTest.rosario,
            PlayerTest.degrom,
            PlayerTest.segura,
            PlayerTest.rizzo,
            PlayerTest.peraza,
            PlayerTest.choo,
            PlayerTest.morton,
            PlayerTest.yelich,
            PlayerTest.braun,
            PlayerTest.santana,
        },
        {
            PlayerTest.springer,
            PlayerTest.rosario,
            PlayerTest.degrom,
            PlayerTest.segura,
            PlayerTest.yelich,
            PlayerTest.braun,
            PlayerTest.santana,
        },
        [l1, l2, l3],
        0,
        True,
    )

    small_lineup_settings = LineupSettings({
        BaseballSlot.OUTFIELD: 1,
        BaseballSlot.INJURED: 1
    })
    sl0 = Lineup({BaseballSlot.OUTFIELD: [PlayerTest.springer]}, BaseballSlot)
    sl1 = Lineup({BaseballSlot.OUTFIELD: [PlayerTest.rosario]}, BaseballSlot)
    sl2 = Lineup({BaseballSlot.OUTFIELD: [PlayerTest.yelich]}, BaseballSlot)
    terminal_state = DraftState(
        DraftGameInfo(3, 1000, small_lineup_settings),
        {PlayerTest.springer, PlayerTest.rosario, PlayerTest.yelich},
        {PlayerTest.springer, PlayerTest.rosario, PlayerTest.yelich},
        [sl0, sl1, sl2],
        0,
        True,
    )

    def test__possible_additions(self):
        poss_p0 = self.state._possible_additions(0)
        self.assertEqual(4, len(poss_p0))
        self.assertTrue((PlayerTest.rizzo, BaseballSlot.BENCH) in poss_p0)
        self.assertTrue((PlayerTest.peraza, BaseballSlot.SHORT) in poss_p0)
        self.assertTrue((PlayerTest.choo, BaseballSlot.BENCH) in poss_p0)
        self.assertTrue((PlayerTest.morton, BaseballSlot.PITCHER) in poss_p0)

        poss_p1 = self.state._possible_additions(1)
        self.assertEqual(4, len(poss_p1))
        self.assertTrue((PlayerTest.rizzo, BaseballSlot.UTIL) in poss_p1)
        self.assertTrue((PlayerTest.peraza, BaseballSlot.UTIL) in poss_p1)
        self.assertTrue((PlayerTest.choo, BaseballSlot.OUTFIELD) in poss_p1)
        self.assertTrue((PlayerTest.morton, BaseballSlot.BENCH) in poss_p1)

        poss_p2 = self.state._possible_additions(2)
        self.assertEqual(4, len(poss_p2))
        self.assertTrue((PlayerTest.rizzo, BaseballSlot.UTIL) in poss_p2)
        self.assertTrue((PlayerTest.peraza, BaseballSlot.SHORT) in poss_p2)
        self.assertTrue((PlayerTest.choo, BaseballSlot.UTIL) in poss_p2)
        self.assertTrue((PlayerTest.morton, BaseballSlot.PITCHER) in poss_p2)

    def test_children(self):
        children_p0 = self.state.children()
        self.assertEqual(4, len(children_p0))
        for child in children_p0:
            # different lineup lists
            self.assertTrue(self.state.lineups != child.lineups)
            # different lineups for player 0
            self.assertNotEqual(self.state.lineups[0], child.lineups[0])
            # same lineups for all other players
            self.assertEqual(self.state.lineups[1], child.lineups[1])
            self.assertEqual(self.state.lineups[2], child.lineups[2])

    def test_is_terminal(self):
        self.assertFalse(self.state.is_terminal())
        self.assertTrue(self.terminal_state.is_terminal())

    def test__next_player(self):
        self.assertEqual(1, self.state._next_player())

    def test__next_player_end_returning(self):
        ds = DraftState(self.info, [], {}, [], 2, False)
        self.assertEqual(1, ds._next_player())

    def test__next_direction(self):
        self.assertTrue(self.state._next_direction())

    def test__next_direction_returning(self):
        ds = DraftState(self.info, [], {}, [], 2, False)
        self.assertFalse(ds._next_direction())
예제 #20
0
 def home_lineup(self):
     lineup = Lineup()
     for p in self._home_roster_share:
         if p.starter:
             lineup.append(p)
     return lineup