Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add live bonus to Fixture class #77

Merged
merged 6 commits into from
Oct 20, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 31 additions & 7 deletions fpl/fpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,15 +437,39 @@ async def get_gameweek(self, gameweek_id, include_live=False,
static_gameweeks = getattr(self, "events")

try:
static_gameweek = next(gameweek for gameweek in static_gameweeks.values() if
gameweek["id"] == gameweek_id)
static_gameweek = next(
gameweek for gameweek in static_gameweeks.values() if
gameweek["id"] == gameweek_id)
except StopIteration:
raise ValueError(f"Gameweek with ID {gameweek_id} not found")

live_gameweek = await fetch(
self.session, API_URLS["gameweek_live"].format(gameweek_id))
if include_live:
live_gameweek = await fetch(
self.session, API_URLS["gameweek_live"].format(gameweek_id))

live_gameweek.update(static_gameweek)
# Convert element list to dict
live_gameweek["elements"] = {
element["id"]: element for element in live_gameweek["elements"]}

# Include live bonus points
if not static_gameweek["finished"]:
fixtures = await self.get_fixtures_by_gameweek(gameweek_id)
fixtures = filter(lambda f: not f.finished, fixtures)
bonus_for_gameweek = []

for fixture in fixtures:
bonus = fixture.get_bonus(provisional=True)
bonus_for_gameweek.extend(bonus["a"] + bonus["h"])

bonus_for_gameweek = {bonus["element"]: bonus["value"]
for bonus in bonus_for_gameweek}

for player_id, bonus_points in bonus_for_gameweek:
if live_gameweek["elements"][player_id]["bonus"] == 0:
live_gameweek["elements"][player_id]["bonus"] += bonus_points
live_gameweek["elements"][player_id]["total_points"] += bonus_points

static_gameweek.update(live_gameweek)

if return_json:
return static_gameweek
Expand Down Expand Up @@ -534,8 +558,8 @@ async def get_h2h_league(self, league_id, return_json=False):
async def login(self, email=None, password=None):
"""Returns a requests session with FPL login authentication.

:param string email: Email address for the user's Fantasy Premier League
account.
:param string email: Email address for the user's Fantasy Premier
League account.
:param string password: Password for the user's Fantasy Premier League
account.
"""
Expand Down
150 changes: 96 additions & 54 deletions fpl/models/fixture.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ def add_player(location, information):
location.append({"player": player, "goals": goals})


class Fixture():
# noinspection PyUnresolvedReferences
class Fixture:
"""A class representing fixtures in the Fantasy Premier League.

Basic usage::
Expand All @@ -27,122 +28,163 @@ class Fixture():
>>> asyncio.run(main())
Arsenal vs. Man City - 10 Aug 19:00
"""

def __init__(self, fixture_information):
for k, v in fixture_information.items():
if k == "stats":
v = {w["identifier"]: {"a": w["a"], "h": w["h"]} for w in v}
setattr(self, k, v)

def _get_players(self, metric):
"""Helper function that returns a dictionary containing players for the
given metric (away and home).
"""
stats = getattr(self, "stats", [])
for statistic in stats:
if metric in statistic.keys():
return statistic[metric]

return {}

def get_goalscorers(self):
"""Returns all players who scored in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("goals_scored")
try:
return self.stats["goals_scored"]
except KeyError:
return {"a": [], "h": []}

def get_assisters(self):
"""Returns all players who made an assist in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("assists")
try:
return self.stats["assists"]
except KeyError:
return {"a": [], "h": []}

def get_own_goalscorers(self):
"""Returns all players who scored an own goal in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("own_goals")
try:
return self.stats["own_goals"]
except KeyError:
return {"a": [], "h": []}

def get_yellow_cards(self):
"""Returns all players who received a yellow card in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("yellow_cards")
try:
return self.stats["yellow_cards"]
except KeyError:
return {"a": [], "h": []}

def get_red_cards(self):
"""Returns all players who received a red card in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("red_cards")
try:
return self.stats["red_cards"]
except KeyError:
return {"a": [], "h": []}

def get_penalty_saves(self):
"""Returns all players who saved a penalty in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("penalties_saved")
try:
return self.stats["penalties_saved"]
except KeyError:
return {"a": [], "h": []}

def get_penalty_misses(self):
"""Returns all players who missed a penalty in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("penalties_missed")
try:
return self.stats["penalties_missed"]
except KeyError:
return {"a": [], "h": []}

def get_saves(self):
"""Returns all players who made a save in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}
try:
return self.stats["saves"]
except KeyError:
return {"a": [], "h": []}

return self._get_players("saves")

def get_bonus(self):
def get_bonus(self, provisional=False):
"""Returns all players who received bonus points in the fixture.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("bonus")
if self.finished:
return self.stats["bonus"]
elif self.started and provisional:
bps = self.get_bps()
home = [b["element"] for b in bps["h"]]
away = [b["element"] for b in bps["a"]]
bps = bps["a"] + bps["h"]
bps = {b["element"]: b["value"] for b in bps}
bps_values = set(bps.values())

try:
bps_1st = max(bps_values)
bps_values.remove(bps_1st)
bps_2nd = max(bps_values)
bps_values.remove(bps_2nd)
bps_3rd = max(bps_values)
except ValueError:
return {"a": [], "h": []}

else:
bonus_3rd = list(
filter(lambda x: bps[x] == bps_1st, bps.keys()))
bonus_2nd = bonus_1st = []

if len(bonus_3rd) == 1:
bonus_2nd = list(
filter(lambda x: bps[x] == bps_2nd, bps.keys()))
if len(bonus_3rd) + len(bonus_2nd) == 2:
# 2 way tie for 3 bonus
if len(bonus_3rd) == 2:
bonus_1st = list(
filter(lambda x: bps[x] == bps_2nd, bps.keys()))
else:
bonus_1st = list(
filter(lambda x: bps[x] == bps_3rd, bps.keys()))

bonus_3rd = [{"value": 3, "element": b} for b in bonus_3rd]
bonus_2nd = [{"value": 2, "element": b} for b in bonus_2nd]
bonus_1st = [{"value": 1, "element": b} for b in bonus_1st]
bonus = bonus_3rd + bonus_2nd + bonus_1st

h = []
a = []

for b in bonus:
if b["element"] in home:
h.append(b)
elif b["element"] in away:
a.append(b)

return {"a": a, "h": h}
else:
return {"a": [], "h": []}

def get_bps(self):
"""Returns the bonus points of each player.

:rtype: dict
"""
if not getattr(self, "finished", False):
return {}

return self._get_players("bps")
try:
return self.stats["bps"]
except KeyError:
return {"a": [], "h": []}

def __str__(self):
return (f"{team_converter(self.team_h)} vs. "
f"{team_converter(self.team_a)} - "
f"{self.deadline_time_formatted}")
f"{self.kickoff_time}")
Loading