def set_name_and_team(re_match, group_name, game, sample): if group_name in re_match.groupdict() and re_match.group( group_name) is not None: player = re_match.group(group_name) sample.set_arg(group_name, f'[[{player}]]') if sample.get_arg(f'{group_name}Team') is None: try: playerObj = Player.find_by_name(player) playerId = playerObj.id historicalPlayerObj = Player.load_by_gameday( playerId, game.season, game.day) if historicalPlayerObj is not None: teamId = historicalPlayerObj.team_id teamObj = Team.load(teamId) print( f'{player}: Found historical team data: {teamObj.full_name}' ) sample.set_arg(f'{group_name}Team', f'[[{teamObj.full_name}]]') elif playerObj.team_id is not None: teamObj = Team.load(playerObj.team_id) print( f'{player}: Falling back to current team: {teamObj.full_name}' ) sample.set_arg( f'{group_name}Team', f'maybe? [[{playerObj.league_team.full_name}]]') else: print(f'Tried but failed to look up {player}') sample.set_arg(f'{group_name}Team', 'Unknown') except: print(f'Failed to look up {player}') sample.set_arg(f'{group_name}Team', 'Unknown')
def main(player_id, player_ids): site = pwb.Site() always = False error_count = 0 page_count = 0 if (player_id): player = Player.load_one(player_id) # Load player from blaseball-mike (page_count, error_count, always) = wiki_edit(player, site, always, error_count, page_count, None, None, False) elif (player_ids): ids_list = player_ids.split(',') for player_id in ids_list: player = Player.load_one(player_id) # Load player from blaseball-mike (page_count, error_count, always) = wiki_edit(player, site, always, error_count, page_count, None, None, False) else: teams = Team.load_all() for team in teams.values(): if team.nickname == 'Shoe Thieves': for batter in team.lineup: (page_count, error_count, always) = wiki_edit(batter, site, always, error_count, page_count, team.full_name, 'Batter', False) for pitcher in team.rotation: (page_count, error_count, always) = wiki_edit(pitcher, site, always, error_count, page_count, team.full_name, 'Pitcher', False) # for batter in team.bench: # (page_count, error_count, always) = wiki_edit(batter, site, always, error_count, page_count, team.full_name, 'Batter', True) # for pitcher in team.bullpen: # (page_count, error_count, always) = wiki_edit(pitcher, site, always, error_count, page_count, team.full_name, 'Pitcher', True) print(f'Updated {page_count} pages. Error count: {error_count}.')
def adjust_stlats_for_items(player): items = player.items player_copy = Player(player.json()) for item in items: if item.health: player_copy = handle_player_adjustments(player_copy, item.root["adjustments"]) for section in ("root", "pre_prefix", "post_prefix", "suffix"): if getattr(item, section): player_copy = handle_player_adjustments( player_copy, getattr(item, section)["adjustments"]) if item.prefixes: for prefix in item.prefixes: player_copy = handle_player_adjustments( player_copy, prefix["adjustments"]) for category in ("defense", "hitting", "pitching", "baserunning"): setattr( player_copy, "_{}_rating".format(category), max( (getattr(player_copy, "_{}_rating".format(category)) or 0.001) + (getattr(item, "{}_rating".format(category)) or 0.001), 0.001, ), ) return player_copy
def get_item_stats(items, include_wielder=False): """ Display item information :param items: Item or list of items :param include_wielder: Whether to include wielder information :return: pandas DataFrame """ if not isinstance(items, (Item, list, dict)): return if isinstance(items, Item): items = [items] elif isinstance(items, dict): items = list(items.values()) table = [] for i in items: mods = [ Modification.load_one(a["mod"]).title for a in i.adjustments if a["type"] == 0 ] entry = {} if include_wielder: ret = database.get_players_by_item(i.id) if isinstance(ret, list): wielder = Player(ret[0]) entry["Wielder"] = wielder.name entry["Team"] = wielder.league_team.nickname entry = {"Max Durability": i.durability, "Modifications": mods} table.append(pandas.Series(entry, name=i.name)) return pandas.DataFrame(table)
def player_jose_haley_chronicler(self): """Chronicler data, S2""" return Player({ "timestamp": "2020-07-29T08:12:22.438Z", "_id": "bd8d58b6-f37f-48e6-9919-8e14ec91f92a", "name": "José Haley", "soul": 6, "moxie": 0.8394594855531319, "buoyancy": 0.7153473609848746, "coldness": 0.4320650950278062, "deceased": False, "divinity": 0.5795954963679981, "chasiness": 0.8107670476342832, "martyrdom": 0.7474878946878154, "baseThirst": 0.11819202161814601, "indulgence": 0.8312626148346798, "musclitude": 0.06110516802113031, "tragicness": 0, "omniscience": 0.21850704217419237, "patheticism": 0.1284083999268748, "suppression": 0.46870067653782654, "continuation": 0.521443505906251, "ruthlessness": 0.8408153901712421, "totalFingers": 10, "watchfulness": 0.5372326666660634, "laserlikeness": 0.773597769166374, "overpowerment": 0.04988723501487735, "tenaciousness": 0.5026610346424867, "thwackability": 0.15773648236309823, "anticapitalism": 0.7154488256234361, "groundFriction": 0.4110965363045602, "pressurization": 0.5228629100377091, "unthwackability": 0.20228895235926592, "shakespearianism": 0.9898894978911135 })
def test_load_all_by_gameday(self): players = Player.load_all_by_gameday(season=11, day=99) assert isinstance(players, dict) assert len(players) > 0 for key, player in players.items(): assert isinstance(key, str) assert isinstance(player, Player) assert key == player.id
def test_load(self): players = Player.load("6644d767-ab15-4528-a4ce-ae1f8aadb65f", "d97835fd-2e92-4698-8900-1f5abea0a3b6") assert isinstance(players, dict) assert len(players) == 2 for key, player in players.items(): assert isinstance(key, str) assert isinstance(player, Player) assert key == player.id
def test_load_all(self): all_players = Player.load_all() assert isinstance(all_players, dict) assert len(all_players) > 0 for id_, p in all_players.items(): assert isinstance(p, Player) assert isinstance(id_, str) assert id_ == p.id
def get_held_items(): """ Get a list of all items currently held by players :return: list of Items objects """ players = Player.load_all() carried_items = [] for p in players.values(): carried_items.extend(p.items) return carried_items
def _get_or_generate_player(name): try: p = Player.find_by_name(name) player = p.json() player['current_vibe'] = p.get_vibe(_current_day()) player['batting_stars'] = p.batting_stars player['pitching_stars'] = p.pitching_stars player['baserunning_stars'] = p.baserunning_stars player['defense_stars'] = p.defense_stars player['soulscream'] = p.soulscream player['blood'] = p.blood player['coffee'] = p.coffee except (AttributeError, KeyError, json.decoder.JSONDecodeError): player = _make_player_json(name) return player
def chart_vibes(name): player = Player.make_random(name=name, seed=name) player = player.simulated_copy(buffs={'overall_rating': (player.total_fingers - 10) * .01}) days = list(range(99)) vibes = [player.get_vibe(d) for d in days] return make_response(render_template( 'vibe_chart.html', days=days, vibes=vibes, quality=[.1] * len(days), excellent=[.4] * len(days), most_excellent=[.8] * len(days), less=[-.1] * len(days), far_less=[-.4] * len(days), terrible=[-.8] * len(days), ))
def _parse_collection_names(names, anim=None, lineup_length=9): collection = [] for i, name in enumerate(names): player = Player.make_random(seed=name) player = player.simulated_copy(buffs={'overall_rating': (player.total_fingers - 10) * .01}) if i < lineup_length: rating = player.batting_stars else: rating = player.pitching_stars rating = math.modf(rating) collection.append(( name, range(int(rating[1])), rating[0] >= .5, _get_animation(name, anim), )) return collection
def _make_player_json(name, id_=None): player = Player.make_random(name=name, seed=name) player = player.simulated_copy(buffs={'overall_rating': (player.total_fingers - 10) * .01}) js = player.json() props = [ 'soulscream', 'batting_rating', 'batting_stars', 'pitching_rating', 'pitching_stars', 'baserunning_rating', 'baserunning_stars', 'defense_rating', 'defense_stars', ] for prop in props: js[prop] = getattr(player, prop) if id_: js['id'] = id_ js['current_vibe'] = player.get_vibe(_current_day()) return js
def player_blintz_chamberlain(self): """popular Onomancer player, used for random-generation tests""" return Player({ "name": "Blintz Chamberlain", "id": "afa445a3-4d67-3a30-8efb-a375eecb93d7", "baseThirst": 0.7652405249671463, "continuation": 0.6428867401667699, "groundFriction": 0.5912931500736168, "indulgence": 0.8700238829332707, "laserlikeness": 0.9663994370523981, "divinity": 0.8889020005767538, "martyrdom": 0.511810911577921, "moxie": 0.43305961431596485, "musclitude": 0.11869863677781145, "patheticism": 0.41867249633703796, "thwackability": 0.21012113556844603, "tragicness": 0.6954262334361944, "anticapitalism": 0.990390904466214, "chasiness": 0.31053980147709115, "omniscience": 0.1362389075835675, "tenaciousness": 0.8473490203578398, "watchfulness": 0.8531692290089713, "coldness": 0.4445769874349872, "overpowerment": 0.6330609772412268, "ruthlessness": 0.0870056506991157, "shakespearianism": 0.12353901517799748, "unthwackability": 0.5639130497577806, "suppression": 0.821247826644212, "buoyancy": 0.6876701268906852, "cinnamon": 0.9637391502188264, "deceased": False, "peanutAllergy": False, "pressurization": 0.4258005116863378, "soul": 9, "totalFingers": 23, "fate": 71 })
def test_load_all_by_gameday_bad_day_low(self): with pytest.raises(ValueError): bad_day = Player.load_all_by_gameday(season=6, day=-1)
def test_load_by_gameday_bad_day_low(self): with pytest.raises(ValueError): bad_day = Player.load_by_gameday("f70dd57b-55c4-4a62-a5ea-7cc4bf9d8ac1", season=6, day=-1)
def generate_file(filename, inactive, archive, include_items, unscattered): sim = SimulationData.load() if archive and os.path.isfile(filename): os.rename( filename, filename.replace(".csv", "S{}preD{}.csv".format(sim.season, sim.day + 1)), ) output = [] positions = (("lineup", "rotation", "shadows") if inactive else ("lineup", "rotation")) league = League.load() players = Player.load_all() for subleague in league.subleagues.values(): for division in subleague.divisions.values(): for team in division.teams.values(): for position in positions: for turn_order, player_id in enumerate( getattr(team, "_{}_ids".format(position))): player = players[player_id] if include_items: player = adjust_stlats_for_items(player) player_row = [ team.full_name, subleague.name, division.name, player.name if not unscattered or "unscatteredName" not in player.state else player.state["unscatteredName"], position, turn_order + 1, player.id, player.anticapitalism, player.base_thirst, player.buoyancy, player.chasiness, player.coldness, player.continuation, player.divinity, player.ground_friction, player.indulgence, player.laserlikeness, player.martyrdom, player.moxie, player.musclitude, player.bat.id or "", player.omniscience, player.overpowerment, player.patheticism, player.ruthlessness, player.shakespearianism, player.suppression, player.tenaciousness, player.thwackability, player.tragicness, player.unthwackability, player.watchfulness, player.pressurization, player.total_fingers, player.soul, player.deceased, player.peanut_allergy, player.cinnamon, player.fate, player.armor.id or "", player.ritual, player._blood_id, player._coffee_id, ";".join(attr.id for attr in player.perm_attr + player.item_attr), ";".join(attr.id for attr in player.seas_attr), ";".join(attr.id for attr in player.week_attr), ";".join(attr.id for attr in player.game_attr), player.batting_rating * 5.0, player.pitching_rating * 5.0, player.baserunning_rating * 5.0, player.defense_rating * 5.0, ] output.append(player_row) output.sort(key=operator.itemgetter(0, 4, 5)) with open(filename, "w") as f: f.write("{}\n".format(",".join('"{}"'.format(col) for col in COLUMNS))) f.write("\n".join(",".join(['"{}"'.format(d) for d in datarow]) for datarow in output))
def player_tot_clark(self): """player common case""" return Player.load_one("e3c514ae-f813-470e-9c91-d5baf5ffcf16")
def test_load_by_gameday_bad_day_high(self): bad_day = Player.load_by_gameday("f70dd57b-55c4-4a62-a5ea-7cc4bf9d8ac1", season=6, day=999) assert bad_day is None
def test_load_all_by_gameday_bad_day_high(self): bad_day = Player.load_all_by_gameday(season=6, day=999) assert isinstance(bad_day, dict) assert len(bad_day) == 0
def player_test_playerson(self): """worst possible player, invalid ID, modifications, items""" return Player({ "id": "00000000-0000-0000-0000-000000000000", "name": "Test Playerson", "anticapitalism": 0.01, "baseThirst": 0.01, "buoyancy": 0.01, "chasiness": 0.01, "coldness": 0.01, "continuation": 0.01, "divinity": 0.01, "groundFriction": 0.01, "indulgence": 0.01, "laserlikeness": 0.01, "martyrdom": 0.01, "moxie": 0.01, "musclitude": 0.01, "omniscience": 0.01, "overpowerment": 0.01, "patheticism": 0.99, "ruthlessness": 0.01, "shakespearianism": 0.01, "suppression": 0.01, "tenaciousness": 0.01, "thwackability": 0.01, "tragicness": 0.1, "unthwackability": 0.01, "watchfulness": 0.01, "pressurization": 0.01, "totalFingers": 11, "soul": 1, "deceased": False, "peanutAllergy": True, "cinnamon": 0.01, "fate": 1, "bat": "MUSHROOM", "armor": "ARM_CANNON", "ritual": "Providing sufficient test coverage", "coffee": 0, "blood": 0, "permAttr": ["SHELLED"], "seasAttr": ["SIPHON"], "weekAttr": ["MARKED"], "gameAttr": ["EXTRA_BASE"], "hitStreak": 0, "consecutiveHits": 0, "leagueTeamId": None, "tournamentTeamId": None, "eDensity": 69.420, "state": {}, "evolution": 0, "items": [ { "id": "217ef5c6-9616-41fc-9f76-f34aa097e001", "name": "Bat", "forger": None, "forgerName": None, "prePrefix": None, "prefixes": None, "postPrefix": None, "root": { "name": "Bat", "adjustments": [ { "stat": 2, "type": 1, "value": 0.14652311755001893 } ] }, "suffix": None, "durability": 1, "health": 1, "baserunningRating": 0, "pitchingRating": 0, "hittingRating": 0.07809707777020458, "defenseRating": 0 } ], "itemAttr": ["PERK"] })
def secret_baserunner_name(self) -> Optional[str]: if self.secret_baserunner: return Player.load_one(str(self.secret_baserunner)).name return None
def test_load_by_gameday_bad_season_high(self): bad_season = Player.load_by_gameday("f70dd57b-55c4-4a62-a5ea-7cc4bf9d8ac1", season=999, day=100) assert bad_season is None
def test_load_all_by_gameday_bad_season_high(self): bad_season = Player.load_all_by_gameday(season=999, day=5) assert isinstance(bad_season, dict) assert len(bad_season) == 0
def test_load_history_bad_id(self): bad_player = Player.load_history("00000000-0000-0000-0000-000000000000", count=200) assert isinstance(bad_player, list) assert len(bad_player) == 0
def test_load_by_gameday(self): player = Player.load_by_gameday("f70dd57b-55c4-4a62-a5ea-7cc4bf9d8ac1", season=2, day=100) assert isinstance(player, Player)
def player_vibe(self): """vibes reference player""" return Player({ "buoyancy": 0.01, "cinnamon": 0.9043236348376793, "pressurization": 0.7857967407463393, "vibes": [ 0.9043236348376793, 0.4817935409416749, -0.36326664685033416, -0.7857967407463392, -0.36326664685033505, 0.48179354094167404, 0.9043236348376793, 0.48179354094167576, -0.36326664685033394, -0.7857967407463392, -0.36326664685033594, 0.48179354094167254, 0.9043236348376793, 0.481793540941676, -0.3632666468503337, -0.7857967407463392, -0.36326664685033483, 0.48179354094167365, 0.9043236348376793, 0.4817935409416748, -0.3632666468503336, -0.7857967407463392, -0.36326664685033494, 0.4817935409416735, 0.9043236348376793, 0.48179354094167753, -0.3632666468503334, -0.7857967407463392, -0.3632666468503377, 0.48179354094167326, 0.9043236348376793, 0.48179354094168036, -0.3632666468503333, -0.7857967407463392, -0.3632666468503378, 0.48179354094167054, 0.9043236348376793, 0.48179354094168053, -0.36326664685033305, -0.7857967407463392, -0.36326664685033805, 0.4817935409416703, 0.9043236348376793, 0.48179354094168075, -0.36326664685033283, -0.7857967407463392, -0.36326664685033816, 0.48179354094167015, 0.9043236348376793, 0.4817935409416809, -0.3632666468503275, -0.7857967407463392, -0.3632666468503384, 0.48179354094167, 0.9043236348376793, 0.48179354094168114, -0.3632666468503273, -0.7857967407463392, -0.3632666468503386, 0.4817935409416698, 0.9043236348376793, 0.48179354094167604, -0.36326664685032706, -0.7857967407463392, -0.36326664685034393, 0.48179354094166965, 0.9043236348376793, 0.4817935409416815, -0.36326664685033216, -0.7857967407463392, -0.36326664685033905, 0.4817935409416642, 0.9043236348376793, 0.4817935409416764, -0.36326664685032684, -0.7857967407463392, -0.3632666468503444, 0.48179354094166926, 0.9043236348376793, 0.48179354094168175, -0.3632666468503317, -0.7857967407463392, -0.3632666468503394, 0.4817935409416639, 0.9043236348376793, 0.4817935409416768, -0.3632666468503264, -0.7857967407463392, -0.3632666468503447, 0.48179354094166893, 0.9043236348376793, 0.48179354094168214, -0.3632666468503315, -0.7857967407463392, -0.3632666468503397, 0.48179354094166355, 0.9043236348376793, 0.4817935409416876, -0.36326664685032606 ]})
def test_load_by_gameday_bad_id(self): bad_player = Player.load_by_gameday("00000000-0000-0000-0000-000000000000", season=4, day=1) assert bad_player is None
def get_similar_player(player, stat='batting', num_players=10, include_shadows=False, filter_by_postion=True, filter_dead=True): """ Get a list of players that have statlines similar to the selected player. TODO: Weight the attributes based on importance? :param player: player to compare :param stat: stats to compare: 'batting', 'pitching', 'baserunning', 'defense', 'offense' :param num_players: number of players to return :param include_shadows: whether to include shadows players in the comparison :param filter_by_postion: if True, do not include players that are not currently active in this position :param filter_dead: if True, do not include dead players :return: dictionary with players as values and relative similarity as the key """ bat = [ "thwackability", "divinity", "musclitude", "moxie", "patheticism", "martyrdom", "tragicness", "buoyancy" ] pitch = [ "unthwackability", "ruthlessness", "overpowerment", "shakespearianism", "coldness", "suppression" ] run = [ "laserlikeness", "continuation", "baseThirst", "indulgence", "groundFriction" ] def_ = [ "omniscience", "tenaciousness", "watchfulness", "anticapitalism", "chasiness" ] if stat == 'batting': attrs = bat position = 'BATTER' elif stat == 'pitching': attrs = pitch position = 'PITCHER' elif stat == 'baserunning': attrs = run position = 'BATTER' elif stat == 'defense': attrs = def_ position = 'BATTER' elif stat == 'offense': attrs = bat + run position = 'BATTER' else: raise ValueError(f"Invalid stat {stat}") # Generate table of all players url = "https://api.sibr.dev/datablase/v1/allPlayers" if include_shadows: url += f"?includeShadows={include_shadows}" all_players = [ reference._apply_type_map(p) for p in requests.get(url).json() ] if filter_dead: all_players = [x for x in all_players if x["deceased"] is False] all_players_table = pandas.DataFrame( all_players, index=[x["player_id"] for x in all_players]) if filter_by_postion: all_players_table = all_players_table[ all_players_table["position_type"] == position] all_table = all_players_table.filter(items=attrs) min_stat = all_table.min(axis=0) max_stat = all_table.max(axis=0) all_scaled = (2.0 * ((all_table - min_stat) / (max_stat - min_stat))) - 1.0 # Generate table row of selected player player_array = pandas.Series(player.json()) player_array = player_array.filter(items=attrs) player_scaled = (2.0 * ((player_array - min_stat) / (max_stat - min_stat))) - 1.0 # PERFORM THE RITUAL all_norm = all_scaled.apply(np.linalg.norm, axis=1) player_norm = np.linalg.norm(player_scaled) results = all_scaled.dot(player_scaled) / (all_norm * player_norm) # Sort and organize output results = results.drop(index=player.id, errors='ignore') sorted_ = results.sort_values(ascending=False) players = Player.load(*sorted_.index[0:num_players]) players = [players.get(id_) for id_ in sorted_.index[0:num_players]] return {results[x.id]: x for x in players}
def player_ortiz_lopez_datablase(self): """Datablase data""" return Player({ "player_id": "2b157c5c-9a6a-45a6-858f-bf4cf4cbc0bd", "player_name": "Ortiz Lopez", "current_state": "active", "current_location": "main_roster", "debut_gameday": 0, "debut_season": 2, "debut_tournament": -1, "team_id": "b72f3061-f573-40d7-832a-5ad475bd7909", "team_abbreviation": "LVRS", "team": "Lovers", "position_id": 2, "position_type": "BATTER", "valid_from": "2020-08-30T07:25:58.403Z", "valid_until": "2020-09-20T19:15:35.880Z", "gameday_from": None, "season_from": 3, "tournament_from": None, "phase_type_from": "END_POSTSEASON", "deceased": False, "incineration_season": None, "incineration_gameday": None, "incineration_phase": None, "anticapitalism": 0.121689363683167, "base_thirst": 0.829374928477014, "buoyancy": 0.829453218121553, "chasiness": 0.450694519660136, "coldness": 0.562656726994396, "continuation": 1.02827830638762, "divinity": 0.538723065444542, "ground_friction": 0.266134659534965, "indulgence": 1.03510699315732, "laserlikeness": 0.212273332142247, "martyrdom": 0.0977123559614549, "moxie": 0.803384285735094, "musclitude": 0.319551775656397, "omniscience": 0.330914500226764, "overpowerment": 0.71321914390113, "patheticism": 0.440188944762842, "ruthlessness": 0.581635439058792, "shakespearianism": 0.893373843807914, "suppression": 0.870271818425412, "tenaciousness": 0.984116177774339, "thwackability": 0.291937408193296, "tragicness": 0.1, "unthwackability": 0.962527250911458, "watchfulness": 0.420183966025271, "pressurization": 0.84275013393132, "cinnamon": 0.85286944117706, "total_fingers": 10, "soul": 9, "fate": 38, "peanut_allergy": False, "armor": "", "bat": "", "ritual": "Yoga", "coffee": "Flat White", "blood": "Basic", "url_slug": "ortiz-lopez", "modifications": None, "batting_rating": 0.437806991128796, "baserunning_rating": 0.398604818480104, "defense_rating": 0.548036988423843, "pitching_rating": 0.731829178453461 })