-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadvisor.py
More file actions
414 lines (358 loc) · 13.7 KB
/
advisor.py
File metadata and controls
414 lines (358 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
# advisor.py
#
# "Roll vs Level" Expected Value advisor for TFT.
# This is the core "Moneyball" feature: given current game state, should
# the player spend gold rolling at their current level, or save gold to
# level up first (improving tier odds)?
import math
from typing import Dict, List, Tuple, Any
from probability import calculate_shop_odds, POOL_SIZES, SHOP_ODDS
# Gold cost per shop reroll
GOLD_PER_ROLL = 2
# Number of shop slots revealed per roll
SLOTS_PER_SHOP = 5
# Gold cost for 4 XP (the buy-XP button gives 4 XP for 4 gold)
GOLD_PER_XP_BUY = 4
XP_PER_BUY = 4
def _prob_at_least_one_in_shop(
level: int,
tier: int,
units_gone_for_champion: int,
total_tier_units_gone: int,
num_champions_in_tier: int,
) -> float:
"""
Thin wrapper around the existing probability module.
Returns the probability of seeing at least one copy of a specific
champion in a single 5-slot shop at the given level.
Returns 0.0 if the tier is not available at this level.
"""
try:
return calculate_shop_odds(
level=level,
tier=tier,
units_gone_for_champion=units_gone_for_champion,
total_tier_units_gone=total_tier_units_gone,
num_champions_in_tier=num_champions_in_tier,
)
except ValueError:
return 0.0
def calculate_roll_ev(
level: int,
tier: int,
units_gone_for_champion: int,
total_tier_units_gone: int,
num_champions_in_tier: int,
) -> float:
"""
Calculate the expected gold cost to find at least one copy of a
specific champion by rolling at the current level.
The model uses a geometric distribution: if the probability of
hitting the unit in a single shop (roll) is p, the expected number
of rolls is 1/p. Each roll costs 2 gold.
Args:
level: Player's current level (1-10).
tier: Cost tier of the target champion (1-5).
units_gone_for_champion: Copies of the specific champion already
taken from the shared pool.
total_tier_units_gone: Total copies of ANY champion in this tier
removed from the pool.
num_champions_in_tier: Number of unique champions in the tier.
Returns:
Expected gold cost to hit the unit. Returns float('inf') when
the probability is 0 (unit cannot appear at this level/tier).
"""
p = _prob_at_least_one_in_shop(
level, tier, units_gone_for_champion,
total_tier_units_gone, num_champions_in_tier,
)
if p <= 0:
return float("inf")
expected_rolls = 1.0 / p
return expected_rolls * GOLD_PER_ROLL
def _gold_to_level_up(current_level: int, xp_to_next_level: int) -> float:
"""
Calculate the gold required to buy enough XP to reach the next level.
Args:
current_level: The player's current level.
xp_to_next_level: How much more XP is needed to level up.
Returns:
Gold cost, or float('inf') if leveling is impossible (already 10).
"""
if current_level >= 10:
return float("inf")
if xp_to_next_level <= 0:
return 0.0
# Each buy gives XP_PER_BUY xp for GOLD_PER_XP_BUY gold.
# We need ceil(xp_to_next_level / XP_PER_BUY) purchases.
purchases = math.ceil(xp_to_next_level / XP_PER_BUY)
return purchases * GOLD_PER_XP_BUY
def calculate_level_ev(
level: int,
gold_to_level: float,
tier: int,
units_gone_for_champion: int,
total_tier_units_gone: int,
num_champions_in_tier: int,
) -> float:
"""
Calculate the expected total gold cost if the player levels up first,
then rolls for the target champion at the new (higher) level.
Total cost = gold spent leveling + expected rolling cost at new level.
Args:
level: Current level (1-10).
gold_to_level: Gold required to reach the next level.
tier: Cost tier of the target champion (1-5).
units_gone_for_champion: Copies of the champion already taken.
total_tier_units_gone: Total copies of this tier removed from pool.
num_champions_in_tier: Unique champions in the tier.
Returns:
Expected total gold cost (leveling + rolling at new level).
Returns float('inf') if leveling is impossible or the champion
still cannot appear at the new level.
"""
if level >= 10:
return float("inf")
new_level = level + 1
p_new = _prob_at_least_one_in_shop(
new_level, tier, units_gone_for_champion,
total_tier_units_gone, num_champions_in_tier,
)
if p_new <= 0:
return float("inf")
expected_rolls_new = 1.0 / p_new
rolling_cost_new = expected_rolls_new * GOLD_PER_ROLL
return gold_to_level + rolling_cost_new
def _compute_aggregate_ev(
level: int,
target_champions: List[Tuple[str, int]],
units_gone: Dict[str, Dict[str, int]],
champions_by_tier: Dict[str, List[str]],
use_level: int = None,
) -> float:
"""
Compute the combined expected gold cost to hit ALL target champions
at a given level. This is a simplified additive model -- the true
joint EV would require simulation, but summing individual EVs is a
good heuristic for decision-making.
Args:
level: The base level (used if use_level is None).
target_champions: List of (champion_name, tier) the player wants.
units_gone: Nested dict tier_str -> champion_name -> count.
champions_by_tier: Dict tier_str -> list of champion names.
use_level: If provided, compute EV at this level instead.
Returns:
Sum of expected gold costs for each target champion.
"""
eval_level = use_level if use_level is not None else level
total_ev = 0.0
for champ_name, tier in target_champions:
tier_str = f"{tier}-cost"
tier_champs = champions_by_tier.get(tier_str, [])
num_champs_in_tier = len(tier_champs) if tier_champs else 1
tier_gone = units_gone.get(tier_str, {})
champ_gone = tier_gone.get(champ_name, 0)
total_tier_gone = sum(tier_gone.values())
p = _prob_at_least_one_in_shop(
eval_level, tier, champ_gone, total_tier_gone, num_champs_in_tier,
)
if p <= 0:
total_ev += float("inf")
else:
total_ev += (1.0 / p) * GOLD_PER_ROLL
return total_ev
def get_roll_or_level_advice(
level: int,
gold: int,
xp_to_next_level: int,
target_champions: List[Tuple[str, int]],
units_gone: Dict[str, Dict[str, int]],
champions_by_tier: Dict[str, List[str]],
) -> Dict[str, Any]:
"""
Main entry point. Given the current game state, recommend whether
the player should ROLL at the current level, LEVEL UP first, or SAVE
gold because neither option provides good expected value.
Args:
level: Player's current level (1-10).
gold: Current gold.
xp_to_next_level: XP still needed to reach the next level.
target_champions: List of (champion_name, tier) tuples the player
wants to find.
units_gone: Nested dict { "N-cost": { "ChampName": count, ... } }
reflecting how many copies of each champion have been taken
from the shared pool.
champions_by_tier: Dict { "N-cost": [list of champion names] }.
Returns:
Dict with keys:
action: "ROLL" | "LEVEL" | "SAVE"
reasoning: Human-readable explanation string.
roll_ev: Expected gold cost to hit targets rolling now.
level_ev: Expected gold cost to hit targets after leveling.
confidence: "high" | "medium" | "low"
"""
# ---- Handle degenerate inputs ----
if not target_champions:
return {
"action": "SAVE",
"reasoning": "No target champions specified. Save gold until you identify units to chase.",
"roll_ev": float("inf"),
"level_ev": float("inf"),
"confidence": "high",
}
# ---- Compute ROLL EV at current level ----
roll_ev = _compute_aggregate_ev(
level, target_champions, units_gone, champions_by_tier,
use_level=level,
)
# ---- Compute LEVEL EV (level-up cost + rolling at next level) ----
gold_needed_to_level = _gold_to_level_up(level, xp_to_next_level)
if gold_needed_to_level == float("inf"):
# Already level 10 or cannot level further
level_ev = float("inf")
else:
roll_ev_at_next_level = _compute_aggregate_ev(
level, target_champions, units_gone, champions_by_tier,
use_level=level + 1,
)
level_ev = gold_needed_to_level + roll_ev_at_next_level
# ---- Decision logic ----
action, reasoning, confidence = _decide(
roll_ev, level_ev, gold, gold_needed_to_level, level, target_champions,
)
return {
"action": action,
"reasoning": reasoning,
"roll_ev": roll_ev,
"level_ev": level_ev,
"confidence": confidence,
}
def _decide(
roll_ev: float,
level_ev: float,
gold: int,
gold_to_level: float,
level: int,
target_champions: List[Tuple[str, int]],
) -> Tuple[str, str, str]:
"""
Internal decision engine. Compares roll EV and level EV against the
player's current gold to produce an action, reasoning string, and
confidence level.
Returns:
(action, reasoning, confidence)
"""
both_inf = (roll_ev == float("inf") and level_ev == float("inf"))
# --- Case 1: Neither option is viable ---
if both_inf:
return (
"SAVE",
"Target champions cannot be found at your current level or the "
"next level. Save gold and reassess your targets.",
"high",
)
# --- Case 2: Very low gold (cannot meaningfully roll or level) ---
min_actionable_gold = GOLD_PER_ROLL # need at least 2g to roll once
if gold < min_actionable_gold:
return (
"SAVE",
f"Only {gold}g available. Save gold until you can afford to "
f"roll or level.",
"high",
)
# --- Case 3: Compare EVs ---
# Determine which is cheaper
roll_is_cheaper = roll_ev <= level_ev
cheaper_ev = min(roll_ev, level_ev)
costlier_ev = max(roll_ev, level_ev)
# Compute how decisive the gap is
if costlier_ev == float("inf"):
ratio = float("inf")
elif cheaper_ev <= 0:
ratio = float("inf")
else:
ratio = costlier_ev / cheaper_ev
# Confidence thresholds
if ratio >= 2.0 or costlier_ev == float("inf"):
confidence = "high"
elif ratio >= 1.3:
confidence = "medium"
else:
confidence = "low"
# Build target description for messaging
target_names = ", ".join(name for name, _ in target_champions)
# --- Sub-case: rolling is impossible but leveling works ---
if roll_ev == float("inf") and level_ev < float("inf"):
can_afford_level = gold >= gold_to_level
if can_afford_level:
return (
"LEVEL",
f"Cannot find [{target_names}] at level {level}. "
f"Level up for {gold_to_level:.0f}g to unlock better odds "
f"(expected {level_ev:.0f}g total).",
"high",
)
else:
return (
"SAVE",
f"Cannot find [{target_names}] at level {level} and you "
f"need {gold_to_level:.0f}g to level up (you have {gold}g). "
f"Save gold to level first.",
"high",
)
# --- Sub-case: leveling is impossible but rolling works ---
if level_ev == float("inf") and roll_ev < float("inf"):
return (
"ROLL",
f"Already at max level or leveling does not improve odds. "
f"Roll now -- expected cost {roll_ev:.0f}g for [{target_names}].",
confidence,
)
# --- Sub-case: both are finite ---
if roll_is_cheaper:
if gold < roll_ev:
return (
"ROLL",
f"Roll now for [{target_names}] (expected ~{roll_ev:.0f}g, "
f"you have {gold}g). Odds are better at current level "
f"({roll_ev:.0f}g) vs leveling first ({level_ev:.0f}g), "
f"but you may run out of gold.",
confidence,
)
return (
"ROLL",
f"Roll now for [{target_names}]. Expected cost ~{roll_ev:.0f}g "
f"at level {level} vs ~{level_ev:.0f}g if you level first.",
confidence,
)
else:
# Leveling is cheaper
can_afford_level = gold >= gold_to_level
if can_afford_level:
return (
"LEVEL",
f"Level up first for [{target_names}]. Expected total cost "
f"~{level_ev:.0f}g (level {gold_to_level:.0f}g + roll "
f"~{level_ev - gold_to_level:.0f}g at level {level + 1}) "
f"vs ~{roll_ev:.0f}g rolling at level {level}.",
confidence,
)
else:
if gold >= roll_ev * 0.5:
return (
"ROLL",
f"Leveling first would be cheaper (~{level_ev:.0f}g vs "
f"~{roll_ev:.0f}g) but you need {gold_to_level:.0f}g "
f"to level (have {gold}g). Rolling now is your best "
f"available option for [{target_names}].",
"low",
)
else:
return (
"SAVE",
f"Leveling first would be optimal (~{level_ev:.0f}g) but "
f"you need {gold_to_level:.0f}g (have {gold}g). Rolling "
f"at current level costs ~{roll_ev:.0f}g which is also "
f"too expensive. Save gold.",
confidence,
)