Skip to content

Commit

Permalink
difficulty, first pb integration
Browse files Browse the repository at this point in the history
  • Loading branch information
ccev committed Dec 30, 2021
1 parent a52dd93 commit 6f40939
Show file tree
Hide file tree
Showing 8 changed files with 77 additions and 75 deletions.
5 changes: 5 additions & 0 deletions locale/english.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
"mega_egg": "Mega Egg",
"Help": "Help",
"shadow": "Shadow",
"difficulty_1": "🟥 Impossible",
"difficulty_2": "🟧 Hard",
"difficulty_3": "🟨 Medium",
"difficulty_4": "🟩 Easy",
"difficulty_5": "🟦 Very easy",
"context_stats_desc": "Show this player's stats",
"command_stats_desc": "Show a linked player's stats",
"command_stats_trainer_desc": "Leave empty to view your own stats",
Expand Down
5 changes: 5 additions & 0 deletions locale/german.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
"mega_egg": "Mega Ei",
"Help": "Hilfe",
"shadow": "Crypto",
"difficulty_1": "🟥 Nicht möglich",
"difficulty_2": "🟧 Schwer",
"difficulty_3": "🟨 Medium",
"difficulty_4": "🟩 Einfach",
"difficulty_5": "🟦 Sehr einfach",
"context_stats_desc": "Zeigt die Stats von diesem Spieler",
"command_stats_desc": "Zeigt die Stats von einem gelinkten Spieler",
"command_stats_trainer_desc": "Leer lassen, um deine eigenen Stats zu zeigen",
Expand Down
3 changes: 2 additions & 1 deletion taubsi/cogs/raids/raid_cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ async def create_raid(self, raidmessage: RaidMessage):
raidmessage.make_warnings()
self.raidmessages[raidmessage.message.id] = raidmessage
self.bot.loop.create_task(raidmessage.set_image())
self.bot.loop.create_task(raidmessage.set_pokebattler())

emojis = []
for number in range(1, 7):
Expand Down Expand Up @@ -200,7 +201,7 @@ async def raid_loop(self):
raidmessage.gym.raid.boss.name))

raidmessage.raid = raidmessage.gym.raid.copy()
await raidmessage.make_base_embed()
raidmessage.make_base_embed()
await raidmessage.set_image()
await raidmessage.db_insert()
except Exception as e:
Expand Down
99 changes: 27 additions & 72 deletions taubsi/cogs/raids/raidmessage.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
from taubsi.utils.utils import asyncget, reverse_get
from taubsi.cogs.raids.raidmember import RaidMember
from taubsi.core import bot, Gym, Raid, Team, log
from taubsi.pokebattler.models import Difficulty

if TYPE_CHECKING:
from datetime import datetime
from taubsi.core import RaidChannel
from taubsi.pokebattler.models import RaidPayload

timeformat = bot.translate("timeformat_short")

Expand Down Expand Up @@ -129,7 +131,8 @@ def __init__(self, raidmessage):
async def pokebattler(self, _, interaction: discord.Interaction):
pb = await bot.pokebattler.get(self.raidmessage.raid.boss, self.raidmessage.raid.level)
attackers = pb.best_attackers
text = "\n".join([a.pokemon.name for a in attackers])
text = str(pb.get_difficulty(self.raidmessage.total_amount))
text += "\n".join([a.pokemon.name for a in attackers])
await interaction.response.send_message(text)


Expand All @@ -155,6 +158,9 @@ class RaidMessage:
remotes: List[int]
lates: List[int]

pokebattler: Optional[RaidPayload]
difficulty: Difficulty

notified_5_minutes: bool = False

def __init__(self, gym: Gym, start: arrow.Arrow, channel_id: int):
Expand All @@ -173,6 +179,8 @@ def __init__(self, gym: Gym, start: arrow.Arrow, channel_id: int):
self.lates = []
self.warnings = set()
self.static_warnings = set()
self.difficulty = Difficulty.UNKNOWN
self.pokebattler = None

@classmethod
async def from_slash(cls, gym: Gym, start_time: arrow.Arrow, interaction: discord.Interaction) -> RaidMessage:
Expand Down Expand Up @@ -228,6 +236,9 @@ async def from_db(cls, channel_id: int, message_id: int, init_message_id: int, s
self.message = message
self.role = self.message.guild.get_role(role_id)

await self.set_pokebattler()
self.set_difficulty()

try:
self.init_message = await channel.fetch_message(init_message_id)
self.author_id = self.init_message.author.id
Expand Down Expand Up @@ -356,75 +367,15 @@ async def notify(self, message: str, user: Optional[discord.User] = None) -> NoR

await member.member.send(embed=embed)

async def get_difficulty(self):
# unused
if not self.raid.boss:
return None
try:
pb_mon_name = self.raid.boss.base_template
if self.raid.boss.temp_evolution_id > 0:
pb_mon_name += "_" + self.raid.boss.temp_evolution_template
path = f"config/pokebattler/{pb_mon_name}.json"
try:
with open(path, "r") as f:
pb_data = json.load(f)
except FileNotFoundError:
if self.raid.level == 6:
level = "MEGA"
else:
level = self.raid.level
url = f"https://fight.pokebattler.com/raids/defenders/{pb_mon_name}/levels/RAID_LEVEL_{level}/" \
f"attackers/levels/35/strategies/CINEMATIC_ATTACK_WHEN_POSSIBLE/DEFENSE_RANDOM_MC" \
f"?sort=ESTIMATOR&weatherCondition=NO_WEATHER&dodgeStrategy=DODGE_REACTION_TIME" \
f"&aggregation=AVERAGE&randomAssistants=-1&includeLegendary=true&includeShadow=false" \
f"&attackerTypes=POKEMON_TYPE_ALL"
pb_data_raw = await asyncget(url)
pb_data_raw = json.loads(pb_data_raw.decode("utf-8"))
pb_data = {}

attackers = pb_data_raw["attackers"][0]
for data in attackers["byMove"]:
move1 = data["move1"]
move2 = data["move2"]
pb_data[move1 + "+" + move2] = data["total"]
pb_data["?"] = attackers["randomMove"]["total"]

with open(path, "w+") as f:
f.write(json.dumps(pb_data))

if not self.raid.is_scanned or not self.raid.moves[0]:
estimator = pb_data["?"]
else:
estimator = pb_data["+".join([m.proto_id for m in self.raid.moves])]

estimator = estimator["estimator"]

if self.total_amount < estimator:
if self.total_amount < estimator - 0.3:
difficulty = 0
else:
difficulty = 1
else:
if self.total_amount <= ceil(estimator):
difficulty = 2
elif self.total_amount <= ceil(estimator) + 1:
difficulty = 3
else:
difficulty = 4

if self.total_amount < floor(estimator):
difficulty = 0

if self.total_amount == 0:
difficulty = 0

return ""
self.embed.color = DIFFICULTY_COLORS[difficulty]
return DIFFICULTY_NAMES[difficulty] + "\n\n"
def set_difficulty(self):
if self.raid.boss and self.pokebattler:
self.difficulty = self.pokebattler.get_difficulty(self.total_amount)
else:
self.difficulty = Difficulty.UNKNOWN

except Exception as e:
log.exception(e)
return None
async def set_pokebattler(self):
if self.raid.boss:
self.pokebattler = await bot.pokebattler.get(self.raid.boss, self.raid.level)

def make_warnings(self) -> NoReturn:
self.embed.description = self.text
Expand Down Expand Up @@ -456,7 +407,11 @@ async def set_image(self) -> NoReturn:
await self.edit_message()

def make_footer(self, amount: int = 0) -> NoReturn:
self.embed.set_footer(text=f"{self.footer_prefix}{bot.translate('Total')}: {amount}")
if self.difficulty.value > 0:
difficulty = " | " + bot.translate(f"difficulty_{self.difficulty.value}")
else:
difficulty = ""
self.embed.set_footer(text=f"{self.footer_prefix}{bot.translate('Total')}: {amount}{difficulty}")

async def make_member_fields(self) -> NoReturn:
self.embed.clear_fields()
Expand All @@ -482,8 +437,6 @@ async def make_member_fields(self) -> NoReturn:
field_value += member.make_text()
self.embed.insert_field_at(index=index, name=field_name, value=field_value, inline=False)

self.make_footer(self.total_amount)

self.warnings.clear()

total_remote = sum(m.amount for m in self.members if m.is_remote)
Expand All @@ -500,6 +453,8 @@ async def make_member_fields(self) -> NoReturn:
self.warnings.add(bot.translate("warn_is_late"))

self.make_warnings()
self.set_difficulty()
self.make_footer(self.total_amount)
await self.edit_message()

async def db_insert(self) -> NoReturn:
Expand Down
5 changes: 3 additions & 2 deletions taubsi/pogodata/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,8 @@ def __init__(self, language: str, raw_protos: str, raw_gamemaster: List[dict], r
self.mons[f"{mon_id}:0:{mega_id}"] = v
elif k.startswith("move_name_"):
self.moves[int(k[10:])] = v
elif k == "filter_key_shadow":
self.shadow_translation = v.title()
elif k == "filter_label_shadow":
self.shadow_translation = v

result = []
for entry in raw_gamemaster:
Expand All @@ -85,6 +85,7 @@ def __init__(self, language: str, raw_protos: str, raw_gamemaster: List[dict], r
base_stats = BaseStats(list(stats.values()))
identifier = f"{mon_id}:{form_id}"
self.base_stats[f"{identifier}:0"] = base_stats
print(self.base_stats)

mega_overrides: Optional[List[dict]] = settings.get("tempEvoOverrides")
if not mega_overrides:
Expand Down
1 change: 1 addition & 0 deletions taubsi/pogodata/pokemon.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def __init__(self, id_: int, pogodata: PogoData, form: int = 0, costume: int = 0
else:
self.proto_form = ""

print(self.id, self.form_id)
self.base_stats = pogodata.base_stats.get(f"{self.id}:{self.form_id}:0")
if not self.base_stats:
self.base_stats = pogodata.base_stats.get(f"{self.id}:0:0")
Expand Down
1 change: 1 addition & 0 deletions taubsi/pokebattler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

if TYPE_CHECKING:
from taubsi.pogodata import PogoData, Pokemon
from taubsi.core.pogo import Raid


BASE_URL = "https://fight.pokebattler.com/raids/defenders/{}/levels/RAID_LEVEL_{}/attackers/levels/40/strategies/" \
Expand Down
33 changes: 33 additions & 0 deletions taubsi/pokebattler/models.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
from pydantic import BaseModel, validator, PrivateAttr
from typing import Optional, List
from enum import Enum
import math
from arrow import Arrow

from taubsi.core import bot
from taubsi.core.pogo import Moveset
from taubsi.pogodata import Pokemon


class Difficulty(Enum):
UNKNOWN = 0
IMPOSSIBLE = 1
HARD = 2
MEDIUM = 3
EASY = 4
VERY_EASY = 5


class _BaseModel(BaseModel):
@validator("*")
def list_reverse(cls, v):
Expand Down Expand Up @@ -115,3 +126,25 @@ def best_attackers(self) -> List[Defender]:
@property
def estimator(self) -> float:
return self.attackers[0].randomMove.total.estimator

def get_difficulty(self, players: int) -> Difficulty:
if players < self.estimator:
if players < self.estimator - 0.3:
difficulty = Difficulty.IMPOSSIBLE
else:
difficulty = Difficulty.HARD
else:
if players <= math.ceil(self.estimator):
difficulty = Difficulty.MEDIUM
elif players <= math.ceil(self.estimator) + 1:
difficulty = Difficulty.EASY
else:
difficulty = Difficulty.VERY_EASY

if players < math.floor(self.estimator):
difficulty = Difficulty.IMPOSSIBLE

if players == 0:
difficulty = Difficulty.IMPOSSIBLE

return difficulty

0 comments on commit 6f40939

Please sign in to comment.